首页 > 解决方案 > Django没有使用内置登录视图重定向到下一页

问题描述

我不知道我的代码发生了什么,一旦未经身份验证的用户尝试访问页面并重定向到登录页面,我可以在浏览器中看到下一个参数,但在用户登录后,它需要用户到默认的 LOGIN_REDIRECT_URL 而不是下一页。同样在模板上,next 没有返回,所以模板似乎没有得到下一个值,但在 url 中它显示 /?next=,提前谢谢。

网址.py

from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from blog import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.HomeView.as_view(),name="index"),
    path('accounts/login/', auth_views.LoginView.as_view(), name='login'),
    path('accounts/logout/', auth_views.LogoutView.as_view(next_page='/'), name='logout'),
    path('accounts/profile/', views.ProfileView.as_view(), name='profile'),
]

注册/login.html

{% extends 'app/base.html' %}

{% block link %} id="active" {%endblock%}

{% block content %}
<div class="row">
    <div class="col-md-3">

    </div>
    <div class="col-md-6">
        <div class="jumbotron" id="font">

            {% if next %}
                {% if user.is_authenticated %}
                <h2 class="customtext" align="center">Your account doesn't have access to this page. To proceed,
                please login with an account that has access.</h2>
                {% else %}
                <h2 class="customtext" align="center">Please login.</h2>
                {% endif %}
            {% else %}
            <h2 class="customtext" align="center">Enter your login details.</h2>
            {% endif %}
            <form action="{% url 'login' %}" method="POST">
                {%csrf_token%}
                <div class="form-group">
                    <input type="text" name="username" placeholder="username" class="form-control">
                </div>
                <div class="form-group">
                    <input type="password" name="password" placeholder="password" class="form-control">
                </div>
                <!-- <div align="center"> -->
                    {% if form.errors %}
                        <!-- <p style="color: red; font-style: italic;">Your username or email is does not match.</p> -->
                        {{form.errors}}
                    {% endif %}
                <!-- </div> -->
                <div class="loginbtndiv" align="center">
                    <input type="submit" class="btn btn-warning btn-lg loginbtn" value="LOGIN">
                </div>
                <input type="hidden" name="next" value="{{ next }}">
            </form>

        </div>
    </div>
    <div>

    </div>
</div>

{% endblock %}

标签: pythondjango

解决方案


LOGIN_REDIRECT_URL在您的 settings.py 文件中使用。


推荐阅读