【问题标题】:django can't find template when trying to use formsdjango在尝试使用表单时找不到模板
【发布时间】:2021-04-18 07:28:19
【问题描述】:

我正在尝试遵循 django 文档如何使用 sjango 表单类创建表单。我正在做每一步,但是在尝试访问我的表单时,它说找不到模板:

django.template.exceptions.TemplateDoesNotExist: lform

这是我的forms.py:

class LoginForm(Form):
    
    uname=CharField(label='user name',max_length=20)
    passw=CharField(label='password', max_length=20)

模板 lform.html:

<form action="ulogin" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit">
</form>

还有我的看法。我认为问题出在渲染函数中:

def testform(request):

    if request.method=='POST':
        form=LoginForm(request.POST)
        
        if form_is_valid():
            return render('index')
        else:
            HttpResponseRedirect('index')

    else:
        form=LoginForm()
    
    return render(request,'lform',{'form':form})

和 url.py:

path('lform',views.testform,name='lform')

视图函数的最后一行,

return render(request,'lform',{'form':form})

对错误有什么建议吗?

【问题讨论】:

    标签: django forms templates


    【解决方案1】:

    您正在尝试渲染模板lform。您的模板是 lform.html

    您需要通过模板路径设置提供模板的完整路径。

    【讨论】:

    • 更改为 lform.html 会出现同样的错误:TemplateDoesNotExist at /lform lform.html
    【解决方案2】:

    更正您的模板名称:

    def testform(request):
    
    if request.method=='POST':
        form=LoginForm(request.POST)
        
        if form_is_valid():
            return render('index')
        else:
            HttpResponseRedirect('index')
    
    else:
        form=LoginForm()
    
    return render(request,'lform.html',{'form':form})
    

    在您的设置中。

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': ["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',
                ],
            },
        },
    ]
    

    【讨论】:

    • 在我的设置中,我有以下路径:'DIRS': [os.path.join(BASE_DIR,'templates')],其他一切都与您的设置示例相同,我仍然得到改成lform.html后出现同样的错误
    • 您的模板在哪里?您的模板应该在您的 manage.py 所在的文件夹中。
    • 它们在下面:django/kammem/templates/kammem 但是所有其他模板都可以找到,只是这个lform找不到
    • 模板中的 action = "ulogin" 是什么。
    • 这就是当你按下提交按钮时会发生的事情,所有这些都是这样的:docs.djangoproject.com/en/3.1/topics/forms
    【解决方案3】:

    好的,错误只是模板的路径以某种方式丢失。我将模板在目录中进一步向上移动,现在它显示了表单。谢谢大家的回答。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-24
      • 2020-06-14
      • 2013-05-15
      • 1970-01-01
      • 1970-01-01
      • 2020-03-23
      • 2018-01-02
      • 2012-07-10
      相关资源
      最近更新 更多