Django Admin 链接到相关对象 [英] Django Admin linking to related objects

查看:19
本文介绍了Django Admin 链接到相关对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用有创建页面的用户.在管理员的页面屏幕中,我想列出创建页面的用户,在该列表中,我希望用户名有一个链接,该链接指向管理员中的用户页面(而不是页面).

My app has users who create pages. In the Page screen of the admin, I'd like to list the User who created the page, and in that list, I'd like the username to have a link that goes to the user page in admin (not the Page).

class PageAdmin(admin.ModelAdmin):
    list_display = ('name', 'user', )
    list_display_links = ('name','user',)
admin.site.register(Page, PageAdmin)

我希望通过将它作为 list_display 中的链接,它会默认链接到实际的用户对象,但它仍然会转到 Page.

I was hoping that by making it a link in the list_display it would default to link to the actual user object, but it still goes to Page.

我确定我在这里遗漏了一些简单的东西.

I'm sure I'm missing something simple here.

推荐答案

将此添加到您的模型中:

Add this to your model:

  def user_link(self):
      return '<a href="%s">%s</a>' % (reverse("admin:auth_user_change", args=(self.user.id,)) , escape(self.user))

  user_link.allow_tags = True
  user_link.short_description = "User" 

您可能还需要将以下内容添加到 models.py 的顶部:

You might also need to add the following to the top of models.py:

  from django.template.defaultfilters import escape
  from django.core.urls import reverse

admin.py中,在list_display中,添加user_link:

list_display = ('name', 'user_link', )

不需要 list_display_links.

这篇关于Django Admin 链接到相关对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆