如何在jinja2中使用CSRF令牌?

时间:2013-11-19 12:33:46

标签: python django django-templates jinja2

我的form.html:

<form action="/contact/" method="post"><input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
    <table>
    <tr><p><td>Subject: </td><td><input type="text" name="subject" value="{{ subject }}"></p></td></tr>
    <tr><p><td>Your e-mail (optional): </td><td><input type="text" name="email" value="{{ email }}"></p></td></tr>
    <tr><p><td>Message: </td><td><textarea name="message" rows="10" cols="50">**{{ message }}**</textarea></p></td></tr>
    </table>
    <input type="submit" value="Send">
</form>

但我仍然得到禁止(403) CSRF验证失败。请求中止。

如何纠正?

2 个答案:

答案 0 :(得分:1)

我可能错了,但我相信{{csrf_token}}会出现在您的表单标签内部。

<form>{{ csrf_token }}
blah: <input type="text">
<input type="submit">
</form>

答案 1 :(得分:0)

您还需要将django.core.context_processors.csrf添加到TEMPLATE_CONTEXT_PROCESSORS设置中。否则{{ csrf_token }}将没有值。

您现在可能正在使用空CSRF令牌提交表单。