Dynamic form for 1:M:N model

Is it possible to create a single-page “Order form” for 1:M:N model?

class Topping(models.Model):
    name = models.CharField(max_length=100)
    type = models.CharField(max_length=100)
    amount = models.FloatField(validators=[MinValueValidator(0.1), MaxValueValidator(9999.0)])

class Pizza(models.Model):
    box_label = models.CharField(max_length=100)
    box_type = models.PositiveSmallIntegerField(validators=[MinValueValidator(1), MaxValueValidator(999)])
    toppings = models.ManyToManyField(Topping,blank=True)

class Order(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    code = models.CharField(max_length=100)
    pizzas = models.ManyToManyField(Pizza, blank=True)

I would like to fill all form fields on a single page and save it in single submit (without AJAX). Pizzas and their Toppings can be added/removed dynamically(using javascript).

One “quick-and-dirty” solution is submit it as “plain HTML form” and handle POST parameters manually - without “django-form” features like validations, automatic binding, etc, but I would like to use django’s form features which are very handy.

Yes, you can nest formsets. (Or, more accurately, you can have a formset that uses a form that has a formset as a field within it.) You just need to be very careful with the id attributes being created for the new entries being added by your javascript.

We do this in one of our projects. We have a view that will create the “skeleton html” for a new “Pizza” that contains the formset for the “Topping”. The JavaScript will make an ajax call to that view on an insert.

[Side note: I’m curious about the use of ManyToMany fields here, typically, this type of data structure is represented by a ForeignKey in Pizza to Order, and a ForeignKey in Topping to Pizza.]

Hi, nested formsets looked too complicated. I solved this problem with custom form objects, which were not as complicated as I thought (couple of boilerplate code for request parameters binding but OK).

To your question about ManyToMany fields: I am Django newbie, so I thought using this relationship I can easily access “master-detail” values. Now I know, Django provides “something_set” collection on master object for details objects in OneToMany relationship, what was exactly what I was looking for.

Now, I finished this simple project and I can say, Django is really very interesting and powerful framework for rapid web app development.