DJango模板未找到

2024-04-27 00:05:20 发布

您现在位置:Python中文网/ 问答频道 /正文

仍在学习Django,由于某些原因,我很难掌握一些概念,尤其是url/模板/视图映射。试图将FormView重新定向到“完整”页面,我有以下内容:

你知道吗网址.py你知道吗

from django.urls import path

from .views import *

urlpatterns = [
    path('', IndexView.as_view(), name='index'),
    path('forgotid/', ForgotId.as_view(),name="forgotid"),
    path('forgotid/complete/',ForgotIdComplete.as_view(),name="forgotid_complete"),
    path('forgotpwd/', ForgotPwd.as_view(),name="forgotpwd")
]

你知道吗视图.py你知道吗

from django.shortcuts import render
from django.views.generic import FormView, TemplateView

from .forms import LoginForm, ForgotIDForm


class IndexView(FormView):
    template_name = "login/index.html"
    form_class = LoginForm


class ForgotId(FormView):
    template_name = "login/forgotid.html"
    form_class = ForgotIDForm
    success_url = 'complete/'


class ForgotIdComplete(TemplateView):
    template_name = "login/forgotid/complete/forgotid_complete.html"

    def get(self, request):
        return render(request, self.template_name, None)


class ForgotPwd(TemplateView):
    template_name = "login/forgotpwd.html"

提交ForgotID表单应该将我重定向到success_url,但是我得到一个错误,说明找不到模板。有人能解释一下我为什么做得不对吗。你知道吗

我收到的错误是:

TemplateDoesNotExist at /login/forgotid/complete/

我的文件夹结构: enter image description here

编辑 我发现了问题。ForgotIdComplete类中的模板名称应为:login/forgotid_complete,而不是login/forgotid/complete/forgotid_complete.html


Tags: pathnamefromimportview模板urlhtml
3条回答

将您的成功url更改为此。你知道吗

from django.core.urlresolvers import reverse_lazy

class ForgotId(FormView):
    template_name = "login/forgotid.html"
    form_class = ForgotIDForm
    success_url = reverse_lazy('forgotid_complete')

这个错误意味着,django想要从您提供的路径render获取模板,但是在磁盘上找不到它。你知道吗

转到settings.py并确保templates配置为实际的模板目录。你知道吗

PROJECT_DIR = os.path.realpath('.')
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [(os.path.join(PROJECT_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',
            ],
        },
    },
]

我发现了问题。ForgotIdComplete类中的模板名称应为: login/forgotid_complete 而不是 login/forgotid/complete/forgotid_complete.html

相关问题 更多 >