如何检查(在模板中)用户是否属于组 [英] How to check (in template) whether user belongs to group

查看:116
本文介绍了如何检查(在模板中)用户是否属于组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查用户是否属于某个组?

How to check in template whether user belongs to some group?

可以在视图中生成模板但是如果我想在 base.html 中检查这个扩展模板(它没有自己的视图功能)?

It is possible in a view which is generating the template but what if I want to check this in base.html which is an extending template (it does not have it's own view function)?

我的所有模板都扩展了 base.html ,所以在每个视图

All of my templates extends base.html so it is not good to check it in each view.

base.html 包含上面的栏,其中应包含按钮,具体取决于哪个登录的用户是(客户,卖家)。

The base.html contains upper bar, which should contain buttons depending on in which group logged user is (Customers, Sellers).

在我的 base.html 中是:

{% if user.is_authenticated %}

这还不够因为我必须从客户 Sellers 中的用户执行不同的操作。

which is not enough because I have to act differently to users from Customers and users from Sellers.

所以我想要的是:

{% if user.in_group('Customers') %}
 <p>Customer</p>
{% endif %}
{% if user.in_group('Sellers') %}
<p>Seller</p>
{% endif %}


推荐答案

自定义模板标签:

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.get(name=group_name) 
    return group in user.groups.all() 

在您的模板中:

{% if request.user|has_group:"mygroup" %} 
    <p>User belongs to my group 
{% else %}
    <p>User doesn't belong to mygroup</p>
{% endif %}

资料来源: http://www.abidibo.net/blog/2014/05 / 22 / check-if-user-belongs-group-django-templates /

文档: https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/

这篇关于如何检查(在模板中)用户是否属于组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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