[英]django retrieve csrf token
In my web application I need to retrieve csrf token for sending some data through xmlhttprequest but I'm getting an error at the server as " django\\middleware\\clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'str' object has no attribute 'get' ". This is my code 在我的Web应用程序中,我需要检索csrf令牌,以便通过xmlhttprequest发送一些数据,但是在服务器上,我在process_response中的 “ django \\ middleware \\ clickjacking.py”处收到错误, 如果response.get('X- Frame-Options')不是None:AttributeError:'str'对象没有属性'get' “。这是我的代码
//views.py //views.py
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.template.context_processors import csrf
def interfacePage(request):
return render(request, "interfacePage.html", {})
def interfacePageSubmit(request):
if request.method == 'POST':
datarecvd = request.POST['data']
return render(request, "interfacePageSubmit.html", {})
else:
print("in def interfacePageSubmit")
csrf1 = str(csrf(request)['csrf_token'])
return csrf1
//interfacePage.html //interfacePage.html
function sumbit() {
var xhr = new XMLHttpRequest();
var url = {% url 'interfacePageSubmit' %};
xhr.open("GET", url, false);
xhr.withCredentials = false;
xhr.setRequestHeader("x-csrf-token", "fetch");
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
var data = null;
xhr.send(data);
console.log(xhr.readyState);
console.log(xhr.status);
if (xhr.readyState === 4 && xhr.status === 200) {
var csrfToken = xhr.getResponseHeader('x-csrf-token');
url = {% url 'interfacePageSubmit' %};
xhr.open("POST", url, true);
xhr.withCredentials = false;
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.setRequestHeader('x-csrf-token', csrfToken);
}
**/ further code goes here
Pls note my " interfacePage.html only contains a button without any form tag 请注意我的“ interfacePage.html仅包含一个没有任何表单标签的按钮
You need to return an HttpResponse
. 您需要返回
HttpResponse
。 Try something like this: 尝试这样的事情:
def interfacePageSubmit(request):
# . . .
csrf1 = str(csrf(request)['csrf_token'])
json_data = json.dumps(csrf1)
return HttpResponse(json_data, content_type='json')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.