Django csrftoken未设置

时间:2015-12-28 18:19:23

标签: ajax django cookies csrf

我尝试按照docs使用Django进行AJAX POST - 如果我已登录该网站,这样可以正常工作。但是,如果我已注销或使用隐身模式,则我的csrftoken尚未设置 - 我已尝试将{{csrf_token}}置于检查状态,这会返回值NOTPROVIDED

什么可能导致令牌不生成?

我正在运行Django 1.7。

视图的简化版本(没有ensure_csrf_cookie装饰器):

def pg2(request, **kwargs):
    name_slug = kwargs.pop('name_slug')
    num_guests = request.session['guests']
    date = request.session['date']

    venue = get_object_or_404(Venue, name_slug=name_slug)
    try:
        rental = request.session['rental']
    except:
        rental = None

    filtered_items = Item.objects.filter(venue_id=venue.pk)

    context = {'venue':venue, 'rental':rental, 'filtered_items':filtered_items}
    return render(request, 'app/pg2.html', context)

设置中的中间件:

MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.common.BrokenLinkEmailsMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.contrib.redirects.middleware.RedirectFallbackMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'project.middleware.SecureRequiredMiddleware', # to add SSL
)

1 个答案:

答案 0 :(得分:0)

您需要在所有Ajax POST中明确发送cookie。要首先获取cookie,您可以在JS文件中运行以下命令:

var c = getCookie('csrftoken');

但是要使上面的getCookie函数工作,请使用给定的代码创建一个新的javascript文件,并在html模板中调用它。希望它适合你!

<强> ajaxpostcsrf.js

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]);
        if (cookie.substring(0, name.length + 1) == (name + '=')) {
            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
            break;
        }
    }
}
return cookieValue;
}
$.ajaxSetup({
    headers: { "X-CSRFToken": getCookie("csrftoken") }
});