django {%如果user.groups =='FC'%}不起作用 [英] django {% if user.groups == 'FC' %} doens't work

查看:18
本文介绍了django {%如果user.groups =='FC'%}不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用django建立一个网站.

I'm making a website using django.

{%,如果user.groups =='FC'%}在我的模板中不起作用.我有类似的组.

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

例如,如下所示,我的一个用户(用户名为"hong")属于"FC"组.

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

但是

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

如果user.groups ==''不起作用.

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

如何检查用户组?我必须按组区分用户.

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

推荐答案

您必须使用标签.在您的应用程序中,您可以创建一个目录,该目录名为: templatetags .

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

然后,您必须在文件 user_tags.py 中创建一个文件,该文件将包含:

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, ..) ;)

这篇关于django {%如果user.groups =='FC'%}不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆