Reputation: 950
I know it is easy to display fields for foreign keys in the admin area, but how do I display fields for many to many relationships if through is used?
Models.py:
class Pizza(models.Model):
toppings = models.ManyToManyField(Topping, through='PizzaTopping')
class Topping(models.Model):
topping = models.CharField(max_length=255)
class PizzaTopping(models.Model):
pizza = models.ForeignKey(Pizza)
topping = models.ForeignKey(Topping)
Admin.py:
class PizzaAdmin(admin.ModelAdmin):
fieldsets = (
(None, {
'fields': ('toppings')
}),
})
)
This produces the following error:
<class 'pizzas.admin.PizzaAdmin'>: (admin.E013) The value of 'fieldsets[0][1]["fields"]' cannot include the many-to-many field 'toppings' because that field manually specifies a relationship model.
I want to display a box or listbox which allows me to select a topping.
Is this possible?
Thanks
Upvotes: 4
Views: 2143
Reputation: 309039
You can display the toppings as inlines.
from django.contrib import admin
class ToppingInline(admin.TabularInline):
model = PizzaTopping
class Pizza(admin.ModelAdmin):
inlines = [
ToppingInline,
]
exclude = ('toppings',)
See the admin docs on working with many-to-many models for more info.
Upvotes: 6