django - 登录后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')
解决方案
您的重定向不是到模板而是到 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
推荐阅读
- python - SSHUTTLE 在连接到 GCP 实例的静态外部 IP (VPN) 时抛出错误 99
- sql - 我需要像下面的 sql server 请帮助解决这个问题
- google-calendar-api - Google 不同步我订阅的 ICS 提要
- javascript - 即使值已更改,对象状态仍返回空值
- c# - 从字符串数组中删除文本并检查特定字符串是否包含在字符串数组中?
- c - c header-guards被忽略了吗?
- java - 在执行线程上运行 Spring 方面的建议
- java - 如何在 H2 数据库中模拟 Oracle DB 链接?
- html - 视频仅在移动设备上溢出
- c# - 第一次导航到页面时阻塞主线程