如何使用 Django REST 框架制作 POST 简单 JSON?CSRF 令牌丢失或不正确 [英] How to make a POST simple JSON using Django REST Framework? CSRF token missing or incorrect

查看:27
本文介绍了如何使用 Django REST 框架制作 POST 简单 JSON?CSRF 令牌丢失或不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有人向我展示如何使用 JSON 和 Django REST 框架发出简单的 POST 请求,我会很感激.我在教程中的任何地方都没有看到任何示例?

这是我想要发布的角色模型对象.这将是一个全新的角色,我想添加到数据库中,但出现 500 错误.

<代码>{"name": "经理",描述":管理人员"}

这是我在 bash 终端提示符下的 curl 请求:

curl -X POST -H "Content-Type: application/json" -d '[{"name": "经理",描述":管理人员"}]'http://localhost:8000/lakesShoreProperties/role

网址

http://localhost:8000/lakesShoreProperties/roles

是否可以处理 GET 请求,我可以拉下数据库中的所有角色,但似乎无法创建任何新角色.我没有设置权限.我在 views.py 中使用标准视图

class RoleDetail(generics.RetrieveUpdateDestroyAPIView):查询集 = Role.objects.all()serializer_class = RoleSerializer格式 = 无类 RoleList(generics.ListCreateAPIView):查询集 = Role.objects.all()serializer_class = RoleSerializer格式 = 无

在我的 urls.py 中,相关的 url - 视图映射是正确的:

url(r'^roles/$', views.RoleList.as_view()),url(r'^role/(?P<pk>[0-9]+)/$', views.RoleDetail.as_view()),

错误信息是:

<代码>{"detail": "CSRF 失败:CSRF 令牌丢失或不正确."}

这里发生了什么,对此有什么解决方法?localhost 是跨站点请求吗?我已将 @csrf_exempt 添加到 RoleDetailRoleList 但它似乎没有改变任何东西.这个装饰器甚至可以添加到类中,还是必须添加到方法中?添加 @csrf_exempt 装饰,我的错误变成:

请求方式:POST请求网址:http://127.0.0.1:8000/lakeshoreProperties/roles/Django 版本:1.5.1异常类型:属性错误异常值:函数"对象没有属性as_view"

然后我在整个应用程序中禁用了 CSRF,现在我收到了这条消息:

{"non_field_errors": ["Invalid data"]} 当我知道我的 JSON 对象是有效的 json 时.这是一个非字段错误,但我卡在了这里.

好吧,原来我的json无效?

<代码>{"name": "管理员",描述":管理人员"}

对比

<预><代码>[{"name": "管理员",描述":管理人员"}]

有括号 [],会导致 POST 请求失败.但是使用 jsonlint.com 验证器,我的两个 json 对象都会验证.

更新:问题在于通过 PostMan 发送 POST,而不是在后端.请参阅 https://stackoverflow.com/a/17508420/203312

解决方案

您可能需要随请求一起发送 CSRF 令牌.查看 https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/#csrf-ajax

更新:因为您已经尝试免除 CSRF,所以这可能会有所帮助(取决于您使用的 Django 版本):https://stackoverflow.com/a/14379073/977931

Would appreciate someone showing me how to make a simple POST request using JSON with Django REST framework. I do not see any examples of this in the tutorial anywhere?

Here is my Role model object that I'd like to POST. This will be a brand new Role that I'd like to add to the database but I'm getting a 500 error.

{
    "name": "Manager", 
    "description": "someone who manages"
}

Here is my curl request at a bash terminal prompt:

curl -X POST -H "Content-Type: application/json" -d '[
{
    "name": "Manager", 
    "description": "someone who manages"
}]'


http://localhost:8000/lakesShoreProperties/role

The URL

http://localhost:8000/lakesShoreProperties/roles

DOES work with a GET request, and I can pull down all the roles in the database, but I can not seem to create any new Roles. I have no permissions set. I'm using a standard view in views.py

class RoleDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Role.objects.all()
    serializer_class = RoleSerializer
    format = None

class RoleList(generics.ListCreateAPIView): 
        queryset = Role.objects.all()
        serializer_class = RoleSerializer
        format = None

And in my urls.py for this app, the relevant url - view mappings are correct:

url(r'^roles/$', views.RoleList.as_view()),
url(r'^role/(?P<pk>[0-9]+)/$', views.RoleDetail.as_view()),

Error message is:

{
    "detail": "CSRF Failed: CSRF token missing or incorrect."
}

What is going on here and what is the fix for this? Is localhost a cross site request? I have added @csrf_exempt to RoleDetail and RoleList but it doesn't seem to change anything. Can this decorator even be added to a class, or does it have to be added to a method? Adding the @csrf_exempt decorate, my error becomes:

Request Method: POST
Request URL:    http://127.0.0.1:8000/lakeshoreProperties/roles/
Django Version: 1.5.1
Exception Type: AttributeError
Exception Value:    
'function' object has no attribute 'as_view'

Then I disabled CSRF throughtout the entire app, and I now get this message:

{"non_field_errors": ["Invalid data"]} when my JSON object I know is valid json. It's a non-field error, but I'm stuck right here.

Well, it turns out that my json was not valid?

{
    "name": "admin", 
    "description": "someone who administrates"
}

vs

[
    {
        "name": "admin",
        "description": "someone who administrates"
    }
]

Having the enclosing brackets [], causes the POST request to fail. But using the jsonlint.com validator, both of my json objects validate.

Update: The issue was with sending the POST with PostMan, not in the backend. See https://stackoverflow.com/a/17508420/203312

解决方案

You probably need to send along the CSRF token with your request. Check out https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/#csrf-ajax

Update: Because you've already tried exempting CSRF, maybe this could help (depending on which version of Django you're using): https://stackoverflow.com/a/14379073/977931

这篇关于如何使用 Django REST 框架制作 POST 简单 JSON?CSRF 令牌丢失或不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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