Consider the following models and form:
class Pizza(models.Model):
name = models.CharField(max_length=50)
class Topping(models.Model):
name = models.CharField(max_length=50)
ison = models.ManyToManyField(Pizza, blank=True)
class ToppingForm(forms.ModelForm):
class Meta:
model = Topping
When you view the ToppingForm it lets you choose what pizzas the toppings go on and everything is just dandy.
My questions is: How do I define a ModelForm for Pizza that lets me take advantage of the Many-to-Many relationship between Pizza and Topping and lets me choose what Toppings go on the Pizza?
I guess you would have here to add a new
ModelMultipleChoiceFieldto yourPizzaForm, and manually link that form field with the model field, as Django won’t do that automatically for you.The following snippet might be helpful :
This
PizzaFormcan then be used everywhere, even in the admin :Note
The
save()method might be a bit too verbose, but you can simplify it if you don’t need to support thecommit=Falsesituation, it will then be like that :