rest framework错误笔记——身份验证和权限
按照官网教程(http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/)走到最后一步验证时,命令窗口执行http POST http://127.0.0.1:8000/snippets/ code="print 123"后
{ "detail": "Authentication credentials were not provided." }
这条结果是因为#视图类中的写法(1):
authentication_classes = ( BasicAuthentication, ) permission_classes = ( IsAuthenticatedOrReadOnly, )
若根据教程的写法(2)
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly,)
则返回如下结果:
{ "detail": "You do not have permission to perform this action." }
根据版本不同视图类中的代码不同则提示不同,虽然无论哪种结果都代表没有权限,但还是建议用写法(1),因为写法(2)会导致执行http -a admin:password123 POST http://127.0.0.1:8000/snippets/ code="print 789"后仍然验证不通过返回上面的结果。
当这些设置完成后,执行http -a admin:password123 POST http://127.0.0.1:8000/snippets/ code="print 789"报错:
Exception Type: IntegrityError at /snippets/
Exception Value: NOT NULL constraint failed: snippets_snippet.owner_id
只需将视图类中post方法里面的
serializer.save()
改为:
serializer.save(owner=self.request.user)