overclock
overclock

Reputation: 625

How to show different content depending on UserGroup in Django?

I have created a password_change_done template.

But I need to to show a Back to Dashboard button for Employees and a Back to Profile for Customers.

How can I achieve this through UserGroup checking, without messing with the views.py?

Upvotes: 1

Views: 630

Answers (1)

Manan M.
Manan M.

Reputation: 1394

Then you have to use the filter of the template as below...

In your app create a folder 'templatetags'. In this folder create two files:

  1. __init__.py
  2. get_group.py

The folder structure looks like ...

app/
    __init__.py
    models.py
    templatetags/
        __init__.py
        get_group.py
    views.py

get_group.py file :

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): 
    return user.groups.filter(name=group_name).exists()

Then in your html page use it as below...

{% load get_group %}

{% if request.user|has_group:"Client" %} 
    ... Back to Dashboard button ...
{% else %}
    ... Back to profile button ...
{% endif %}

Upvotes: 2

Related Questions