Search code examples
pythonhtmldjangoadminusergroups

Allow certain group and admin to view part of HTML in Django


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.


Solution

  • 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 %}