0

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 %}
Yuval.R
  • 1,182
  • 4
  • 15
Clatters
  • 17
  • 4
  • Here is the answer you want. Check his answer https://stackoverflow.com/questions/44983959/django-if-user-groups-fc-doenst-work – ngawang13 Jun 10 '20 at 05:51

2 Answers2

1
# 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 %}
Mukul Kumar
  • 2,033
  • 1
  • 7
  • 14
  • Excellent. While I couldn't get your example to work exactly, you got me on the right path. In the end I just used {% if user.groups == 'Recruiter' %} a bunch of buttons {% endif %} – Clatters Jun 10 '20 at 07:39
0

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 %}
Tartempion34
  • 492
  • 6
  • 23