In the Django admin, is there a way to show a list

2019-05-06 19:14发布

If this is too complicated or not the right way to do things, feel free to link me to something else or just tell me I should do it another way...

Basically, I'm working on a project where there are Clients, and each one has an arbitrary number of Websites attached to it. So the Websites model has a ForeignKey to the Client model. The Website admin page is pretty in-depth, and each Client might have 10 or more sites, so I'd rather not have them all display as inlines, because that's really messy and crazy looking.

What I'd like is that when you go to the admin panel and click Clients, you're brought to the change page where it has the basic stuff you'd edit for the client and then an inline of actual links to each of the client's website admin pages. Like this:

Change client

General

Name:

Address:

Phone:

Websites

Link to edit Website 1

Link to edit Website 2

Link to edit Website 3

Link to edit Website 4

Link to edit Website 5

1条回答
小情绪 Triste *
2楼-- · 2019-05-06 19:53

You can use a TabularInline that includes only a link to the model change page:

class ClientAdmin(admin.ModelAdmin):
    # everything as normal
    inlines = WebsiteInline,

class WebsiteInline(admin.TabularInline):
    model = Website
    fields = 'link',
    readonly_fields = 'link',
    def link(self, instance):
        url = reverse("admin:myapp_website_change", args = (instance.id,))
        return mark_safe("<a href='%s'>%s</a>" % (url, unicode(instance)))

admin.site.register(Client, ClientAdmin)
admin.site.register(Website)

See my recent question How do I add a link from the Django admin page of one object to the admin page of a related object? which was about how to do exactly this, but with several pairs of models rather than just one.

查看更多
登录 后发表回答