使用Django Rest框架在Pre_Save中提高验证错误 [英] Raise Validation Error In Pre_Save Using Django Rest Framework
问题描述
我无法使用Django Rest框架提高验证错误。
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
我的问题是如果此代码失败,如何提高验证错误。我尝试在pre_save方法中提出错误,但这不能正常工作。它实际上导致了从Django返回的HTML响应,而不是Django Rest框架的消息。
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.
推荐答案
使用<一个href =http://www.django-rest-framework.org/api-guide/exceptions =nofollow> django休息框架异常。例如:
from rest_framework.exceptions import ParseError
...
parsed_data = self.parse(some_data)
if not parsed_data:
raise ParseError('Some error occurred')
另请注意,您不会在其中看到404,因为它使用django.http.Http404异常。这些都是由API以很好的方式返回的。
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.
注意:
您可能需要查看将您的逻辑放在序列化程序中。
这篇关于使用Django Rest框架在Pre_Save中提高验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!