django {%如果user.groups =='FC'%}不起作用

编程入门 行业动态 更新时间:2024-10-26 08:31:44
本文介绍了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'%}不起作用

本文发布于:2023-11-24 11:14:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1624976.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不起作用   user   django   groups   FC

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!