1

I'm trying to make it so that a certain part of the html is only viewable if a user belongs to a certain group or is an admin. I managed to find a way to make it so that only a certain group can see it:

base.html

{% for group in user.groups.all %}
    {% if group.name == 'example' %}
        Insert html here
    {% endif %}
{% endfor %}

The problem comes in trying to allow the admin to see it too. When I tried to add something like request.user.is_staff to the if statement, the code basically just ignored it. Is there anyway allowing the admin to see this html regardless of group without having to add the admin to the group? Also, this is the base.html, so trying to do this with a Python module would be problematic.

Jerry Bi
  • 321
  • 6
  • 24
  • status admin or superuser implies that this user has an access to everything without being explicitly added to a group. – Hisagr Sep 09 '17 at 16:52
  • That doesn't change the fact that the conditional is not allowing the admin to see the html regardless. – Jerry Bi Sep 09 '17 at 17:01
  • that's because you are using a group name instead of a permission. After setting specific permission you need to check {% if user.is_authenticated %}.More details are here https://docs.djangoproject.com/en/1.11/topics/auth/default/#all-authentication-views – Hisagr Sep 09 '17 at 17:21

1 Answers1

1

You need custom template tag:

from django import template
from django.contrib.auth.models import Group 

register = template.Library() 

@register.filter(name='has_group') 
def has_group(user, group_name):
    group =  Group.objects.get(name=group_name) 
    return group in user.groups.all() 

In your template:

{% if request.user|has_group:"moderator" and if request.user|has_group:"admin" %} 
    <p>User belongs to group moderator or admin</p>
{% else %}
    <p>User doesn't belong to moderator or admin</p>
{% endif %}
Kirill N
  • 40
  • 6
  • Yeah, I kind of figured this alternative out myself. It didn't work the first time I did it, but once I changed a few things, it worked. – Jerry Bi Sep 09 '17 at 19:39
  • For those unsure of where to put this, check out [this answer](https://stackoverflow.com/a/54398466/12601926) – sajeyks mwangi Mar 06 '23 at 13:56