我试图呈现从Django中的POST请求的JSON响应,使得我的看法是CSRF令牌错误,同时要求对POST请求一个JSON
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import View
class TaskView(View):
def get(self,request,*args,**kwargs):
return HttpResponse("hello",content_type="application/json")
def post(self,request,*args,**kwargs):
return HttpResponse("hello",content_type="application/json")
这必须返回两个你好JSON响应获取以及作为发布请求。
但我做了这个工作得到请求。但是,如果我做一个post请求,然后 我收到以下错误
Forbidden (403)
CSRF verification failed. Request aborted.
You are seeing this message because this HTTPS site requires a 'Referer header' to be sent by your Web browser, but none was sent. This header is required for security reasons, to ensure that your browser is not being hijacked by third parties.
If you have configured your browser to disable 'Referer' headers, please re-enable them, at least for this site, or for HTTPS connections, or for 'same-origin' requests.
Help
Reason given for failure:
Referer checking failed - no Referer.
In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:
Your browser is accepting cookies.
The view function uses RequestContext for the template, instead of Context.
In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.
You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.
You can customize this page using the CSRF_FAILURE_VIEW setting.
我中间件类设置
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',
)
我需要重构的角度来处理JSON POST请求任何部分。
你是如何发送POST请求?它是一个表单提交或通过AJAX等?如果你可以编辑你的模板代码,这将是有益的 – 2014-12-08 08:51:43
不,我使用邮递员工具铬插件 – 2014-12-08 16:44:24
嗨!你解决了这个问题吗? – bellum 2015-11-03 11:53:01