IntegrityError:使用django美味馅饼登录用户时,重复键值违反了唯一约束

时间:2012-10-04 15:00:42

标签: django tastypie

这是我的UserLoginResource:

class UserLoginResource(ModelResource):

    class Meta:
        object_class = User
        queryset = User.objects.all()
        allowed_methods = ['post','get']
        include_resource_uri = False
        resource_name = 'login'
        excludes = ['is_active','is_staff','is_superuser']
        authentication = SillyAuthentication()
        authorization = SillyAuthorization()

    def obj_create(self, bundle, request=None, **kwargs):
        try:
            bundle = super(UserLoginResource, self).obj_create(bundle,request,**kwargs)
            bundle.obj.set_password(bundle.data.get('password'))
            bundle.obj.set_username(bundle.data.get('username'))
            bundle.obj.save() 
            return bundle
        except IntegrityError:
            raise BadRequest('The username exists')

    def dehydrate(self,bundle):
        bundle.data['custom_field'] = "Whatever you want"
        return bundle

如果我使用已存在的用户名和密码发布,则会出现500错误,指出完整性错误,并且用户名已存在。

  1. 我如何登录?
  2. 即使出现错误(假设用户名不存在,我如何美化错误回复?

1 个答案:

答案 0 :(得分:0)

  1. 使用此代码创建用户对象而不是登录

  2. 请参阅tastypie.validation