gpt4 book ai didi

python - CSRF token 丢失或不正确,即使我有 {% csrf_token %} 但我使用 HttpResponse

转载 作者:行者123 更新时间:2023-11-28 19:29:52 27 4
gpt4 key购买 nike

表单.html

<form action='/login/' method = 'post'>
{% csrf_token %}
<label>Email: (*)</label><input type='text' name='email' value='' /><br />
<label>Password: </label><input type='password' name='password' value='' /><br />
<input type='submit' name='submit' value='Log in' />
</form>

和 views.py 我使用 HttpResponse 而不是 render_to_response

def login(request):
success = False
message = ''

try:
emp = Employee.objects.get(email = request.POST['email'])
if emp.password == md5.new(request.POST['password']).hexdigest() :
emp.token = md5.new(request.POST['email'] + str(datetime.now().microsecond)).hexdigest()
emp.save()
info = serializers.serialize('json', Employee.objects.filter(email = request.POST['email']))
success = True
return HttpResponse(json.dumps({'success':str(success).lower(), 'info':info}))
else:
message = 'Password wrong!'
return HttpResponse(json.dumps({'success':str(success).lower(), 'message':message}), status = 401)
except:
message = 'Email not found!'
return HttpResponse(json.dumps({'success':str(success).lower(), 'message':message}), status = 401)

如果使用 render_to_response,我只是添加了 RequestContext 而不是 HttpResponse,我不知道该怎么做。

我使用 Django 1.4
我的问题在哪里

=========================

当我更改呈现 HTML 的函数时,我的问题得到解决:

def homepage(request):
return render_to_response('index.html')

def homepage(request):
return render_to_response('index.html', context_instance=RequestContext(request))

这是一个愚蠢的错误...谢谢...

最佳答案

如果您使用 ajax 发送表单并包含 jQuery,则有两种可能性:

  1. 手动将 csrfmiddlewaretoken 数据添加到您的 POST 请求
  2. 通过修改 jQuery ajax 请求 header 自动处理 CSRF token

1。手动添加csrfmiddlewaretoken

var data = {
csrfmiddlewaretoken: $('#myForm input[name=csrfmiddlewaretoken]').val(),
foo: 'bar',
};

$.ajax({
type: 'POST',
url: 'url/to/ajax/',
data: data,
dataType: 'json',
success: function(result, textStatus, jqXHR) {
// do something with result
},
});

2。自动化 CSRF token 处理

jQuery(document).ajaxSend(function(event, xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function sameOrigin(url) {
// url could be relative or scheme relative or absolute
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
// or any other URL that isn't scheme relative or absolute i.e relative.
!(/^(\/\/|http:|https:).*/.test(url));
}
function safeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
});

但是:据说修改 ajax 请求 header 是不好的做法。因此,我会选择第一个解决方案。

来源:Cross Site Request Forgery protection: AJAX

关于python - CSRF token 丢失或不正确,即使我有 {% csrf_token %} 但我使用 HttpResponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11152717/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com