I got this view and I'm using PermissionRequiredMixin
on it...it works fine but when I redirect to login template (set in settings LOGIN_URL
) I need it shows a message there like "You don't have permission to do this". Any idea how to do it without creating a custom decorator, just using PermissionRequiredMixin
itself?
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)
What do I need to add in order to achieve that?
You should use the messaging framework. To add your own message, simple overwrite:
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()
you'll also need to add the following to your base.html
(or login form):
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}