简体   繁体   English

Django的管理。 链接以编辑list_display中的用户配置文件

[英]Django-admin. Link to edit user profile from list_display

I inserted "creator"-method to my model like this: 我将“creator”方法插入到我的模型中,如下所示:

def creator(self):
        return self.user

Then i'd add this line to Admin-class of this model^ 然后我将此行添加到此模型的Admin-class ^

list_display = ('title','created_at','votes','creator')

And there was all good... usernames are displayed on that column, but i want to make links from that names which will forward me to edit that user-profiles. 并且有很好的...用户名显示在该列上,但是我想从这些名称创建链接,这些链接将转发我以编辑该用户配置文件。 How can i do this? 我怎样才能做到这一点? Thanks a lot! 非常感谢!

First, add 'user_link' to list_display. 首先,将“user_link”添加到list_display。 Then, add this to your ModelAdmin: 然后,将其添加到您的ModelAdmin:

def user_link(self, obj):
        return '<a href="%s">%s</a>' % (
            urlresolvers.reverse('admin:auth_user_change', args=(obj.user.id,)), obj.user
            )
user_link.allow_tags = True
user_link.short_description = 'User'

(untested) (另)

There is a better alternative: raw_id_fields . 还有一个更好的选择: raw_id_fields

@admin.register(Ticket)
class AdminTicket(admin.ModelAdmin):
    fields = ['user', 'subject', 'message']
    raw_id_fields = ['user']

Here is how this will look like: 这是这样的:

在此输入图像描述

In Django 2.0 you cannot use allow_tags = True anymore. 在Django 2.0中,你不能再使用allow_tags = True了。 Instead, you need to mark the string as safe by returning mark_safe("<a href="...">...</a>) . 相反,您需要通过返回mark_safe("<a href="...">...</a>)将字符串标记为安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM