2014-01-21 66 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