Skip to main content
 首页 » 编程设计

python之如何从外键关系创建 Django 表单

2025年05月04日32jiqing9006

我想创建一个多项选择题表单,其中外键指向该问题的所有选项都显示为复选框。

从类似的问题中,我了解到子类化 ModelForms 可能是实现此目的的方法。但我不知道如何将特定的 question_id 传递给 ModelForm。

目前,我正在尝试以下操作:

来自 model.py:

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 

所以在 forms.py 中,我尝试创建这样一个表单:

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)) 

在 views.py 中,我创建了一个 QuestionForm,将 question_id 作为构造函数参数传递。 但是我在构造 MODelChoiceField 的 QuestionForm 中不断收到 NameError "name 'question_id' is not defined。

请您参考如下方法:

docs谈谈元类:

class ArticleForm(ModelForm): 
    class Meta: 
        model = Article 

有帮助吗?