在Django管理员中内联显示子级 [英] Show children inline in Django admin

查看:78
本文介绍了在Django管理员中内联显示子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django 1.11中,我有2个模型,分别是 Foo Bar :

In Django 1.11, I have 2 models, Foo and Bar:

class Foo(models.Model):
    name = models.CharField()

class Bar(models.Model):
    name = models.CharField()
    foo = models.ForeignKey(Foo)

当我在Django管理员中访问Foo页面时,我希望能够看到其下方的Bar列表.所以我在 admin.py :

When I visit the Foo page in the Django admin, I want to be able to see a list of its Bars underneath it. So I do this in admin.py:

class BarInline(admin.StackedInline):
    model = Bar

@admin.register(Foo)
class FooAdmin(admin.ModelAdmin):
    list_display = ('name')
    fields = ('name')
    inlines = [BarInline]

但是我真正想要的是可单击链接的列表,这些链接指向一个单独的页面,我可以在其中编辑每个Bar(以及添加"按钮以向此Foo添加新Bar).IE.我不想要整个内联表单.在Django中怎么可能?

But what I really want is a list of clickable links to a separate page where I can edit each Bar (as well as a Add button to add a new Bar to this Foo). I.e. I don't want the entire inline form. How is this possible in Django?

推荐答案

admin.py

from django.urls import reverse
from django.utils.html import format_html_join

@admin.register(Foo)
class FooAdmin(admin.ModelAdmin):
    list_display = ('name')
    fields = ('name', get_related, )
    readonly_fields = (get_related, )

    def get_related(self, instance):
        obj = instance.bar_set.all()
        return format_html_join(
            ',',
            '<a href="{}">{}</a>',
            ((
                reverse('admin:{{ app_label }}_bar_change', args=(c.id,)), 
                c.name
            ) for c in obj),
        )

您可以创建一个可调用的只读字段,它将返回相反的

You can create a callable readonly field which will return the reversed admin url of each relation wrapped in the relevant html code.

这将导致类似以下内容:

This will result in something like:

您的只读字段":link1,link2,link3

"your readonly field": link1, link2, link3

这篇关于在Django管理员中内联显示子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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