python - 禁止(未设置 CSRF cookie。)Django

标签 python django angular

我正在尝试做一个端点API。为此,我使用 django。

我在 urls.py 中的网址是:

path('tutorials/', tutorial_list_test.as_view()),

我的views.py就像

class tutorial_list_test(GuestOnlyView, FormView):
    print("test");
    @api_view(['GET', 'POST', 'DELETE'])
    def tutorial_list(self):
        request = self.request;
        if request.method == 'POST':
            alldata=request.POST
            username = alldata.get("username", "0")
            print("POST name: " + username)
            return Response('The tutorial does not exist', status=status.HTTP_404_NOT_FOUND) 

但是当我执行请求时,我每次都会遇到相同的错误“Forbidden (CSRF cookie not set.):/accounts/tutorials/

所以我做了一些研究,我可以看到几个建议的解决方案。 第一个是使用 csrf_exempt 但它对我不起作用:

path('tutorials/', csrf_exempt(tutorial_list_test.as_view())),

我用过的所有方法都是一样的。即使我从 settings.py 中删除这一行,也不会发生任何变化

  #  django.middleware.csrf.CsrfViewMiddleware',

为了测试,我使用 Postman,但即使使用我的 Angular 前端,它也会做同样的事情。

const formData = new FormData()
formData.append('username', this.username_signup);

this.http.post('http://127.0.0.1:8000/accounts/tutorials/', formData)
.map((data: Response) => {
  if (data !== null) {
    console.log(JSON.stringify(data));
  };
}).subscribe(response => console.log(response))

我想知道您是否知道我该怎么做。

因为我需要能够访问我的模型,所以不使用类并直接创建 def 不是一个选项,即使它有效。

(我尝试过,如果我删除类(class)并且我的路线仅链接到我的默认教程列表,那么我的请求实际上会通过)。 谢谢。

最佳答案

from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
@api_view(['GET', 'POST', 'DELETE'])
    def tutorial_list(self):
        # code

关于python - 禁止(未设置 CSRF cookie。)Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72067667/

相关文章:

angular - 在 ionic 2 应用程序中使用 promise with observable

python - 无法导入 Decimal 模块

python - 传递相同形式的序列? - Django

python - 用于具有多个左连接的 SQL 查询的 Django ORM

javascript - 将所有 typescript 文件输出生成到单个 js 文件时,AngularJs 2 无法启动

angular - 将页面选择设置为 PrimeNG p-table 的最后一页

Python 子进程 - 通过 SSH 运行多个 shell 命令

python - Django:服务用户上传的文件

python - Python 中的可选正则表达式组失败

django - 使用 Django 应用程序在 Heroku 上获取 Twitter 流