开发者

Making Django Readonly ForeignKey Field in Admin Render as a Link

开发者 https://www.devze.com 2023-02-17 01:45 出处:网络
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 ca

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. someuser@domain.com). 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/">someuser@domain.com</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'


Cerin's answer does not work in my Django 1.8 project, because readonly_fields should not contain string 'user_link', but a reference to defined function:

class ProfileAdmin(admin.ModelAdmin):
    # https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display
    def user(obj):
        change_url = reverse('admin:auth_user_change', args=(obj.user.id,))
        return mark_safe('<a href="{0}">{1}</a>'.format(change_url, obj.user.email))
    user.short_description = 'Edit linked user'
    raw_id_fields = ('user',)
    list_display = (user, 'last_name', 'first_name', 'specialization',)
    list_display_links = ('first_name', 'last_name', ,)
    readonly_fields = (user, 'user',)

Note that user(obj) overrides both single model edit and model list display for Profile.user field. Note also that readonly_fields uses both user and 'user', one renders linked email, another one user name.


I created some mixin:

# base.py
from django.urls import reverse
from django.utils.html import format_html

def base_method_factory(field_name):
    def base_method(obj):
        try:
            model = getattr(
                obj,
                field_name,
            )
            app_label = model._meta.app_label
            model_name = model._meta.model_name
        except AttributeError as e:
            return None
        return format_html(
            '<a href="{0}">{1}</a>&nbsp;',
            reverse('admin:%s_%s_change' % (app_label, model_name), args=[model.id]),
            str(model),
        )

    return base_method

class ReadonlyLinkMixin(object):
    def __init__(self, *args, **kwargs):
        self.create_linked_fields()
        super().__init__(*args, **kwargs)

    def create_linked_fields(self):
        linked_fields = filter(lambda name: name.endswith('_linked'), self.readonly_fields)
        for linked_field in linked_fields:
            setattr(
                self,
                linked_field,
                base_method_factory(linked_field.rpartition('_')[0])
            )

# models.py

class SomeModel(models.Model):
    ...
    task = models.FK(...)

# some_app_admin.py

@admin.register(SomeModel)
class SomeModelAdmin(
    ReadonlyLinkMixin,
    admin.ModelAdmin,
):
    fields = (
        ...
        'task_linked',
    )
    readonly_fields = (
        ...
        'task_linked',
    )

So in admin page it will look as linked string.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号