Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Heterogeneous forms in django formset

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 ?

like image 294
dusual Avatar asked Mar 13 '12 06:03

dusual


1 Answers

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.

like image 98
Igor Avatar answered Nov 05 '22 13:11

Igor