为api提高django形式的验证错误

时间:2013-07-30 20:29:13

标签: django django-forms django-views

我是django和python开发的新手,在理解如何处理异常方面很天真。

我通过调用方法寄存器通过api调用注册用户,并希望在注册时推送成功状态或错误消息。

def register(self,request, **kwargs):

        try:    
            data = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
            email = data['email']
            password = data['password']
            firstname = data['firstname']
            lastname = data['lastname']
            newdata = {'email' : email , 'password1': password , 'password2':password, 'firstname':'firstname' , 'lastname':lastname }

            registrationform = UserEmailRegistrationForm(newdata)
            print registrationform.errors.as_text
            print registrationform.cleaned_data
            cleaned_data = registrationform.cleaned_data
            if Site._meta.installed:
                site = Site.objects.get_current()
            else:
                site = RequestSite(request)

            new_user = RegistrationProfile.objects.create_inactive_user(cleaned_data['username'],cleaned_data['email'],cleaned_data['password1'], site)
            signals.user_registered.send(sender=self.__class__,
                                         user=new_user,
                                         request=request,**cleaned_data)
            registerUser = collections.OrderedDict()
            registerUser['return']='0'
            registerUser['code']='0'
            registerUser['message']='registered user'
            return HttpResponse(registerUser, content_type="application/json")
        except Exception, e:
            logging.exception(e)
            registerUser = collections.OrderedDict()
            registerUser['return']='0'
            registerUser['code']='0'
            registerUser['message']='registered user'
            return HttpResponse(registerUser, content_type="application/json")

当我执行此操作时,例如使用已注册的电子邮件,我在registrationform.errors.as_text中获得以下内容

bound method ErrorDict.as_text of {'email': [u'A user with that email already exists.']}>

对异常进行编码的正确方法是什么,以便在表单经过验证并且用户已注册时可以传递成功消息,如果出现验证错误则返回错误消息?

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

您可能希望查看表单的is_valid()方法:https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.is_valid

例如

if registrationform.is_valid():
   //do your stuff
   ....
   register['error'] = False
else:
   //return the errors
   registerUser['message'] = _('Oops! Please fix the following errors')
   register['error'] = True
   register['errors'] = registrationform.errors
   ....