0

我正在尝试使用我的第一个 Django 表单,主要是遵循这个示例。我需要自己提供一个明确的 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>
4

2 回答 2

2

确保在 settings.py 中配置了模板加载器;

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

看来您已将模板放入应用程序的模板目录并使用应用程序名称为其命名。您应该在渲染调用中包含命名空间(您的应用程序名称)。

return render(request, 'showCrime/getQuery.html', {'form': qform})
于 2013-05-21T03:53:14.127 回答
-1

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

于 2013-05-21T19:47:15.117 回答