简体   繁体   中英

How to know which page redirected to the login URL with the @login_required decorator in Django?

I have two page that the user needs to be logged in to access, both of them redirect to the login URL with the @login_required decorator

@login_required
def ask_question(request)
    
@login_required
def answer_question(request)

and I would like to display a message on the login page that will be specific depending on the page that redirected to the login.

Both pages have a link on the same page, on the index page so I can't use the request origin because the two have the same origin.

Like:

"You need to be logged in to ask question" (if the user came from the ask question redirection)

"You need to be logged in to answer question" (if the user came from the answer redirection)

You can use messages framework of django for both the pages.

For example:

If anybody go on question page,from the button say its name ask question so make a view for it like:

from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.shortcuts import render

@login_required(login_url='/login-route/')
def ask_question(request):
    messages.success(request, 'You need to login to ask the question.')
    context{}
    return render(request,'appname/anyfile.html',context)


@login_required(login_url='/login-route/')
def answer_to_an_question(request):
    context={}
    messages.success(request, 'You need to login to answer the question.')
    return render(request,'appname/anyfile.html',context)

You can use any messages like error,success,warning etc. then it will redirect it to next url . Then on redirected page where user goes, the message will appear, say its a login page where you can show it in format like:

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}

The best part of using django messages is that it will appear only one time.

for example

@login_required(login_url='signin')

write your views here

return render(request, 'path/#####.html', context )

when user logged in your return will take him to the the page that you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM