首页 > 解决方案 > 登录后Django重定向用户

问题描述

登录后尝试将用户重定向到base.html主模板文件夹中的用户时遇到问题。Django 找不到这个模板。

我得到错误:

 Django tried these URL patterns, in this order:

 1. admin/
 2.
 The current path, base.html, didn't match any of these.

如何正确设置 django 以使重定向工作?

Django结构:

accounts
main_folder
    settings.py
    urls.py
staticfiles
templates
    base.html

简短的应用程序结构

accounts
    templates
        accounts
            login.html
    urls.py
    views.py

设置.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

帐户 urls.py

from django.urls import path
from .views import*

urlpatterns = [
    path('', login_view),

]

帐户视图.py

from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.contrib import messages


def login_view(request):
    if request.method == 'POST':
        # get posted data
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        # handle user authentication
        if user is not None and user.is_active and user.is_authenticated:
                login(request, user)
                # move user to main page
                return redirect('base.html')

    return render(request, 'accounts/login.html')

标签: django

解决方案


您的重定向不是到模板而是到 url。因此,在您当前成功登录的代码中,您将被重定向到http://localhost/base.html

您需要将重定向更改为路径:

return redirect('/some-url/')

或者最好还是使用命名的 url。

return redirect('some-named-url')
# this would turn a named url into a url string such as '/auth-url/'

你的 urls 文件看起来像:

from django.urls import path
from .views import*

urlpatterns = [
    path('', login_view),
    path('auth-url/', <some_view>, name='some-named-url'),
]

更好的更多django方式。

如果您没有做任何过于极端的事情,您真的应该考虑使用 djangos 内置身份验证。它不仅经过尝试和测试,而且如果发现漏洞,它也会得到修补。

为此,您可以将 url 更改为:

from django.urls import path
from django.contrib.auth.views import (
    LoginView,
    LogoutView,
)

urlpatterns = [
    path(
        'login/',
        LoginView.as_view(template_name='account/login.html'),
        name='login',
    ),
    path(
        'logged-in/',
        <Your LoginView>,
        name='logged_in',
    ),
    path(
        'logout/',
        LogoutView.as_view(),
        name='logout',
    ),
]

在您的设置文件中:

LOGIN_URL = 'login' # this is the name of the url

LOGOUT_REDIRECT_URL = 'login' # this is the name of the url

LOGIN_REDIRECT_URL = 'logged_in' # this is the name of the url

推荐阅读