django - 如何使用 Django REST 框架制作 POST 简单的 JSON? CSRF token 丢失或不正确

标签 django json post django-rest-framework

如果有人向我展示如何使用带有 Django REST 框架的 JSON 发出简单的 POST 请求,我将不胜感激。我在教程中的任何地方都没有看到任何这样的例子?

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

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

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

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


http://localhost:8000/lakesShoreProperties/role

网址

http://localhost:8000/lakesShoreProperties/roles

确实可以处理 GET 请求,我可以提取数据库中的所有角色,但我似乎无法创建任何新角色。我没有设置权限。我在views.py中使用标准 View

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

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

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

错误信息是:

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

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

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'

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

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

嗯,原来我的json无效?

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

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

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

更新:问题在于使用 PostMan 发送 POST,而不是在后端。见 https://stackoverflow.com/a/17508420/203312

最佳答案

在 Django REST Framework 中,CSRF 是默认豁免的。因此, curl POST 请求可以正常工作。 POSTMAN 请求调用返回的 CSRF 不正确,因为如果在 Cookie 中找到 POSTMAN 包含 csrf token 。您可以通过清理 Cookie 来解决此问题。

关于django - 如何使用 Django REST 框架制作 POST 简单的 JSON? CSRF token 丢失或不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17507206/

相关文章:

php - 如果 (!empty($_POST)) 不工作

sql - Django与select_related的反向关系

regex - django 尝试了这些 url 模式

c# - 将没有属性名称的 Json 解析为 C#

java - Jackson mixins 抛出 stackoverflow 错误

java - java POJO中使用注释限制输入长度

html - 博主数据 :post. firstImageUrl

django - 在 OS X 上安装 Spatialite for python (GeoDjango)

django - Django 中的多个数据库

php - VBA (Access 2013) HTTP POST 不传递参数