I need to pre-populate a formset field with a user's saved data
Here is my 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='')
As you can see, I added a field to accept answers in the EssayQuestionFormSet
My views.py looks like following:
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))
Currently, the view properly renders empty Textarea field for the answer field on the get and properly saves answers on the post. My question, however, **how can I pre-populate the answer field with user's saved answer?**
Here is the Answer model
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)
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5c18b614-5fe8-4230-a340-05c3144a68dc%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment