Link in django admin to foreign key object Link in django admin to foreign key object django django

Link in django admin to foreign key object


You can do the following:

models.py (example):

model B(models.Model):    name = models.CharField(max_length=20)model A(models.Model):    field1 = models.CharField(max_length=20)    Bkey = models.ForeignKey(B)

admin.py

from django.core import urlresolversclass AAdmin(admin.ModelAdmin):    list_display = ["field1","link_to_B"]    def link_to_B(self, obj):        link=urlresolvers.reverse("admin:yourapp_b_change", args=[obj.B.id]) #model name has to be lowercase        return u'<a href="%s">%s</a>' % (link,obj.B.name)    link_to_B.allow_tags=True

Replace yourapp with the name of your app.


In addition of the accepted answer, in newer versions of Django, the reverse method is now in the package django.urls (cf. this link).

Moreover, you should use the format_html function to output HTML in the admin. Then the allow_tags becomes useless.

Finally, to add a link to the edit page of a user, I have this function in admin.py:

from django.urls import reversefrom django.utils.html import format_htmlclass ObjectAdmin(admin.ModelAdmin):    list_display = ('name', 'link_to_user')    def link_to_user(self, obj):        link = reverse("admin:auth_user_change", args=[obj.user_id])        return format_html('<a href="{}">Edit {}</a>', link, obj.user.username)    link_to_user.short_description = 'Edit user'

Don't forget to check the comments, there are a few considerations to take into account.


Django 2.0+ and Python 3.5+:

from django.urls import reversefrom django.utils.html import escape, mark_safe@admin.register(models.YourModel)class YourModelAdmin(BaseModelAdmin):    def model_str(self, obj: models.YourModel):        link = reverse("admin:module_model_change", args=[obj.model_id])        return mark_safe(f'<a href="{link}">{escape(obj.model.__str__())}</a>')    model_str.short_description = 'Model'    model_str.admin_order_field = 'model' # Make row sortable    list_display = (        'model_str',    )