[Answer]-How to get all the data from form at once and save in database in Django?

1👍

Let’s imagine you’ve a Django model form class (you cannot save in DB directly a simple form since there is no corresponding schema, but you can with a model form)

class MyForm(forms.ModelForm):
  field1 = forms.IntegerField(...)
  ...

You rendered it in a template with {{ form.as_p }}

Then in the reception view, do the following:

def myview(request):
  if request.method == "POST":
    form = MyForm(request.POST)
    if form.is_valid():
      form.save() # here you save the form all at once
    else:
      ... # here return the "form" to the template, and render it with form.as_p: it will display the validation errors
  else:
    ... # here treat the get request. If not get: return an Http 404 response

Leave a comment