Django csrftoken未设置


                    

我正在尝试根据 docs使用Django将AJAX POST与Django一起使用 -如果我登录到该站点,则可以正常工作。 但是,如果我已注销或使用隐身模式,则未设置我的csrftoken-我尝试过尝试 {{csrf_token}} </ code>进行检查,该操作会返回值 NOTPROVIDED </ code> </ p>

是什么导致令牌无法生成? </ p>


  • 我正在使用 render </ code>,所以我认为这不是 </ li>
  • 存在 django.middleware.csrf.CsrfViewMiddleware </ code>,并且我没有更改任何默认的csrf设置</ li>
  • ensure_csrf_cookie < / code> 装饰器工作正常</ li>
    </ ul>

    我正在运行Django 1.7。</ p>

    视图的简化版本(没有 ensure_csrf_cookie </ code>装饰器):</ p>

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

         场地= get_object_or_404(地点,name_slug = name_slug)
         尝试:
             租赁= request.session ['rental']
         除了:
             租金=无

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

         context = {'venue':venue,'rental':rental,'filtered_items':filtered_items}
         返回render(请求,'app / pg2.html',上下文)
    </ code> </ pre>

    我在设置中的中间件:</ p>

      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',#添加SSL

    </ code> </ pre>
         </ div>

展开原文

原文

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个回答


您需要在所有Ajax POST中显式发送cookie。 要首先获取Cookie,可以在JS文件中运行以下代码:</ p>

  var c = getCookie('csrftoken');
</ code> </ pre>

但是要使上述getCookie函数正常工作,请使用给定的代码创建一个新的javascript文件,并在您的html模板中调用它。 希望它对您有用!</ p>

ajaxpostcsrf.js </ strong> </ p>

  function getCookie(name){
var cookieValue = null;
如果(document.cookie && document.cookie!=''){
     var cookies = document.cookie.split(';');
     for(var i = 0; i          var cookie = jQuery.trim(cookies [i]);
         如果(cookie.substring(0,name.length +1)==(name +'=')){
             cookieValue =解码URIComponent(cookie.substring(name.length + 1));
             打破;
         }
     }
}
返回cookieValue;
}
$ .ajaxSetup({
     标头:{“ X-CSRFToken”:getCookie(“ csrftoken”)}
});
code> </ pre>
     </ div>

展开原文

原文

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

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐