gemasr
gemasr

Reputation: 187

Post Django formset via AJAX

Here, a newbie to django.

I am using formsets in Django as part of a step in a wizard process and I would like to submit them once the process has been finished (not via the classic submit). I would like to send it along with another data via POST using Javascript.

Is there another way than serializing one by one all the forms and send them in a json array "manually"? Is it posible to send them as "formset"?

Example of what I have:

in views.py

formset = formset_factory(CustomerForm, extra=customer_number)
return render (request, 'customer/customer_info.html', {'customerformset':formset})

in template

{% for form in customerformset %}
{{form}}
{% endfor %}

in rendered html

<input class="form-control input-sm" maxlength="30" name="form-0-name" placeholder="Name" required="true" type="text">
<input class="form-control input-sm" maxlength="30" name="form-0-surname" placeholder="Surname" required="true" type="text">
<input class="form-control input-sm" maxlength="30" name="form-0-email" placeholder="Email" required="true" type="text">

Upvotes: 4

Views: 1017

Answers (2)

Danial Tz
Danial Tz

Reputation: 1984

You can use a Form Wizard in django, and each step can have totally different form classes. The information can be stored in either cookie or Session, and once finally submitted (and validated, remember, it is just like any other form) the information will be removed from the session.

class ContactWizard(AccessMixin, NamedUrlSessionWizardView):

Usually the wizard is fine to use, however it can become quite tricky if you want to add e.g. registration/login steps in between.

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599530

Although the forms are separate from the point of view of Django, in the HTML they're all contained within the same <form> element. So you can serialize them in one go:

data = $('form').serialize();

Note that this doesn't convert to JSON, and there is no need to do so: this converts the values to the normal form-encoded data, which can be posted directly and used in Django via the standard request.POST.

Upvotes: 3

Related Questions