Django trick: using named admin urls in templates

To add a link to an admin page on the user-side of your django site, you can use the named url patterns. (Seems like a simple and fairly straightforward thing to want to do, but I frequently find that things are not so simply found in most open source docs, nor are the examples always useful. But my usual open source docs rant is for another day. *g*)

It took a bit of digging, but I finally found that the admin url pattern options are listed here. From that, I was able to figure out that if I wanted to link to the edit (change action) page (parameter) for an article (model) in the app article, the pattern was:

{{ app_label }}_{{ model_name }}_action [parameters]

The namespace for the admin is, of course, admin, so putting that together using the {% url %} template tag, you get:

<a href="{% url 'admin:article_article_change' article.pk %}">{% trans 'Edit' %}</a>

That correctly creates the relative url to /admin/article/article/2. Yay!

Be sure to load the admin template tags in your template, too, or it won't work:

{% load admin_urls %}

Et voilà! *vbg* Hope this saves someone else a bit of time.

(This works for Django 1.4, btw.)

One Comment

  1. Gabriele says:

    Thank you!! I was not understanding the Django docs about reversing admin urls in templates. Now I solved my problem thanks to your post :-)

Leave a Reply