Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Django Readonly ForeignKey Field in Admin Render as a Link

I have a model exposed in Django's admin, which uses ModelAdmin's readonly_fields list to show a "user" field, which is a ForiegnKey linking to Django's User model. By default, readonly_fields causes this field to be rendered as simple text containing the user's email (e.g. [email protected]). How would I change this to render as a link to the associated admin page for that user? (e.g. <a href="/admin/auth/user/123/">[email protected]</a>)

like image 785
Cerin Avatar asked Mar 16 '11 19:03

Cerin


1 Answers

Digging into the source code, I found you can essentially define your own fields as methods within your ModelAdmin subclass, and you can get the field to render as a link by simply returning the link html from the method.

e.g.

from django.contrib import admin
from django.utils.safestring import mark_safe
from django.core import urlresolvers

class MyModelAdmin(admin.ModelAdmin):

    readonly_fields = ['user_link']

    def user_link(self, obj):
        change_url = urlresolvers.reverse('admin:auth_user_change', args=(obj.user.id,))
        return mark_safe('<a href="%s">%s</a>' % (change_url, obj.user.email))
    user_link.short_description = 'User'
like image 111
Cerin Avatar answered Sep 30 '22 00:09

Cerin