saikuron
saikuron

Reputation: 369

Django: Show button in template for certain group level

I have 3 groups: viewer, editor and creator. I want to show the right amount of button according to the permissions.

viewer: can see list and detail

editor: viewer permissions + can edit

creator: editor permissions + can create and delete

I've tried to run this for the template:

{% load groupfilter %}
{% if request.user|group:"creator" %}
<p>creator permissions</p>
{% endif %}{% if request.user|group:"editor" || request.user|group:"creator" %}
<p>editor permissions</p>
{% endif %}{% if request.user|group:"editor" || request.user|group:"creator" || request.user|group:"viewer"%}
<p>viewer permissions</p>
{% endif %}

but I get this error: Could not parse the remainder: '||' from '||'.

groupfilter.py:

from django import template
register = template.Library()

@register.filter(name='group')
def group(u, group_names):
return u.groups.filter(name=group_names)

What have I done wrong? Is there an easier way to do this? Thanks

Upvotes: 0

Views: 1288

Answers (1)

Higor Rossato
Higor Rossato

Reputation: 2046

Your logic is right on the template but the usage is wrong. You're trying to check OR condition and in Python/Django you should use the word or. Also your filter should check if the group exists because you're returning a Queryset to the template which it'll never do what you want. You can check my example below.

{% load groupfilter %}

{% if request.user|group:"creator" %}
    <p>creator permissions</p>
{% endif %}
{% if request.user|group:"editor" or request.user|group:"creator" %}
    <p>editor permissions</p>
{% endif %}
{% if request.user|group:"editor" or request.user|group:"creator" or request.user|group:"viewer"%}
    <p>viewer permissions</p>
{% endif %}

What you could also do is to implement your filter in a way that it receives a list of group names and with that you don't need a lot of "ors"

from django import template
register = template.Library()

@register.filter(name='group')
def group(u, group_names):
    group_names = group_names.split(',')
    return u.groups.filter(name__in=group_names).exists()
{% load groupfilter %}

{% if request.user|group:"creator" %}
    <p>creator permissions</p>
{% endif %}
{% if request.user|group:"editor,creator" %}
    <p>editor permissions</p>
{% endif %}
{% if request.user|group:"editor,creator,viewer" %}
    <p>viewer permissions</p>
{% endif %}

Upvotes: 1

Related Questions