我使用 Django 和模型表单集。它是一个非常基本的多项选择题模型。创建问题的表单成功地使用了模型表单集和常规表单 - 问题的常规表单和可能答案的表单集。这部分正在工作。
但是,如何创建一个“编辑”版本呢?我想查询我当前为给定问题保存的答案,并将它们绑定到表单集中的每个表单。
谢谢,迈克
模型:
class Question(models.Model):
title = models.CharField(...)
text = models.TextField(...)
time_allowed = models.DecimalField(...)
class Answer(models.Model):
uuid = models.CharField(...)
question = models.ForeignKey(QuestionDetail, ...)
text = models.TextField()
weight = models.DecimalField(...)
表格:
class QuestionModelForm(forms.ModelForm):
required_css_class = 'required'
class Meta:
model = QuestionDetail
widgets = {
'text': forms.Textarea(attrs={'rows': 3, 'class': 'question-text'})
}
class AnswerModelForm(forms.ModelForm):
required_css_class = 'required'
class Meta:
widgets = {
'text': forms.Textarea(attrs={'rows': '3', 'class': 'question-text'}),
'weight': forms.TextInput(attrs={'maxlength':'5', 'class': 'question-weight'}),
}
class BaseAnswerFormSet(BaseFormSet):
def __init__(self, *args, **kwargs):
super(BaseAnswerFormSet, self).__init__(*args, **kwargs)
# Must have at least two answers.
self.forms[0].empty_permitted = False
self.forms[1].empty_permitted = False
AnswerFormSet = modelformset_factory(Answer, formset=BaseAnswerFormSet, form=AnswerModelForm)