Django的没有在cookie中csrftoken [英] django no csrftoken in cookie

查看:280
本文介绍了Django的没有在cookie中csrftoken的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我测试做一个POST Ajax请求

I'm testing to make a POST ajax request

由于没有csrftoken我得到了一个403

I got a 403 because of no csrftoken

我跟着文档,它仍然无法正常工作。

I followed the Document, it still not work.

我发现了一个名为cookie的csrftoken是

I found the cookie named csrftoken is empty

这是用于 $。饼干(csrftoken)返回NULL

有人可以告诉我的理由!

can someone tell me the reason !!

如何设置csrftoken到的Cookie

how to set csrftoken into cookie

THX !!

推荐答案

我想你应该提供code,你怎么弄的CSRF令牌在HTML / JS code和设置您的中间件。

I think you should provide the code how you get the csrf token in your HTML/JS code and settings for your middlewares.

首先,你应该检查 django.middleware.csrf.CsrfViewMiddleware 已打开。

First of all you should check that django.middleware.csrf.CsrfViewMiddleware is turned on.

我有一个类似的问题,当蟒蛇code我用 request.META.get('CSRF_COOKIE')获得令牌。

I had a similar issue, when in python code I used request.META.get('CSRF_COOKIE') to get the token.

在使用此标记模板 - {%csrf_token%} 的Django指出,该令牌呈现并设置cookie的 CsrfViewMiddleware.process_response 。如果你在其他的方式Django的令牌值将错过这个标志。因此,它会为你生成一个令牌,但不会设置相应的cookie。

When you use this token in template - {% csrf_token %} Django notes that the token was rendered and sets the Cookie in CsrfViewMiddleware.process_response. If you get the token value in other way Django will miss this flag. So it will generate you a token but will not set the corresponding cookie.

我有2个解决方法在code。你应该把它添加到您的视图,用于生成与JS code模板。

I have 2 workarounds in code. You should add it to your views that are used to generate templates with JS code.

1 您可以强制Django的设置CSRF的Cookie:

1. You can force Django to set the CSRF Cookie:

# Force updating CSRF cookie
request.META["CSRF_COOKIE_USED"] = True

2 Django的设置是否自动调用CSRF_COOKIE_USED 的get_token

2. Django sets the CSRF_COOKIE_USED automatically if you call get_token

from django.middleware.csrf import get_token
# don't use direct access to request.META.get('CSRF_COOKIE')
# in this case django will NOT send a CSRF cookie. Use get_token function
csrf_token = get_token(request)

这个解决方案的每个人应该独立工作。我建议使用的get_token

这篇关于Django的没有在cookie中csrftoken的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆