1

我创建了一个password_change_done模板。

但我需要Back to Dashboard为员工和Back to Profile客户显示一个按钮。

我怎样才能通过用户组检查来实现这一点,而不会弄乱views.py

4

1 回答 1

2

然后你必须使用filter下面的模板...

在您的应用程序中创建一个文件夹“templatetags”。在此文件夹中创建两个文件:

  1. __init__.py
  2. get_group.py

文件夹结构看起来像......

app/
    __init__.py
    models.py
    templatetags/
        __init__.py
        get_group.py
    views.py

get_group.py 文件:

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): 
    return user.groups.filter(name=group_name).exists()

然后在你的html页面中使用它如下......

{% load get_group %}

{% if request.user|has_group:"Client" %} 
    ... Back to Dashboard button ...
{% else %}
    ... Back to profile button ...
{% endif %}
于 2020-03-12T22:13:04.587 回答