Django - how to tell if user was redirected to the page by @login_required?

僤鯓⒐⒋嵵緔 提交于 2021-02-11 14:20:16

问题


I want to use the

@login_required 

decorator for a view called

allUsers_page

, which is used when you go to the url

r'^users/allUsers$'

In my settings.py, I have

LOGIN_URL='/login'

so when a user goes to the

allUser_page

view (when he goes to the url

users/allUsers

, if the user is not signed into his account, it will redirect him to the login page. Now, in the login page, is there a way for me to find out if the user just went to the login page directly or if he was redirected to the login page by the

@login_required

decorator? Basically, I want my login page to be something like

{% if the user was redirected to this page by @login_required %}
    <p>Hi, you must log in in order to view the page you were trying to view.</p>
{% else %}
    <p>Welcome! Please sign in.</p>
<!-- Here is where the log in form is -->

NOTE: I am using the generic login view.


回答1:


If the user user was redirected from another page, django will provide the next query string parameter, so that the user can be redirected back after signing in.

Add this to your settings.py

TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    "django.contrib.messages.context_processors.messages",
    "django.core.context_processors.request",
)

then, in the template, check if this parameter exists or not.

{% if 'next' in request.GET %}

Not tested, though.

See Auth docs



来源:https://stackoverflow.com/questions/21082520/django-how-to-tell-if-user-was-redirected-to-the-page-by-login-required

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!