1

So I want to change what information is displayed based on the group the user is in.

So:

{% if user.is_staff %} 
......

That works but when I try and do

{% if user.is_China %}

This group doesn't work?

Is there a specific thing I need to do to find out if the user is part of a group?

ChrisB
  • 123
  • 5
  • 13
  • Possible duplicate of https://stackoverflow.com/questions/4789021/in-django-how-do-i-check-if-a-user-is-in-a-certain-group – mikep Jun 13 '17 at 10:49
  • is_staff is inbuilt attr for django admin model User, is_china is not. To able to use is_china you need a custom user model in which you can define is_china attr. – Amar Jun 13 '17 at 10:54

2 Answers2

2

Maybe what you need is a custom template tag:

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

register = template.Library() 

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

In your template:

{% if user|is_group:"group" %} 
    <p> User belongs to group </p>
{% else %}
    <p> User doesn't belong to group </p>
{% endif %}
Tanvir Nayem
  • 702
  • 10
  • 25
zaidfazil
  • 9,017
  • 2
  • 24
  • 47
1

The only note to the Fazil Zaid answer is that a Group.DoesNotExist exception will be raised if no Group will be found by a group_name. In my opinion it would be better to handle this exception and return False if group does not exist.

@register.filter(name='is_group') 
def is_group(user, group_name):
    try:
        group =  Group.objects.get(name=group_name) 
        return group in user.groups.all() 
    except Group.DoesNotExist:
        return False

See https://docs.djangoproject.com/en/1.11/ref/models/instances/#django.db.models.Model.DoesNotExist for more information about the exception.

A. Grinenko
  • 341
  • 1
  • 3
  • 5