Tastypie如何将模型中的错误正确地提交回用户?

时间:2013-10-18 11:59:14

标签: python django tastypie

我正在使用Tastypie通过API调用创建用户(请参阅下面的api.py)。如您所见,任何错误都会触发相同的except IntegrityError。我希望我的模型能够将正确的错误消息发回给用户。示例请参见下面的模型管理器,当电子邮件为空时,错误“必须设置给定的电子邮件”应该作为IntegrityError错误返回给用户。

我该怎么做?

api.py

class CreateResource(ModelResource):
    """
    API Facet that creates and returns a new user with self.user_email
    as login and self.user_password as password.
    """
    class Meta:
        object_class = CompanyUser
        resource_name = 'accounts/create'
        fields = ['password1', 'password2', 'email', 'company']
        allowed_methods = ['post']
        queryset = CompanyUser.objects.all()
        serializer = urlencodeSerializer()

    def obj_create(self, bundle, request=None, **kwargs):
        try:
            CompanyUser.objects.create_user(email=bundle.data['email'],
                                            company=bundle.data['company'],
                                          )

        except IntegrityError:
            raise BadRequest('Username already exists')

模特经理

class EmailUserManager(BaseUserManager):

    def create_user(self, email, password=None, **extra_fields):
        """
        Creates and saves an EmailUser with the given email and password.
        """
        now = timezone.now()
        if not email:
            raise ValueError('The given email must be set')
        email = EmailUserManager.normalize_email(email)
        user = self.model(email=email, is_staff=False, is_active=True,
                          is_superuser=False, last_login=now,
                          date_joined=now, **extra_fields)

        user.set_password(password)
        user.save(using=self._db)
        return user

我认为我的选择是:

1)在api.py中逐个检查所有参数(这似乎很糟糕,因为我的模型已经这样做了)然后为我遇到的每个问题提出IntegrityError,即电子邮件空白。

if bundle.data['email'] = '':
    raise BadRequest('no email') 

2)以某种方式将错误从管理器返回到api.py文件并引发动态IntegrityError。

1 个答案:

答案 0 :(得分:2)

如果您使用TastyPie,请查找validation。然后,您可以使用forms.py方法进行验证。