formset_factory包含具有不同初始数据的表单

时间:2014-03-07 18:21:39

标签: django forms django-views django-forms

我正在编写一个使用POST数据显示具有不同预填充FK的多个表单的视图

我在forms.py

中有一个ModelForm
class SurveyForm(forms.ModelForm):
    class Meta:
        model = Survey

谁的模特看起来像这样......

class Survey(models.Model):
    student = models.ForeignKey(Student)
    surveyset = models.ForeignKey(SurveySet)

    cei_0  = models.BooleanField()
    cei_1  = models.BooleanField()

到目前为止,我的观点有点像这样

# ... after building a list from POST we essentially have:
list_of_studentids = [1,3,2,6,7,45]

students = []
for i in list_of_student_ids:
    students.append(Student.objects.filter(id=i))

SurveyFormSet = formset_factory(SurveyForm, extra=6)

formset = SurveyFormSet(initial=[
    {'surveyset': SurveySet.create(),
    'student': ?????,}
])

如何使用不同的学生FK和相同的调查集FK返回一堆表格?

1 个答案:

答案 0 :(得分:0)

您需要将instance属性传递给表单:

prefilled_survey = Survey(student=student_instance, surveyset=surveyset_instance)
form = SurveyForm(request.POST or None, instance=prefilled_survey)