简体   繁体   English

一旦用户登录,如何将用户重定向到他们尝试访问的页面? (Django)

[英]How do I redirect an user back to the page they were trying to access once they log in? (Django)

So currently I'm using @login_required to block certain pages from users and redirect them, telling them they need to log in. but what I can't understand is how do I "let them" go to the page they were trying to go to once they log in. Currently I'm just using a typical render_to_response('with a certain view') but what if i want that response to be anywhere where they were trying to access. 因此,当前我正在使用@login_required阻止用户访问某些页面并重定向它们,告诉他们他们需要登录。但是我不明白的是我如何“让他们”进入他们试图访问的页面到他们登录一次。目前,我只是使用典型的render_to_response('with a some view'),但是如果我希望该响应位于他们尝试访问的任何位置,该怎么办。 How do i code that? 我该如何编码?

您可以将url参数传递回登录页面,并在用户成功完成登录后使用该参数指导用户。

The @login_required will generally pass you back the redirect_field_name (default is "next") for example: /accounts/login/?next=/polls/3/. @login_required通常会将您传递给redirect_field_name(默认为“ next”),例如:/ accounts / login /?next = / polls / 3 /。 So in your login view after authenticating and logging in the user you can do something like 因此,在对用户进行身份验证和登录后,可以在登录视图中执行以下操作

response = HttpResponseRedirect(next)
# Do whatever else you need to do here with the response object
return response

See the docs at https://docs.djangoproject.com/en/1.3/topics/auth/#the-login-required-decorator 请参阅https://docs.djangoproject.com/zh-CN/1.3/topics/auth/#the-login-required-decorator中的文档

from the login requiered decorator docs it says: 从需要登录的装饰器文档中说:

By default, the path that the user should be redirected to upon successful authentication is stored in a query string parameter called "next". 默认情况下,成功身份验证后用户应重定向到的路径存储在名为“ next”的查询字符串参数中。

and usually when the login is done it take to the "next" url 通常,登录完成后,它会转到“下一个” URL

Here's what django.contrib.auth.views.login does: 这是django.contrib.auth.views.login的作用:

If called via GET, it displays a login form that POSTs to the same URL. 如果通过GET调用,它将显示一个登录表单,该表单将POST到相同的URL。 More on this in a bit. 对此有更多的了解。
If called via POST , it tries to log the user in. If login is successful, the view redirects to the URL specified in next . 如果通过POST调用,它将尝试登录用户。 如果登录成功,则视图将重定向到next中指定的URL If next isn't provided, it redirects to settings.LOGIN_REDIRECT_URL (which defaults to /accounts/profile/). 如果未提供next,它将重定向到settings.LOGIN_REDIRECT_URL(默认为/ accounts / profile /)。 If login isn't successful, it redisplays the login form. 如果登录不成功,它将重新显示登录表单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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