【发布时间】:2014-03-10 19:51:10
【问题描述】:
我正在使用 Django-Rest-Framework API 构建一个 Django 应用程序。我已经构建了一个 API 端点,如下所示。
我希望能够从我的浏览器发布数据。我希望这个 POST 操作从我的数据库中检索一个对象模型,该模型具有 URL 中给定的匹配主键。我想根据浏览器发布的数据修改检索到的对象。
如果我可以用我的 ViewSet 抓取发布的数据,我就完成了。但是当我尝试执行该视图集的 update() 函数时,我得到了一个 CSRF 错误。
来自我的 urls.py 文件:
router.register(r'replyComment', views.ReplyComment, base_name="replyComment")
来自我的 views.py 文件:
class ReplyComment(viewsets.ViewSet):
def update(self,request,pk=None):
try:
origComment = Comment.objects.get(pk=pk)
# Do something here that modifies the state of origComment and saves it.
return Response(
json.dumps(True),
status=status.HTTP_200_OK,
)
except Exception as exception:
logger.error(exception)
return Response(status=status.HTTP_400_BAD_REQUEST)
我在 Chrome 浏览器中使用 Advanced Rest Client (ARC) 工具。当我使用 POST 方法将 ARC 工具指向 http://127.0.0.1:3001/api/replyComment/2/ 时,出现以下错误:
{
detail: "CSRF Failed: CSRF token missing or incorrect".
}
This doc 表示我应该使用@csrf_exempt 装饰器。我把那个装饰器放在上面的 update() 函数上。不过好像没什么区别。
我需要进行哪些更改以确保我的 POST 按预期工作?
【问题讨论】:
标签: python django rest django-csrf