简体   繁体   中英

How to populate forms in formset with model data?

I got Questions and Answers as models. So on one page users can create a new question and some answers for it. To do so a QuestionModelForm will be loaded and a formset with the desired number of AnswerModelForms:

class AnswerCreateForm(forms.ModelForm):
    answertext = forms.CharField(max_length=500, widget=forms.TextInput(attrs={"class": "max"}), label="Antworttext")
    field_order = ["answertext", "iscorrect"]
#views.py
AnswerFormSet = formset_factory(AnswerCreateForm, extra=ac)
formset = AnswerFormSet(request.POST)

#html template
<form action="" method="post">
        {% csrf_token %}
        {{ formset.management_data }}
        {{ formset.as_p }}
        <input type="submit" value="add question." />
</form>

This formset will be send to the html-Template. So far no problem. Now I want to add the option for the user to edit previously created questions and their answers. When one goes to the edit page I want the same forms loaded as before, but prepopulated with the data of the object to edit. With the question form its no problem, cause I can just do

form_question = QuestionCreateForm(instance=question)

How can I do the same with my formset for the answers? There will be a query to the DB which loads all answer-objects for that question. Then I want to create a formset with the amount of forms as answers were returned and each of those populated with the answer data.

You populate these with the queryset=… parameter [Django-doc] which is the counterpart of the instance=… parameter for a ModelForm :

from django.forms import 

answers = question.answer_set.all()
AnswerFormSet = Answer, form=AnswerCreateForm, extra=ac
formset = AnswerFormSet(request.POST, request.FILES)

You do the same when you create a form for rendering:

from django.forms import 

answers = question.answer_set.all()
AnswerFormSet = Answer, form=AnswerCreateForm, extra=ac
formset = AnswerFormSet()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM