LOGIN_REDIRECT_URL在django2.1中不起作用

时间:2018-12-15 14:42:06

标签: django

我正在学习Django,并且很难集成内置的Django登录系统。在settings.py中,我提供了LOGIN_REDIRECT_URLLOGOUT_REDIRECT_URL。当我单击注销按钮时,LOGOUT_REDIRECT_URL工作正常。提供登录凭据后,按钮LOGIN_REDIRECT_URL不起作用。

settings.py
LOGOUT_REDIRECT_URL = 'post_list'

LOGIN_REDIRECT_URL = 'post_list'

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',   
]

urls.py

from django.urls import path, include
from django.contrib import admin

urlpatterns = [
path(r'admin/', admin.site.urls),
path(r'', include('blog.urls')),
]

blog/urls.py
from django.urls import path
from .views import (BlogListView, BlogDetailView, BlogCreateView, BlogUpdateView, BlogDeleteView)

urlpatterns = [
path('', BlogListView.as_view(), name='post_list'),
path('post/<int:pk>/', BlogDetailView.as_view(), name='post_detail'),
path('post/new/', BlogCreateView.as_view(), name='post_new'),
path('post/<int:pk>/edit/', BlogUpdateView.as_view(), name='post_edit'),
path('post/<int:pk>/delete/', BlogDeleteView.as_view(), name='post_delete'),
]
login.html
{% extends 'base.html' %}


{% block content %}
<h2>Login</h2>
<form action="post">
{% csrf_token %}

{{form.as_p}}

<button type='submit'>Login</button>
</form>

{% endblock %}

base.html
<body>

<div class="container">
    <header>
        <div class="nav-left">
            <h1><a href="/">Django Blog</a></h1>
        </div>
        <div class=nav-right>
            <a href="{% url 'post_new' %}"> + New Blog Post. </a>
        </div>
    </header>

    {% if user.is_authenticated %}
        <p>Hi! {{user.username}}</p>
        <a href="{% url 'logout' %}">Logout</a>
    {% else %}
        <p>You are not logged in. </p>
        <a href="{% url 'login' %}">Login</a>
    {% endif %}

    {% block content %}

    {% endblock %}
</div>

</body>

1 个答案:

答案 0 :(得分:0)

将settings.py文件中的更改设置为

LOGIN_REDIRECT_URL = '/app/post_list/'

将此添加到您的登录URL到urls.py

url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html', 'redirect_field_name': '/app/post_list'}),