0
我已經構建了一個上下文過程,將登錄用戶權限作爲字符串發送到模板中。然後根據用戶的隱私我顯示或隱藏網址。Django - 上下文過程查詢重複102次
但是隻使用看出,查詢運行是有原因的102倍的調試工具欄IVE我不知道
調試(該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>
那工作,謝謝! – AlexW
是否可以通過這種方式檢查組?我無法在頁面上看到 – AlexW
'{%if perms.app.perm_name%}'與['user.has_perm']的工作方式相同(https://docs.djangoproject.com/en/1.11/ref/ contrib/auth /#django.contrib.auth.models.User.has_perm) - 如果用戶位於具有該權限的組中,則返回「True」。它也適當地處理超級用戶和活動標誌。 – Alasdair