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>
)
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With