weixin_33674437 2015-12-28 18:19 采纳率: 0%
浏览 133

Django csrftoken未设置

I'm trying to using AJAX POST with Django as per the docs - this works fine if I'm logged in to the site. But if I'm logged out or using incognito, my csrftoken is not being set - I've tried putting {{csrf_token}} to check, which returns the value NOTPROVIDED.

What could be causing the token not to generate?

  • I'm using render so I don't think it's a context processor issue
  • The django.middleware.csrf.CsrfViewMiddleware is present, and I've not changed any default csrf settings
  • The ensure_csrf_cookie decorator works fine

I'm running Django 1.7.

Simplified version of the view (without the ensure_csrf_cookie decorator):

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)

My middleware in settings:

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条回答 默认 最新

  • 北城已荒凉 2015-12-28 18:29
    关注

    Youn need to explicitly send the cookie in all Ajax POSTs. To get the cookie in the first place, you can run the following in your JS file:

    var c = getCookie('csrftoken');
    

    But to make the above getCookie function work, create a new javascript file with the code as given and call it in your html template. Hope it works for you!

    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") }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码