ValueError... "Contestant.contest" must be a "Contest" instance

Viewed 26

I am trying to create a contestant through a model form, each contestant is a foreign key to a contest model, Whenever i try to submit a form to create a new contestant, i get a value error:

Cannot assign "27": "Contestant.contest" must be a "Contest" instance. ```

I have two models, Contest and Contestant in my `models.py`


    ```class Contest(models.Model):
        contest_title = models.CharField(max_length=30)
        contest_post = models.CharField(max_length=100)
    
    
    
    class Contestant(models.Model):
        contest = models.ForeignKey(Contest, on_delete=models.CASCADE, related_name='participating_contest')
        contestant_name = models.CharField(max_length=10, blank=True, null=True)
        contestant_intro = models.CharField(max_length=30, blank=True, null=True)
        contestant_post = models.CharField(max_length=100, blank=True, null=True)

in my urls.py i am trying to pass the Contest primary key (PK) to the form urls.py

    path('contestant/<int:pk>/new/', views.ContestantCreateView.as_view(), name='new-contestant'),

i am using django's createview in my views.py and trying to pass in pk to the form's form_valid function. views.py


    class ContestantCreateView(CreateView):
        model = Contestant
        fields = ['contestant_name', 'contestant_intro', 'contestant_post']
    
        def form_valid(self, form):
            form.instance.contest = self.kwargs.get('pk')
            return super().form_valid(form)

I tried changing my views.py to


    class ContestantCreateView(CreateView):
        model = Contestant
        fields = ['contestant_name', 'contestant_intro', 'contestant_post']
    
        def form_valid(self, form):
            contesting_contest = Contest.objects.get(participating_contest=pk)
            contesting_contest.contest = form.instance.contest
            return super().form_valid(form)

but i got NameError at /contests/contestant/27/new/ name 'pk' is not defined

1 Answers

You should assign it to the contest_id, not the contest since that field expects a Contest object:

class ContestantCreateView(CreateView):
    model = Contestant
    fields = ['contestant_name', 'contestant_intro', 'contestant_post']

    def form_valid(self, form):
        form.instance.contest_id = self.kwargs['pk']
        return super().form_valid(form)
Related