User permissions for Django module

TheLifeOfSteve picture TheLifeOfSteve · Feb 3, 2011 · Viewed 9k times · Source

I'm having a small issue with my permissions in my Django template.

I'm trying to, based on permissions, show an icon in the menu bar for my project. I want to have it so that if the user has the permissions to add a new follow-up to the project, they can see the icon, if they don't have that permission, then do not display the link.

My permission syntax is follow.add_followup, which I got from printing user.get_all_permissions().

I have tried this code in my template:

...
{% if user.has_perm('followup.add_followup') %}
<li><a href="{% url followup-new p.id %}">Log</a></li>
{% endif %}
...

But when I display the template, I am presented with this error:

TemplateSyntaxError at /project/232/view/

Could not parse the remainder: '(followup.add_followup)' from 'user.has_perm(followup.add_followup)'

Any thoughts? This has been giving me a headache! :)

Answer

FallenAngel picture FallenAngel · Feb 3, 2011

Since you are using the Django permission system, it's better you use the followingg template syntax...

{%if perms.followup.add_followup%}your URL here{%endif%}

EDIT: Django automatically creates 3 permissions for each model, 'add', 'change' and 'delete'. If there exists no model for adding a link, then you must add the permission from related model, in the model class Meta... Likewise:

somemodels.py

class SomeModel(Model):
    ...
    class Meta:
    permissions = (('add_followup','Can see add urls'),(...))

In the Django auth user admin page, you can see your permission. In the template layer, permission is presented with the basic Django style,

<app_label>.<codename>

which, in this case, will be like:

{%if perms.somemodels.add_followup%}your URL here{%endif%}

If there is no model, related to the job you wish to do, the add the permission to a model...

In your template, you can write

{{perms.somemodels}}

to seal available permissions to that user, where somemodel is the name of the applicaton that you add your permission to one of its models.