预填充formset,用户在重新访问时保存数据

时间:2016-11-23 14:06:50

标签: python django formset

我需要使用用户保存的数据预先填充一个formset字段

这是我的form.py

EssayQuestionFormSetBase = modelformset_factory(models.EssayQuestion,
                                            extra=0,
                                            fields=('prompt',),
                                             widgets={
                                                 'prompt': forms.TextInput(
                                                     attrs={'readonly': True, 'class': 'borderless'}),
                                             },
                                            )

class EssayQuestionFormSet(EssayQuestionFormSetBase):
    def add_fields(self, form, index):
        super(EssayQuestionFormSet, self).add_fields(form, index)
        form.fields['answer'] = forms.CharField(widget=forms.Textarea, label='')

如您所见,我添加了一个字段来接受EssayQuestionFormSet中的答案

我的views.py如下所示:

class QuizDetail(View):

    def get(self, request, **kwargs):

        step = models.Quiz.objects.get(pk=self.kwargs['step_pk'])

        eqs = models.EssayQuestion.objects.filter(quiz_id=self.kwargs['step_pk'])
        eqs_formset = forms.EssayQuestionFormSet(queryset=eqs, prefix='essay')

    def post(self, request, *args, **kwargs):
        step = models.Quiz.objects.get(pk=self.kwargs['step_pk'])   

        eqs = models.EssayQuestion.objects.filter(quiz_id=self.kwargs['step_pk'])
        eqs_formset = forms.EssayQuestionFormSet(request.POST, queryset=eqs, prefix='essay')


        if eqs_formset.is_valid():
            for form in eqs_formset:
                # create a NEW Answer for this form's associated question
                new_answer = models.Answer.objects.create(question=form.instance,
                                                          eq_answer_text=form.cleaned_data.get('answer'),
                                                          student=models.Student.objects.get(user=request.user.pk))                

目前,视图正确地为获取的答案字段呈现空的Textarea字段,并在帖子上正确保存答案。不过,我的问题是如何使用用户保存的答案预先填写答案字段?

这是答案模型

class Answer(models.Model):
    date_answered = models.DateTimeField(default=timezone.now)
    student = models.ForeignKey(Student, blank=True, null=True, related_name='answers')
    question = models.ForeignKey(Question)
    eq_answer_text = models.TextField(blank=False, null=True)

1 个答案:

答案 0 :(得分:0)

是的,你可以通过传递initials.Left手边值名称应该与你想要填充数据的表单字段相同。

initial = {
'question' :answer.question,
'answer':answer.answer,
}
form = AnswerForm(initial=initial)