Raise Validation Error In Pre_Save Using Django Re

2019-07-17 11:01发布

I am having difficulty raising a validation error using the Django Rest Framework.

I have an owner field. The owner field needs to access the request object. The documentation suggests using the following approach:

def pre_save(self, obj):
    obj.owner = self.request.user

My problem is how to raise a validation error if this code fails. I tried raising an error inside the pre_save method, but this doesn't work properly. It actually results in an HTML response coming back from Django, rather than a message from the Django Rest Framework.

1条回答
迷人小祖宗
2楼-- · 2019-07-17 11:52

Use the django rest framework exceptions. For example:

from rest_framework.exceptions import ParseError

...

parsed_data = self.parse(some_data)
if not parsed_data:
    raise ParseError('Some error occurred')

Also note that you won't see a 404 in there, that's because it uses the django.http.Http404 exception. These are returned by the API in a nice way.

Note:

If you are doing a significant amount of validation you might want to look at placing your logic in the serializer.

查看更多
登录 后发表回答