Reputation: 17
I only want to show buttons based on a user group. In this example I have a list of buttons then an IF Statement that checks if the user is in the group 'Recruiter', if they are then it displays some additional buttons:
Is there an easier way to do this in the html, like
{% if request.user.groups == 'recruiter' %}
Views.py
fields = request.user.groups
if fields == 'Recruiter':
fields1 = 'True'
else: fields1 = ''
context['fields1'] = fields1
html
{% if fields1 %}
a bunch of buttons
{% endif %}
Upvotes: 0
Views: 97
Reputation: 2103
# request.user.groups.all will return queryset, so you have iterate on the queryset in order to compare the group 'Recruiter'
{% for group in request.user.groups.all %}
{% if group.name == 'Recruiter' %}
a bunch of buttons
{% endif %}
{% endfor %}
OR
# if you already know that you have only group assigned to the user, then you directly compare the group 'Recruiter'
{% if request.user.groups.all.0.name == 'Recruiter' %}
a bunch of buttons
{% endif %}
Upvotes: 1
Reputation: 600
I guess that you talk about the groups from django auth module, you can create a custom template tag for that:
from django import template
register = template.Library()
@register.filter(name='in_group')
def in_group(user, name):
return user.groups.filter(name=name).exists()
Than in your template:
{% if request.user|in_group:"thegroup" %}
// Put here the buttons you want
{% else %}
// put here what is for everybody
{% endif %}
Upvotes: 0