Django - Creating Form For Editing Multiple Instance Of Model
Note: Django/Python beginner, hope this question is clear I need to create a form where multiple instances of a model can be edited at once in a single form, and be submitted at th
Solution 1:
You need to use a FormSet
, in particular a ModelFormSet:
...
GuestFormSet = modelformset_factory(Guest, form=ExtraForm)
in your view you can use it as a normal form:
formset = GuestFormSet(data=request.POST)
if formset.is_valid():
formset.save()
and in your template:
<formmethod="post"action="">
{{ formset.management_form }}
<table>
{% for form in formset %}
{{ form }}
{% endfor %}
</table></form>
tip: you can avoid the avoid this boilerplate
if request.method == 'POST':
form = ExtraForm(request.POST)
print(form.data)
# Have we been provided with a valid form?if form.is_valid():
with a simple shortcut:
form = ExtraForm(data=request.POST or None)
if form.is_valid():
...
Post a Comment for "Django - Creating Form For Editing Multiple Instance Of Model"