2014-01-21 65 views
0

Twitter的风格错误,我需要找到一种常见的方式与TastyPie例如以错误报告给我的用户在Twitter的看着这也是他们始终显示错误:Django的TastyPie

{"errors":[{"message":"Sorry, that page does not exist","code":34}]} 

因此错误是一个数组的错误。

我试图做沿着相同的路线东西TastyPie这样的:

def is_valid(self, bundle, request=None): 
     errors = {} 
     # Check if user already exists before allowing API to create a new one. 
     this_email = bundle.data.get('email', None) 
     object_count = Member.objects.filter(email=this_email).count() 
     if object_count != 0: 
      errors['ERRORS'] = 'Duplicate email address' 
     return errors 

但你可以看到它不是很干燥,输出是不正确的:

{"object_register":{"ERRORS":"Sorry, that page does not exist"}} 

我有也试过:

reply = {} 
reply['errors'] = [{'message': 'Sorry we could not log you in.'}] 
return self.create_response(request, reply, HttpUnauthorized) 

所以我的问题是,有可能实现'Twitter'风格输出的错误以干的方式使用Tatypie?如果有这样的例子吗?

回答

1

要自定义您的错误输出,您可以覆盖资源本身的is_valid方法。

MyResource(ModelRecource): 
    def is_valid(self, bundle): 
     errors = self._meta.validation.is_valid(bundle, bundle.request) 

     if errors: 
      bundle.errors['errors'] = [errors] 
      return False 

     return True