juju
juju

Reputation: 994

How to update multiple rows at once using Django forms.ModelForm in views.py

I am trying to update many rows of a model based on user input but I'm having trouble updating them in views.py.

I create the modelForm

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ["book_title", "book_title_2"]

In my views

def my_view(request):
    query = MyModel.objects.filter(foo=foo)
    forms = [MyForm(instance=q) for q in query]
    context["forms"] = forms

In templates I iterate over forms and input data for some rows. I know normally on form submission I can use form = MyForm(request.POST) and use the is_valid() and save() attributes to save new data to my model. But when I am using a list of forms like above to update many instances, how can I actually save the forms in views.py? When I call MyForm(request.POST) after submitting all of the queried forms at once I get this error 'WSGIRequest' object has no attribute 'FORM' . When I look at the post data I see a list values for book_title and book_title_2. It seems that because I'm submitting more than one form it doesn't work. Is there a workaround for this? Thanks

Upvotes: 1

Views: 734

Answers (1)

juju
juju

Reputation: 994

As posted in the comments by Willem Formsets is exactly what is needed to handle multiple form in views. In my case specifically where I am making multiple forms based on a model and a queryset of that model, modelformset_factory worked

Upvotes: 1

Related Questions