請幫忙解決問題。發送請求時從哪裏獲取值?
HTML:
<div class="modal fade" id="commonModal" tabindex="-1" role="dialog" aria-labelledby="commonModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="commonModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default but_cancel" data-dismiss="modal">Отменить</button>
<button type="button" class="btn btn-primary but_ok" data-dismiss="modal">Ok</button>
</div>
</div>
</div>
</div>
我發送AJAX請求如下:
$('#commonModalLabel').text('Удалить профиль?');
$('#commonModal .modal-body').html('Возможность восстановить профиль будет доступна в течение двух недель. Для восстановления нужно отправить <a href="mailto:[email protected]">администратору</a> ресурса письмо с почтового адреса, который был указан в профиле.');
$('#commonModal').modal('show');
$('#commonModal .but_ok').on('click', function(){
console.log('ok');
$.ajax({
url: "/accounts/delete_profile/",
type: 'POST',
dataType:"json",
data: {},
success: function(data) {
if(data.result == true){
$('#mySmallModalLabel').text('Профиль удалён');
$('#infoModal').modal('show');
}
}
});
});
views.py:
def delete_profile(request):
result = False
if request.method == "POST" and request.is_ajax():
username = request.POST.get('username', '')
try:
entry = User.objects.get(username=username)
entry.is_active = 0
entry.save()
except:
pass
else:
result = True
data = {
'result': result,
}
return HttpResponse(json.dumps(data), content_type='application/json')
的問題是,在日誌,以下錯誤消息:
故宮(CSRF令牌丟失或不正確。): /帳號/ delete_profile/
的形式的情況下,我會送令牌如下:
{% csrf_token %}
,但在我沒有形式(!)的情況。請告訴我在哪裏獲取令牌以及如何發送
JavaScript是可能沒有發送您的CSRF令牌。您應該將其添加到'ajax()'調用中的'data:{}'屬性中。你可以從MataTag中獲得它。 – 2014-09-23 11:07:41
以及獲取此值的位置?我也沒有形成 – dert 2014-09-23 11:08:44
在這裏檢查:https://docs.djangoproject.com/en/dev/ref/contrib/csrf/ – 2014-09-23 11:10:25