views:

136

answers:

1

In Django admin site, when listing all the objects for a given model, I know we can customize which columns get displayed for a ModelA via list_display

Say that ModelA has a one-to-many relationship with ModelB. I would like to add another column on the listing page for ModelA, where each entry is a URL pointing to all objects of ModelB having a foreign key relationship on corresponding instance of Model A in that row. How can I achieve this customization with the admin app?

+1  A: 

Hi,

you should add a method to ModelA's admin class:

def modelb_link(self, inst):
    url = u'../modelb/?modela__id__exact=%d' % inst.id
    return u'<a href="%s">Models B</a>' % url
modelb_link.allow_tags = True
modelb_link.short_description = u'Models B'

In the url the 'modela_id_exact' part is a filter for list page, where 'modela' is the name of ForeignKey field, in ModelB class, that links to ModelA.

Then use this method in 'list_display' property and you are done. If you encounter any problems, just ask, I'll try to help.

Greetings, Lukasz

Łukasz Korzybski
Thanks for the help Lukasz. I tried your suggestion but hit this error:ImproperlyConfigured at /admin/'ModelA_Admin.fields' refers to field '<function modelb_link at 0xa3e85dc>' that is missing from the formclass ModelA_Admin(admin.ModelAdmin): def modelb_link(self, inst): url = u'/'+settings.ADMIN_PREFIX + u'myapp/modelb/?foreignkey__id__exact=%d' % inst.id return u'<a href="%s">Models B</a>' % url modelb_link.allow_tags = True modelb_link.short_description = u'Models B' fields = ('field1', 'field2', modelb_link)
theactiveactor
Nvm, my mistake I have to add "modelb_link" string to list_display. Also, settings.ADMIN_PREFIX was causing evaluation of the function to bail, so I removed it and hardcoded the admin URL. Now it's working as expected. Thanks again Lukasz!
theactiveactor
You're right about ADMIN_PREFIX, it's not a standard Django setting value, I changed my answer a bit to fix it. Please mark my answer as accepted if you think it answers your question. Greets.
Łukasz Korzybski