Django user permissions in your templates

With Djangos custom template tags you can check for permissions and other stuff in your templates in a really elegant way.

The tasks

On the frontend display an “edit” link for the owner of an object (and for super users).

Developers come across this or similar tasks quite a lot. With a custom template tag in Django, you can create a nice and easy readable solution.

The ugly solution

You have something like this in your template:

{% if user.is_authenticated %}
    {% if user.is_superuser %}
        <a href="{% url 'event:edit' event.id %}">
            Edit event
        </a>
    {% else %}
        {% if myobject.user == user %}
            <a href="{% url 'event:edit' event.id %}">
                Edit event
            </a>        
        {% endif %}
    {% endif %}
{% endif %}

This is not really easy to read and has way to much logic in your template.

The nice solution

You create a custom template filter to check if the user can edit the object. Now your template code looks like this:

{% if user|can_edit:my_obj %}
    <a href="{% url 'my_obj:edit' my_obj.id %}">
        Edit object
    </a>
{% endif %}

This is way better to read. Developing software is all about how easy it is for the next developer to read and understand your code. (The "next developer" can be you in six months when you have absolutely no clue what you where thinking when you write some piece of code six months earlier)

Hope you liked this and it helped you to write more beatiful code!

This is a small accompanying blog post to the lightning talk I did at the December Django Meetup in Vienna.

There are also slides to this topic. Find them on slideshare.net/apirker