Django表单找不到我的模板

时间:2013-05-21 02:38:41

标签: django forms templates

我正在尝试使用我的第一个Django表单,主要是在this example之后。我是否需要自己提供一个明确的HTML表单,或者Django的Form类是否为我做了这个?如果是这样,怎么样?

这是我当前的错误:

Internal Server Error: /showCrime/query
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
    response = callback(request, *callback_args, **callback_kwargs)
  File "/Users/rik/Code/eclipse/djOakData/showCrime/views.py", line 43, in getQuery
    return render(request, 'getQuery.html', {'form': qform})
  File "/Library/Python/2.7/site-packages/django/shortcuts/__init__.py", line 53, in render
    return HttpResponse(loader.render_to_string(*args, **kwargs),
  File "/Library/Python/2.7/site-packages/django/template/loader.py", line 170, in render_to_string
    t = get_template(template_name)
  File "/Library/Python/2.7/site-packages/django/template/loader.py", line 146, in get_template
    template, origin = find_template(template_name)
  File "/Library/Python/2.7/site-packages/django/template/loader.py", line 139, in find_template
    raise TemplateDoesNotExist(name)
TemplateDoesNotExist: getQuery.html

showCrime/views.getQuery():

def getQuery(request):

    # import pdb; pdb.set_trace()
    if request.method == 'POST':
        qform = simpleQ(request.post)
        if qform.is_valid():
            qryData = qform.cleaned_data

            simpleQ.NQUERY += 1
            qurl = 'showCrime/plots/%s+%s.png' % (qryData['beat'], qryData['crimeCat']) 
            return HttpResponseRedirect(qurl)
    else:
        qform = simpleQ()

    return render(request, 'getQuery.html', {'form': qform})

showCrime/templates/showCrime/getQuery.html

<html>
<head>
    <title>ShowCrime - Query</title>
</head>
<body>
<h1>ShowCrime - Query</h1>


    {% if form.errors %}
        <p style="color: red;">
            Please correct the error{{ form.errors|pluralize }} below.
        </p>
    {% endif %}

    <form action="/getQuery/" method="post">
        <table>
            {{ form.as_table }}
        </table>
        {% csrf_token %}
        <input type="submit" value="Submit query">
    </form>

</body>
</html>

2 个答案:

答案 0 :(得分:2)

确保您的settings.py;

中配置了模板加载器
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

您似乎已将模板放入应用的模板目录中,并使用应用名称对其进行命名。您应该在要渲染的调用中包含命名空间(您的应用程序名称)。

return render(request, 'showCrime/getQuery.html', {'form': qform})

答案 1 :(得分:-1)

连同@ andrewS关于调用showCrime/render()前缀的提示,我能够通过遵循Chap7 of the Django book中使用HTML中的空字符串的建议来解决此问题:<form action="" method="post">。似乎有一些django对尾随斜线等的敏感性仍然超出我的范围,但这有效!