24👍
You could define a custom InlineModelAdmin
like so:
class BarInline(admin.TabularInline):
model = Bar.foos.through
and use it in your FooAdmin
:
class FooAdmin(admin.ModelAdmin):
"""Foo admin."""
model = Foo
inlines = [
BarInline,
]
Have a look at this part of the django documentation.
4👍
You can define custom fields for list_display
like this:
@admin.register(Foo)
class FooAdmin(admin.ModelAdmin):
"""Foo admin."""
list_display = ('name', 'get_bars')
search_fields = ('name',)
def get_bars(self, obj):
return obj.bars.all()
This is a very simple example, but I hope it can help you as a starting point.
EDIT:
You can display the associated objects in the edit form as readonly:
readonly_fields = ('get_bars',)
fields = ('name', 'get_bars')
1👍
This code below can display both Foo
and Bar
models in many-to-many relationship on the same page in Django Admin:
class BarInline(admin.TabularInline):
model = Bar.foos.through
@admin.register(Foo)
class FooAdmin(admin.ModelAdmin):
inlines = (BarInline,)
Be careful, if using model = Bar
instead of model = Bar.foos.through
in many-to-many relationship as shown below:
class BarInline(admin.TabularInline):
# model = Bar.foos.through
model = Bar # This will get error
@admin.register(Foo)
class FooAdmin(admin.ModelAdmin):
inlines = (BarInline,)
You will get the error below:
ERRORS: <class ‘xxx.admin.BarInline’>: (admin.E202)
‘xxx.Bar’ has no ForeignKey to ‘xxx.Foo’.
- Django request.user.is_superuser doesn't work
- Override create method in django rest generics CreateAPIView
- Django: admin interface: how to change user password
- Can I create model in Django without automatic ID?
0👍
There is a module called django-admin-extend which provides a generic mechanism to define “Bidirectional many to many fields”. I’m not sure if it still works, because the last contribution is two years old, bit it should be worth giving it a try.
- Does Django cache related ForeignKey and ManyToManyField fields once they're accessed?
- Django __call__() missing 1 required keyword-only argument: 'manager'
- How to customize django rest auth password reset email content/template
- Best way to denormalize data in Django?