外键更改页面的更改列表链接 [英] Change list link to foreign key change page

查看:15
本文介绍了外键更改页面的更改列表链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看模型的管理员更改列表时,是否可以将与外键对应的列链接到各自的页面?一个简单的例子是我有一个包含 Bar 作为外键的 Foo 对象.如果我正在查看 Foo 的管理员更改列表(并将其设置为在 display_list 列中包含 Bar),主列将链接到 Foo 实例的编辑页面,而 Bar 列将链接到 Boo 实例的编辑页面.我知道我可以覆盖使用的模板,但我很好奇是否有不需要这样做的解决方案.

When viewing the admin change list for a model, is it possible to make the columns that correspond to foreign keys links to their respective pages? A simple example is I have a Foo object which contains Bar as a foreign key. If I'm viewing the admin change list for Foo (and have it set to include Bar in the display_list columns), the main column would link to the Foo instance's edit page while the Bar column would link to the Boo instance's edit page. I understand I can override the template that's used, but I was curious if there was a solution that didn't require that.

推荐答案

你可以定义一个自定义方法在 changelist 中使用,它返回链接的 HTML.

You can define a custom method to use in the changelist which returns the HTML of the link.

from django.core.urlresolvers import reverse

class MyFooAdmin(admin.ModelAdmin):
    list_display = ('foo', 'bar_link')

    def bar_link(self, obj):
        url = reverse('admin:myapp_bar_change', args=(obj.pk,))
        return '<a href="%s">Edit Bar</a>' % url 
    bar_link.allow_tags = True 

如前所述,您的问题存在一个问题-如果 Foo 具有 Bar 的外键,则每个 foo 都链接到单个栏,因此您可以链接到该栏的编辑页面.但是,每个 bar 都链接到多个 foo,因此请求Foo 实例的编辑页面"的链接是没有意义的.您可以做的是链接到 Foo 的更改列表页面,并将过滤器设置为仅显示链接到此 Bar 的实例:

One problem with your question as stated - if Foo has a foreign key to Bar, then each foo links to a single bar, so you can link to the edit page for that bar. However, each bar links to multiple foos, so it doesn't make sense to ask for a link to 'the Foo instance's edit page'. What you can do is link to the changelist page for Foo with the filter set to only show the instances that link to this Bar:

    def foo_link(self, obj):
        url = reverse('admin:myapp_foo_changelist')
        return '<a href="%s?bar=%s">See Foos</a>' % (url, obj.pk) 
    foo_link.allow_tags = True 

这篇关于外键更改页面的更改列表链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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