How can I raise send a django error message in a class based view with a LoginRequiredMixin?

Question:

I have a class based view ProfileView to which unauthorized users are not allowed access to. I have used the LoginRequiredMixin to limit access.

class ProfileView(LoginRequiredMixin, TemplateView) :
     template_name='profile.html'
     permission_denied_message='You are not allowed access here' 
     login_url='/users/login'

I have this snippet included in my base.html

{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">
{{ message }}
</div>
{% endfor %}
{% endif %}

But when I try to login as an anonymous user, I am redirected to the login url but there is no message displayed. What do I do?

Asked By: IgnisDa

||

Answers:

I solved the problem with the following custom mixin.

class CustomLoginRequiredMixin(LoginRequiredMixin):
""" The LoginRequiredMixin extended to add a relevant message to the
messages framework by setting the ``permission_denied_message``
attribute. """

    permission_denied_message = 'You have to be logged in to access that page'

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            messages.add_message(request, messages.WARNING,
                             self.permission_denied_message)
            return self.handle_no_permission()
        return super(CustomLoginRequiredMixin, self).dispatch(
            request, *args, **kwargs
        )

This can be used in a view like so:

class SomeView(CustomLoginRequiredMixin, TemplateView):
    template_name = 'myapp/template.html' 
    permission_denied_message = 'Restricted access!'
    # [...] 
Answered By: IgnisDa
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.