Easy Contextual Admin Edit Links for Django

Something I like to include for my clients is per content/page edit links. Django doesn’t have it built in, but its not hard to add. This is a simple tutorial to get you started.

A screenshot of this edit link in context

In the screenshot above, I have the edit link for an Article single in context on the page. This allows site administrators to easily update content without hunting through the administration panels.

Step 1: Where to put it?

In django 1.4.x and django 1.5.x, I make these edits to the project’s app directory’s __init__.py file.

Step 2: Add the code

Essentially, this is going to monkey patch django.db.models.Model to have a instance method get_admin_url

    from django.db import models
    from django.core.urlresolvers import reverse

    # Add admin Url to every content object
    def get_admin_url(self):
        return reverse('admin:%s_%s_change' % (self._meta.app_label,  self._meta.module_name),  args=[self.pk])
    models.Model.get_admin_url = get_admin_url
    {% if request.user.is_staff %}[ <a class="edit-link" href="{{ article.get_admin_url }}">Edit</a> ]{% endif %}

But wait… that staff member may not have permission for that particular resource?

This is a relevant concern. However, the django admin will sort out permissions on its own. If a staff member doesn’t have specific permissions - the link won’t take them to the update page. I’ve chosen to keep the template integration as easy as possible.

Note: you could do the permission check for the individual model resource you are trying to edit, but then these “quick” edit links become a pain to implement in the templates / less generic.

Written on May 15, 2013