Home > Software engineering >  How to jump to a related model object via Django admin's list_display?
How to jump to a related model object via Django admin's list_display?

Time:10-29

I do have a model Comment that relates to the model Poller via FK relationship. Is there any way I can jump to this related object via the Django admin interface from the Comment's overview?

# Models.py

class Comment(models.Model):
    """
    A Class for comments made by users to a specific Poller
    """
    poller = models.ForeignKey(Poller, on_delete=models.CASCADE, related_name='PollerComment')
    user = models.ForeignKey(Account, on_delete=models.CASCADE)
    vote = models.ForeignKey(Vote, on_delete=models.CASCADE)
# Admin.py

@admin.register(Comment)
class PollerCommentAdmin(admin.ModelAdmin):
    list_display = ('user', 'created_on', 'poller', 'comment', 'flag_count', 'upvote_count',
                    'downvote_count', 'is_public', 'is_removed')

Now I would like to make the 'poller' column clickable which will then redirect me to this poller object in the admin.

CodePudding user response:

You need to replace poller in list_display with a custom method that returns the desired link.


from django.utils.safestring import mark_safe
# [...]

@admin.register(Comment)
class PollerCommentAdmin(admin.ModelAdmin):
    list_display = (
        'user', 'created_on', 'get_poller_link', 'comment', 'flag_count',
        'upvote_count','downvote_count', 'is_public', 'is_removed'
    )

    def get_poller_link(self, obj):
        # assuming poller is in the same app...
        return mark_safe('<a href="../poller/%s">%s</a>' % (obj.poller_id, obj.poller)

    get_poller_link.short_description = "Header to display"
    get_poller_link.admin_order_field = 'poller_id' # or another
  • Related