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