2

I'm making a website using django.

{% if user.groups == 'FC' %} doesn't work in my template.I have groups like that.

my user group

For example, one of my users(username is 'hong) belongs to 'FC' group as you see below. enter image description here

But,

{% if user.groups == 'FC' %}
      <li><a href="{% url 'register' %}">register form</a></li>
      <li><a href="{% url 'mypage' %}">fc's my page</a></li>
{% else %}
 <li><a href="{% url 'PT_mypage' %}">fitness' my page</a></li>
{% endif %}

if user.groups == ' ' doesn't work.

How I check the users' group? I have to distinguish the users by groups.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Julia
  • 315
  • 4
  • 15

2 Answers2

4

You have to use tags. In your application, you can create a directory which is named : templatetags.

Then, you have to create inside a file user_tags.py which will contain :

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.filter(name=group_name)
    if group:
        group = group.first()
        return group in user.groups.all()
    else:
        return False

Then, in your template, if you want to specify part, ...

{% load user_tags %}
...
...
{% if request.user|has_group:"yourgroupe" %}
# part which will only accessible for users registered in `yourgroup` 
{% endif %} 

It works in my application with different groups (admin, users, visitors, ..) ;)

Sayok88
  • 2,038
  • 1
  • 14
  • 22
Essex
  • 6,042
  • 11
  • 67
  • 139
3

try below

{% for group in  request.user.groups.all %}
{%  if 'FC' == group.name %}
   <<< write your code that you want >>>
{% endif %}
{% endfor %}
Neeraj Kumar
  • 3,851
  • 2
  • 19
  • 41