在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