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

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

问题描述

当查看模型的管理员变更列表时,是否可以使与外键相对应的列链接到其各自的页面?一个简单的例子是我有一个Foo对象,它包含Bar作为外键。如果我正在查看Foo的管理员更改列表(并将其设置为在display_list列中包含栏),则主列将链接到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.

推荐答案

您可以定义一个自定义方法,用于返回链接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链接到一个单独的栏,所以你可以链接到该栏的编辑页面。然而,每个条链接到多个foos,因此请求链接到Foo实例的编辑页面是没有意义的。您可以做的是链接到Foo的更改列表页面,过滤器设置仅显示链接到此栏的实例:

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天全站免登陆