The Django admin filter_horizontal
setting gives a nice widget for editing a many-to-many relation. But it's a special setting that wants a list of fields, so it's only available on the (admin for the) model which defines the ManyToManyField
; how can I get the same widget on the (admin for the) other model, reading the relationship backwards?
My models look like this (feel free to ignore the User
/UserProfile
complication; it's the real use case though):
class Site(models.Model):
pass
class UserProfile(models.Model):
user = models.OneToOneField(to=User,unique=True)
sites = models.ManyToManyField(Site,blank=True)
I can get a nice widget on the admin form for UserProfile
with
filter_horizontal = ('sites',)
but can't see how to get the equivalent on the Site
admin.
I can also get part-way by adding an inline to SiteAdmin
, defined as:
class SiteAccessInline(admin_module.TabularInline):
model = UserProfile.sites.through
It's roundabout and unhandy though; the widget is not at all intuitive for simply managing the many-to-many relationship.
Finally, there's a trick described here which involves defining another ManyToManyField
on Site
and making sure it points to the same database table (and jumping through some hoops because Django isn't really designed to have different fields on different models describing the same data). I'm hoping someone can show me something cleaner.