我构建了一个上下文进程,将登录用户的权限作为字符串发送到模板中。然后根据用户的权限我显示或隐藏网址。
然而,使用调试工具栏我刚看到该查询运行了102次,原因我不知道
调试(ID更改,看起来重复项中每个ID有3个)
SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE `django_content_type`.`id` = 35
Duplicated 102 times.
0.6862959744274587%
23.41
Sel Expl
Connection: default
/itapp/itapp/sites/views.py in site_detail_files(214)
'PageType' : 'files',
/usr/local/lib/python3.6/contextlib.py in __enter__(81)
return next(self.gen)
/itapp/itapp/itapp/context_processors.py in UserPerms(34)
'Perms': str(all_perms),
功能:
def UserPerms(request):
from django.contrib.auth.models import Permission
all_perms = []
if str(request.user) != 'AnonymousUser':
permissions = Permission.objects.filter(user=request.user)
group_permissions = Permission.objects.filter(group__user=request.user)
all_perms = []
for p in permissions:
all_perms.append(p)
for p in group_permissions:
all_perms.append(p)
return {
'Perms': str(all_perms),
}
添加到settings.py中的模板
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
BASE_DIR + '/templates/',
],
'APP_DIRS': True,
'OPTIONS': {
'debug' : DEBUG,
'context_processors': [
'django.template.context_processors.debug',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media',
'django.template.context_processors.static',
'itapp.context_processors.breadcrumb_history',
'itapp.context_processors.UserPerms',
],
},
},
]
用法示例:
<li><a href="{% url 'sites:site_detail_circuits' SiteID %}">Circuits</a>
{% if "Permission: sites | Circuit Data | Can add Circuit Data" in Perms %}
{% if PageType == 'circuits' %}
<ul>
<li><a href="{% url 'admin:sites_circuits_add' %}?site_data={{ SiteID }}">Add new circuit</a></li>
</ul>
{% endif %}
{% endif %}
</li>
答案 0 :(得分:1)
Django provides a way to check permissions in the template。您不必创建包含权限的字符串。
{% if perms.sites.add_circuit_data %}
{% if PageType == 'circuits' %}
<ul>
<li><a href="{% url 'admin:sites.add_circuit' %}?site_data={{ SiteID }}">Add new circuit</a></li>
</ul>
{% endif %}
您需要为此启用auth
上下文处理器,但由于这是在默认生成的设置文件中,因此您不必更改任何内容。