python - Tastypie 如何将模型中的错误正确地反馈给用户?

标签 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。

最佳答案

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

关于python - Tastypie 如何将模型中的错误正确地反馈给用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19449132/

相关文章:

python - Django Tastypie - 仅包含对象详细信息的资源

python - 使用 Selenium 和 PhantomJS 进行表提取永远不会完成

python - 如何提取lxml中指定的div表数据?

python - python 函数中 r[( s== 'even'::2) 的含义

python - 数据库和Python

javascript - Django + Chart.js : Cannot get two bar charts on the same graph with appropriate data

python - 无法在 django admin 上发布 - 无法将字节连接到字符串

python - 如何使用电子邮件登录用户并使用 Django Rest Framework JSON Web token 将其注销?

python - uwsgi 破管 - django, nginx

python - Django Tastypie 通用关系