简体   繁体   中英

django - Need references to another model from list_display

When i clicked to author field i need to be referenced to clicked author model admin - how to do this?

class BookAdmin(admin.ModelAdmin):
     list_display = ['name', 'pub_date', 'author',]

In the admin class

   def author_link(self, obj):
        return '<a href="/admin/authors-appname/author-model-name/%s">%s</a>' \
               % (obj.auther.pk, obj.auther)
    author_link.allow_tags = True
    author_link.short_description = "auther"

    list_display = ['name', 'pub_date', 'author_link',]
    readonly_fields = ('author_link', )

more elegant is to change the hard link to a function in the model - get_auther_absolute_url and call it from admin

There are a few answers on SO with regards to this, namely:

Change list link to foreign key change page

Link in django admin to foreign key object

To quote the above, what you need to do is define your own method, call it go_to_author() as part of your BookAdmin class, as such

class BookAdmin(admin.ModelAdmin):
    list_display = ['name', 'pub_date', 'go_to_author',]
    def go_to_author(self, obj):
        link=urlresolvers.reverse("admin:yourapp_author_change", args=[obj.author.id])
        return u'<a href="%s">%s</a>' % (link, obj.author.name)
    go_to_author.allow_tags=True

I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM