python - 找不到模板 - Django
问题描述
在我的 Django 项目中,我有两个应用程序,称为data_app
和user_app
。data_app
作品完美,但不是user_app
。
当我在浏览器中写入时http://127.0.0.1:8000/login/
出现以下错误,
django.template.exceptions.TemplateDoesNotExist: /login.html
可能我忘记了什么,但我不知道是什么。然后,我展示不同的部分和我的结构,
视图.py
from django.shortcuts import render
# Create your views here.
from django.shortcuts import redirect
from django.contrib.auth.models import User, auth
from django.contrib import messages
def login(request):
if request.method == 'POST':
username = request.POST['uname']
password = request.POST['pass']
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request,user)
return redirect('/data_app/data-bbdd/')
else:
return redirect('login')
else:
print('Hello2')
return render(request, '/login.html')
def logout(request):
auth.logout(request)
return redirect('login')
urls.py (user_app)
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('login/', views.login, name='login'),
path('logout/', views.logout, name='logout')
]
urls.py(“通用”应用程序)
from django.contrib import admin
from django.urls import path, re_path, include
urlpatterns = [
path('admin/', admin.site.urls),
re_path('', include('applications.data_app.urls')),
re_path('', include('applications.user_app.urls'))
]
结构
我想我忘记了一些路径,但我看不到。
注意print('Hello2')
from工作正常,views.py
问题出在return render(request, '/login.html')
.
非常感谢!
解决方案
由于 shyotov 已经回答了错误render(request, '/login.html')
,因为您的模板位于user_app
文件夹下。
在构建 Django 应用程序时,您应该尝试将模板分开。
您应该将 data_app 模板捆绑在 data_app 中。在以下文件夹中:applications/data_app/templates/data_app/data.html
对于您的 user_app,它将如下所示:
applications/user_app/templates/user_app/login.html
要完成这项工作,您需要更新您的 settings.py:(请参阅https://docs.djangoproject.com/en/3.0/topics/templates/)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
},
},
]
尽管如此,在你的内部views.py
你仍然需要调用:render(request, 'user_app/login.html')
,但你可以让你的模板靠近它们所属的位置。
您应该使用applications/templates
常见的共享模板。通常这个文件夹里面会有一个base.html
,其他模板可以从那里扩展。
推荐阅读
- java - 如何接受用户输入并将其放入 while 条件
- ios - tableview swift中的行为空
- http - 如何在 Go 中自定义 http.Client 或 http.Transport 以在超时后重试?
- python - 使用 QuantLib 的加拿大债券的现金流出现错误
- ios - 核心数据 - FetchedResults
- 没有成员“删除”
- mysql - 左连接不产生空值
- python - 在 Heroku 上部署项目后出现内部服务器错误
- javascript - 未捕获(承诺中)DOMException:加载失败,因为找不到支持的源
- r - ggplot2:图例中的颜色“超出范围”
- r - 如何使用 Rstudio 连接到 Google Cloud PostGress 数据库?