jsa*_*ezs 1 django django-templates django-permissions
我得到了这个视图,并且正在使用PermissionRequiredMixin它......它工作正常,但是当我重定向到登录模板(在设置中设置LOGIN_URL)时,我需要它显示一条消息,例如“您无权执行此操作”。知道如何在不创建自定义装饰器而仅使用PermissionRequiredMixin其自身的情况下做到这一点吗?
from django.contrib.auth.mixins import PermissionRequiredMixin
class MyView(PermissionRequiredMixin,View):
template = 'myapp/item_detail.html'
permission_required = 'myapp.change_item'
def get(self, request, *args, **kwargs):
#Query here
return render(request, self.template)
Run Code Online (Sandbox Code Playgroud)
为了实现这一目标,我需要添加什么?
您应该使用消息传递框架。要添加您自己的消息,只需覆盖即可:
from django.contrib import messages
class MyView(...):
...
def handle_no_permission(self):
# add custom message
messages.error(self.request, 'You have no permission')
return super(MyView, self).handle_no_permission()
Run Code Online (Sandbox Code Playgroud)
您还需要将以下内容添加到您的base.html(或登录表单)中:
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
Run Code Online (Sandbox Code Playgroud)