首页 > 解决方案 > 找不到模板 - Django

问题描述

在我的 Django 项目中,我有两个应用程序,称为data_appuser_appdata_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').

非常感谢!

标签: pythondjangodjango-viewsdjango-templates

解决方案


由于 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,其他模板可以从那里扩展。


推荐阅读