Foreign keys in django admin list display
Solution 1
I don't think there is a mechanism to do what you want automatically out of the box.
But as far as determining the path to an admin edit page based on the id of an object, all you need are two pieces of information:
a) self.model._meta.app_label
b) self.model._meta.module_name
Then, for instance, to go to the edit page for that model you would do:
'../%s_%s_change/%d' % (self.model._meta.app_label, self.model._meta.module_name, item.id)
Take a look at django.contrib.admin.options.ModelAdmin.get_urls
to see how they do it.
I suppose you could have a callable that takes a model name and an id, creates a model of the specified type just to get the label and name (no need to hit the database) and generates the URL a above.
But are you sure you can't get by using inlines? It would make for a better user interface to have all the related components in one page...
Edit:
Inlines (linked to docs) allow an admin interface to display a parent-child relationship in one page instead of breaking it into two.
In the Post/Author example you provided, using inlines would mean that the page for editing Posts would also display an inline form for adding/editing/removing Authors. Much more natural to the end user.
What you can do in your admin list view is create a callable in the Post model that will render a comma separated list of Authors. So you will have your Post list view showing the proper Authors, and you edit the Authors associated to a Post directly in the Post admin interface.
Solution 2
I was looking for a solution to the same problem and ran across this question... ended up solving it myself. The OP might not be interested anymore but this could still be useful to someone.
from functools import partial
from django.forms import MediaDefiningClass
class ModelAdminWithForeignKeyLinksMetaclass(MediaDefiningClass):
def __getattr__(cls, name):
def foreign_key_link(instance, field):
target = getattr(instance, field)
return u'<a href="../../%s/%s/%d">%s</a>' % (
target._meta.app_label, target._meta.module_name, target.id, unicode(target))
if name[:8] == 'link_to_':
method = partial(foreign_key_link, field=name[8:])
method.__name__ = name[8:]
method.allow_tags = True
setattr(cls, name, method)
return getattr(cls, name)
raise AttributeError
class Book(models.Model):
title = models.CharField()
author = models.ForeignKey(Author)
class BookAdmin(admin.ModelAdmin):
__metaclass__ = ModelAdminWithForeignKeyLinksMetaclass
list_display = ('title', 'link_to_author')
Replace 'partial' with Django's 'curry' if not using python >= 2.5.
Solution 3
See https://docs.djangoproject.com/en/stable/ref/contrib/admin/#admin-reverse-urls
Example:
from django.utils.html import format_html
def get_admin_change_link(app_label, model_name, obj_id, name):
url = reverse('admin:%s_%s_change' % (app_label, model_name),
args=(obj_id,))
return format_html('<a href="%s">%s</a>' % (
url, unicode(name)
))
Olivier Verdier
Updated on April 21, 2021Comments
-
Olivier Verdier about 3 years
If a django model contains a foreign key field, and if that field is shown in list mode, then it shows up as text, instead of displaying a link to the foreign object.
Is it possible to automatically display all foreign keys as links instead of flat text?
(of course it is possible to do that on a field by field basis, but is there a general method?)
Example:
class Author(models.Model): ... class Post(models.Model): author = models.ForeignKey(Author)
Now I choose a ModelAdmin such that the author shows up in list mode:
class PostAdmin(admin.ModelAdmin): list_display = [..., 'author',...]
Now in list mode, the author field will just use the
__unicode__
method of theAuthor
class to display the author. On the top of that I would like a link pointing to the url of the corresponding author in the admin site. Is that possible?Manual method:
For the sake of completeness, I add the manual method. It would be to add a method
author_link
in thePostAdmin
class:def author_link(self, item): return '<a href="../some/path/%d">%s</a>' % (item.id, unicode(item)) author_link.allow_tags = True
That will work for that particular field but that is not what I want. I want a general method to achieve the same effect. (One of the problems is how to figure out automatically the path to an object in the django admin site.)
-
Olivier Verdier about 14 yearsThank you for this answer! Could you elaborate on the use of inlines? How would that help?
-
cethegeek about 14 years@Olivier: Editted my answer to point you in the right direction regarding inlines.
-
stepank over 12 yearsItai Tavor, thank you for your answer, it was really halpful, but it may cause problems, details are in my answer to another question.
-
JTE over 9 yearsFor me, using the absolute path of <a href="/admin/%s/%s/%d">%s</a> worked better, as the link would be correct when on the object detail page, rather than just on the list page.
-
Timo about 9 yearswhat is the parameter for the ModelAdminWith... method? I do not have a "MediaDefineClass" as form?
-
Greg over 8 yearsBeautiful solution. Had to change "target._meta.module_name" to "target._meta.model_name". Works nicely.