I have a certain problem with Django forms that seems to me should definitely have a solution already written.
I have a couple of different forms that are submitted in the same view something like ...( Sorry just using pseudo code for now )..
class Form1():
#different attributes
class Form2()
#different attributes
<html>
<form>
{{ 1-instance-Form1 }}
{{ 2-instance-Form1 }}
{{ 1-instance-Form2 }}
{{ 2-instance-Form2 }}
</form>
</html>
Apart from that I want to give the user the ability to add a form instance of one of the form classes available through jquery so the form might become
<html>
<form>
{{ 1-instance-Form1 }}
{{ 2-instance-Form1 }}
{{ 1-instance-Form2 }}
{{ 2-instance-Form2 }}
{{ 3-instance-Form2 }}
</form>
</html>
Now while looking for a solution to handle such a problem I came across the concept of Django formset which as the documentation describes is a collection of instances of the same Form class. However as I can see formsets can have the ability to handle heterogeneous forms as well:
With some definitions changed
class BaseHeterogenousFormSet(StrAndUnicode):
def append(form):
#add one more form to the formset
def is_valid():
#run is_valid for each of the forms in the formset
def clean():
#run the clean for each of the forms ...
Is there something wrong with the way I am thinking about this problem ?
You can submit more than one formset to the same view, but you need to avoid name clashing using different prefixes (https://docs.djangoproject.com/en/3.2/topics/forms/formsets/#using-more-than-one-formset-in-a-view)
One formset handles instances of Form1 and another formset handles instances of Form2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With