两种解决方法
一:CSRF验证设置
前端:
html文件需要加上 {% csrf_token %}
<form action="." method="POST">
{% csrf_token %}
<input type="text" name="test" value="{{test}}"/>
<input type="submit" value="提交" />
</form>
Django后台---2种解决方法:
1:继承TemplateView
from django.views.generic import TemplateView
class TestView(TemplateView):
template_name = "test.html"
def get(self, request):
return self.render_to_response(locals())
def post(self, request):
test = request.POST.get("test", "").strip()
return self.render_to_response(locals())
2: 加上RequestContext
from django.views.generic import View
from django.shortcuts import RequestContext
class TestView(View):
template_name = "test.html"
def get(self, request):
# return render(request, self.template_name ) #这行代码作用和下面一行一样
return render_to_response(self.template_name, context_instance=RequestContext(request))
def post(self, request):
test = request.POST.get("test", "").strip()
# return render(request, self.template_name, locals()) #这行代码作用和下面一行一样
return render_to_response(self.template_name, locals(), context_instance=RequestContext(request))
二:不使用CSRF验证
1:html文件中form表单中移除 {%csrf_token%}
2: settings.py文件中不使用csrf中间件
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.middleware.locale.LocaleMiddleware',
)