'next' 参数如何工作? Django 认证系统

How does the 'next' parameter work? Django authentication system

TLDR:<input type="hidden" name="next" value="{{ next }}"> 是我不明白的代码行。有了它,这个重定向系统工作正常,但是,我不明白它在做什么。就好像 link 将用户带到下一页,但实际上没有 link 被点击?

我了解如果用户未登录,则 next 参数用于将用户重定向到他们在登录后尝试访问的任何 @login_required 装饰视图。虽然这种方式发生似乎有点自动。

我有以下登录相关设置:

LOGIN_REDIRECT_URL = 'dashboard' # tells django which url to redirect after login if no 'next' parameter is present in the request
LOGIN_URL = 'login' # url to redirect the user to log in (for example, views using the login_required decorator)

并且正在使用 django.contrib.auth 中的身份验证视图源(为简单起见只包括三个):

from django.urls import path
from . import views
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('', views.dashboard, name = 'dashboard'),
    path('login/', auth_views.LoginView.as_view(), name = 'login'),
    path('password_change/', auth_views.PasswordChangeView.as_view(), name = 'password_change'),
]

这是位于 account/registration/index 的自定义 login.html 模板。html:

  <div class="login-form">
    <form action="{% url 'login' %}" method="post">
      {{ form.as_p }}
      {% csrf_token %}
      <input type="hidden" name="next" value="{{ next }}">
      <input type="submit"  name="" value="Log-in">
    </form>
  </div>

现在假设我没有登录并尝试访问 /account/password_change,我将被重定向到 login 视图,路径将为 http://127.0.0.1:8000/account/login/?next=/account/password_change/,登录后我可以更改我的密码没问题。但是,如果我从 index.html 中删除 <input type="hidden" name="next" value="{{ next }}">

  <div class="login-form">
    <form action="{% url 'login' %}" method="post">
      {{ form.as_p }}
      {% csrf_token %}
      <input type="submit"  name="" value="Log-in">
    </form>
  </div>

并再次尝试访问 /account/change_password(作为未登录用户),我将被重定向到登录页面并且 url 将与之前相同 http://127.0.0.1:8000/account/login/?next=/account/password_change/ .然而,当我这次登录时,我被重定向到 dashboard 视图(这对我来说很有意义,我用 LOGIN_REDIRECT_URL = 'dashboard' 定义了它并且没有提供 next 参数。

综上所述,我不明白为什么在删除 <input type="hidden" name="next" value="{{ next }}">login 视图窗台 http://127.0.0.1:8000/account/login/?next=/account/password_change/ 的路径(即使我将被重定向到dashboard 而不是 password_change)?为什么在将 <input type="hidden" name="next" value="{{ next }}"> 添加回 html 之后浏览器知道如何将用户重定向到正确的页面?

如果有人花时间阅读并回复本文,在此先感谢!

问得好。 请阅读此代码段 https://github.com/django/django/blob/master/django/contrib/auth/views.py#L71

如果你仔细观察,这行代码试图从 POST 获取数据作为名称 next。如果没有名为 next 的键,它会尝试从查询参数中获取值;我的意思是得到。

因此,如果我们从表单 (<input type="hidden" name="next" value="{{ next }}">) 中删除输入,它仍然有效,因为查询参数充当后备。

希望对您有所帮助。