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

标签 python django django-forms

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

从类似的问题中,我了解到子类化 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

有帮助吗?

关于python - 如何从外键关系创建 Django 表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11117730/

相关文章:

python - 如何将地址模型链接到 View

python - 增加 matplotlib 字符串字体大小

python - 字符串聚类算法 - 指导

python - 属性错误 : 'Flask' object has no attribute 'user_options'

django - 在 Wagtail 中以编程方式创建草稿页面的正确方法是什么?

Django 日志记录 - 未找到处理程序的日志文件

python - 在 Django 中哪里可以翻译表单字段标签?

python - Itertools - 合并两个列表以获得所有可能的组合

django - 如何在 Django 的 TestCase 中使用 session ?

django - ModelChoiceField,删除空白选择