Categories
Python Answers

How to add ModelForm for Many-to-Many fields with Python Django?

Spread the love

To add ModelForm for Many-to-Many fields with Python Django, we can add an intermediary table into our database that has the many to many relationships.

For instance, we write

class Pizza(models.Model):
    name = models.CharField(max_length=50)

class Topping(models.Model):
    name = models.CharField(max_length=50)
    ison = models.ManyToManyField(Pizza, through='PizzaTopping')

class PizzaTopping(models.Model):
    pizza = models.ForeignKey(Pizza)
    topping = models.ForeignKey(Topping)

to add the PizzaTopping model that has the pizza and topping fields that references Pizza and Topping.

Then in admin.py, we add

class PizzaToppingInline(admin.TabularInline):
    model = PizzaTopping

class PizzaAdmin(admin.ModelAdmin):
    inlines = [PizzaToppingInline,]

class ToppingAdmin(admin.ModelAdmin):
    inlines = [PizzaToppingInline,]

admin.site.register(Pizza, PizzaAdmin)
admin.site.register(Topping, ToppingAdmin)

to create the PizzaToppingInline class that has model set to PizzaTopping to let us modify PizzaTopping from PizzaAdmin and ToppingAdmin.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *