解决方案:
1.在对应的模板中, 为每个POST的form添加一行代码:{%
csrf_token %}。 如下所示:
<form action = "" method = "post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type = "submit" value = "Submit">
</form>
2.在对应的views.py中, 使用 django.template.RequestContext 而不是
Context。因为render_to_response 默认使用的是Context,我们需要改成 RequestContext。给
render_to_response函数增加一个参数,如下所示:
return render_to_response(‘contact_form.html‘,
{‘form‘ : form},context_instance = RequestContext(request))
3.修改settings.py,在MIDDLEWARE_CLASSES中加上‘django.middleware.csrf.CsrfViewMiddleware‘。如下所示:
1 MIDDLEWARE_CLASSES = (
2 ‘django.contrib.sessions.middleware.SessionMiddleware‘,
3 ‘django.middleware.common.CommonMiddleware‘,
4 ‘django.middleware.csrf.CsrfViewMiddleware‘,
5 ‘django.contrib.auth.middleware.AuthenticationMiddleware‘,
6 ‘django.contrib.messages.middleware.MessageMiddleware‘,
7 ‘django.middleware.clickjacking.XFrameOptionsMiddleware‘,
8 )
时间: 2024-10-14 14:39:42