Creating a link for Foreign key in Admin

2,437 views
Skip to first unread message

Joshua Partogi

unread,
Sep 6, 2009, 3:39:50 AM9/6/09
to django...@googlegroups.com
Dear all,

I have a model that has a foreign e.g

class Foo(models.Model):
  bar = models.ForeignKey(Bar)

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

This is my FooAdmin:
class FooAdmin(admin.ModelAdmin):
  list_display = ['bar']

Now in the admin Foo's display list I want to have a link to go to bar display list. What would be the best way to do that in django? I tried to search in the doc but could not find a relevant howto on this issue.

Thanks in advance for the insights.

regards,


--
http://blog.scrum8.com
http://twitter.com/scrum8

Daniel Roseman

unread,
Sep 6, 2009, 4:20:16 AM9/6/09
to Django users
Define a custom method on the FooAdmin class which returns the HTML of
a link to the Bar changelist with the relevant filter applied:

def bar_link(self, obj):
return '<a href="/admin/myapp/bar/?foo=%s">See Bars</a>' %
obj.pk
bar_link.allow_tags = True

See http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display
--
DR.

Joshua Partogi

unread,
Sep 6, 2009, 6:21:43 AM9/6/09
to django...@googlegroups.com

Is there any built-in method in django where we can that url without having to hardcode it?

Karen Tracey

unread,
Sep 6, 2009, 8:46:40 AM9/6/09
to django...@googlegroups.com

Yes (assuming you are using 1.1), for the base changelist url:

http://docs.djangoproject.com/en/dev/ref/contrib/admin/#reversing-admin-urls

You'll still have to add on the filter value yourself.

Karen

Joshua Partogi

unread,
Sep 6, 2009, 9:09:49 AM9/6/09
to django...@googlegroups.com

Okay this is good enough for me. Thanks Karen.
Reply all
Reply to author
Forward
0 new messages