我正在尝试创建一个非常简单的Web应用程序(我在Django中非常新)。此应用包含(在index.html
)表单,该表单必须专用于上传文本块。当用户点击提交时,它会返回带有此文本的名为processed_text
的新页面。
问题在于,当我使用GET
时,它可以正常运行,但当我将GET
更改为POST
时(在html
和django
中),它会返回一些异常
禁止(403)CSRF验证失败。请求中止。
它甚至不打印视图中的'process_text method'。
以下是我的代码:
views.py:
def index(request):
return render(request,'uploading/index.html')
def process_text(request):
print 'process_text method'
if 'text_to_translate_name' in request.POST:
message = 'OK {}'.format(request.POST['text_to_translate_name'])
return HttpResponse(message)
index.html: 无头
<body>
<h1>Index z TEMPLATES H1</h1>
<form action="/process_text/" method="post">
<input type="text" name="text_to_translate_name">
<input type="submit" value="upload">
</form>
</body>
</html>
urls.py:
urlpatterns = [
url(r'^$', views.index),
url(r'^process_text/$',views.process_text),
]
你知道问题出在哪里吗?
答案 0 :(得分:3)
您需要在表单中添加{% csrf_token %}
。它将一个csrf标记输入字段插入到表单中,Django将其用于安全目的。
所以你的表格看起来像 -
<form action="/process_text/" method="post">
{% csrf_token %}
<input type="text" name="text_to_translate_name">
<input type="submit" value="upload">
</form>