The Python Oracle

Django-admin : How to display link to object info page instead of edit form , in records change list?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Quiet Intelligence

--

Chapters
00:00 Django-Admin : How To Display Link To Object Info Page Instead Of Edit Form , In Records Change List
00:59 Accepted Answer Score 23
01:27 Answer 2 Score 10
02:10 Thank you

--

Full question
https://stackoverflow.com/questions/1172...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #django #djangoadmin #admin

#avk47



ACCEPTED ANSWER

Score 23


If I understand your question right you want to add your own link to the listing view, and you want that link to point to some info page you have created.

To do that, create a function to return the link HTML in your Admin object. Then use that function in your list. Like this:

class ModelAdmin(admin.ModelAdmin):
    def view_link(self):
        return u"<a href='view/%d/'>View</a>" % self.id
    view_link.short_description = ''
    view_link.allow_tags = True
    list_display = ('id', view_link)



ANSWER 2

Score 10


Take a look at: http://docs.djangoproject.com/en/dev/ref/contrib/admin/, ModelAdmin.list_display part, it says: A string representing an attribute on the model. This behaves almost the same as the callable, but self in this context is the model instance. Here's a full model example:

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    color_code = models.CharField(max_length=6)

def colored_name(self):
    return '<span style="color: #%s;">%s %s</span>' % (self.color_code, self.first_name, self.last_name)
colored_name.allow_tags = True

class PersonAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name', 'colored_name')

So I guess, if you add these two methods to Person

def get_absolute_url(self):
    return '/profiles/%s/' % (self.id)

def profile_link(self):
    return '<a href="%s">%s</a>' % (self.get_absolute_url(), self.username)
profile_link.allow_tags = True

and changes PersonAdmin to

class PersonAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name', 'colored_name', 'profile_link')

Then you done