将数据绑定到django模型表单集

时间:2012-11-19 07:59:05

标签: python django django-forms formset

我使用Django和模型formset。它是多项选择题的一个非常基本的模型。成功创建问题的表单使用模型表单集和常规表单 - 问题的常规表单和可能答案的表单集。这部分正在运作。

但是,如何创建此“编辑”版本?我想查询我目前为给定问题保存的答案,并将它们绑定到表单集中的每个表单。

谢谢,迈克

模特:

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)

1 个答案:

答案 0 :(得分:1)

尝试使用queryset关键字参数:

answers_qs = my_question.answer_set
AnswerFormSet = modelformset_factory(Answer,
                                     formset=BaseAnswerFormSet,
                                     form=AnswerModelForm,
                                     queryset=answers_qs)