Django Tips & Tricks #8 - Hyperlink Foreignkey Fields In Admin

4 min read

Consider Book model which has Author as foreignkey.

from django.db import models


class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author)

We can register these models with admin interface as follows.

from django.contrib import admin

from .models import Author, Book

class BookAdmin(admin.ModelAdmin):
    list_display = ('name', 'author', )

admin.site.register(Author)
admin.site.register(Book, BookAdmin)

Once they are registed, admin page shows Book model like this.

While browing books, to go to a particular author, we have to previous page, go to Author model and then find relevant author. This becomes tedious if we spend lot of time in admin. Instead, if author field has a hyperlink, we can directly go to its page.

Django provides an option to access admin views by its URL reversing system. For example, we can get add view of author model in book app from reverse("admin:book_author_add").

To hyperlink author field in book admin, get url from reversing book_author_change with its id and return required html.

class BookAdmin(admin.ModelAdmin):
    list_display = ('name', 'author_link', )

    def author_link(self, book):
        link = reverse("admin:book_author_change", args=[book.author.id])
        return u'<a href="%s">%s</a>' % (link, book.author.name)
    author_link.allow_tags = True
    author_link.short_description = 'Author'

Now in the book admin view, author field will be hyperlinked and we can visit just by clicking it.

Tags: django | django-tips-tricks | python

I am Chillar Anand. I daydream a lot and write about the things that interest me here. You can read more about this blog here.

See all articles

RSS Feed for the blog

Edit this page