abidibo.net

Add links to django admin changelist view

django django-admin programming tips

You can also be interested in:

Sometimes you may need to add one or more links for each table row in your admin changelist view. There are many ways to do it, and here we'ss see a simple one. So this post is nothing more than a tip.

In my case I had to add a link opening a pdf view of the model item detail, here comes my implementation:

- app/models.py

from django.db import models
from django.core.urlresolvers import reverse
from django.utils.html import mark_safe

class MyModel(models.Model):
    title = models.CharField('title', max_length=255)
    # ...

    def pdf_link(self):
        return mark_safe('<a class="grp-button" href="%s" target="blank">view pdf</a>' % reverse('archiviocr-opera-pdf', args=[self.id]))
    pdf_link.short_description = _('PDF')

- app/admin.py

from app.models import MyModel

class MyModelAdmin(admin.ModelAdmin):
    list_display = ('id', 'title', 'pdf_link',)
    # ...

admin.site.register(MyModel, MyModelAdmin)

Basically all we do is to define a method of the model which returns the html link marking it as safe (otherwise the html is encoded using entities), and using the reverse to get the url pointing to the view which generates the pdf. Such method is then added to the list_display tuple in the ModelAdmin class.

That's it, just an easy tip.

Subscribe to abidibo.net!

If you want to stay up to date with new contents published on this blog, then just enter your email address, and you will receive blog updates! You can set you preferences and decide to receive emails only when articles are posted regarding a precise topic.

I promise, you'll never receive spam or advertising of any kind from this subscription, just content updates.

Subscribe to this blog

Comments are welcome!

blog comments powered by Disqus

Your Smartwatch Loves Tasker!

Your Smartwatch Loves Tasker!

Now available for purchase!

Featured