Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to create a Django form from foreign key relationship?
    text
    copied!<p>I want to create a multiple choice question form where all choices where the foreign key points to that question are displayed as checkboxes.</p> <p>From similar questions, I have gathered that subclassing <code>ModelForms</code> might be the way to do this. But I couldn't figure out how to pass the specific <code>question_id</code> to the <code>ModelForm</code>.</p> <p>Currently, I am trying the following:</p> <p>from <code>model.py</code>:</p> <pre><code>class Question(models.Model): question = models.CharField(max_length=200) creationDate = models.DateTimeField('date published') author = models.ForeignKey(User) def __unicode__(self): return self.question class Choice(models.Model): question = models.ForeignKey(Question) choice = models.CharField(max_length=200) correct = models.BooleanField() def __unicode__(self): return self.choice </code></pre> <p>So in <code>forms.py</code>, I've tried to create such a form:</p> <pre><code>class QuestionForm(forms.Form): def __init__(self, *args, **kwargs): super(QuestionForm, self).__init__(*args, **kwargs) question_id = kwargs.pop('question') self.fields['checkboxes'] = forms.ModelChoiceField( queryset = Choice.objects.filter(question = question_id)) </code></pre> <p>In <code>views.py</code>, I create a <code>QuestionForm</code>, passing the <code>question_id</code> as constructor argument. But I keep getting a <code>NameError "name 'question_id' is not defined</code> in QuestionForm where the MOdelChoiceField is constructed.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload