79716422

Date: 2025-07-27 13:14:51
Score: 0.5
Natty:
Report link

This is an old question and some clever workarounds have been posted already, however, wanted to leave mine here that handles the problem only from the html template without having to modify the views or write custom decorators.

When the user gets redirected to the login page by the @login_required decorator, Django by default stores the path from which the user was redirected from in the 'next=' query parameter.

For example, let's assume we are trying to access the path to view presentation, which is protected by @login_required. This means if we try to access this page without being logged in first, we will be redirected to the login path, which might look something like this:

http://127.0.0.1:8000/user/login?next=/presentations/

Here, you can see the 'next=' query parameter was appended at the end of the login path - the name for this parameter can be customized and made unique by specifying a 'redirect_field_name' parameter for 'login_required()'.

Once you know that this query parameter will always appear in the login path each time a user is redirected by '@login_required', you have the option to add an error message from within the login.html template by doing the following:

{% if request.GET.next %}
        <div class="alert alert-warning alert-dismissible fade show" role="alert">
            Please log in to access this page
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
{% endif %}

This will add the following dismissible warning to the login page to appear only when the user is redirected from '@login_required'.


Example error message

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @login_required
  • User mentioned (0): @login_required
  • Low reputation (1):
Posted by: valkiss024