django - Extending form.is_valid() -


i learning django, , stumbled upon need with:

forms.py

class userform(forms.modelform):     password1 = forms.charfield(widget=forms.passwordinput())     password2 = forms.charfield(widget=forms.passwordinput())      class meta:         model = user         fields = ('username', 'email', 'password1','password2')      def password_matched(self):         if self.data['password1'] != self.data['password2']:             self.errors['password'] = 'passwords not match'             return false         else:             return true      def is_valid(self):         valid = super(userform,self).is_valid()         password_matched = self.password_matched()         if valid , password_matched:             return true         else:             return false 

views.py

def register(request):      #blah...      user.set_password(user.password)      # user.set_password(user.password1) doesn't work ! why!? 

so basically, checking if pw1 == pw2,
after checking, wish set user's password password1.
used line user.set_password(user.password1) complained user object doesn't have password1, yet worked when used password.

why that? thanks.

you should ideally using clean method this, , never touching is_valid method.

something this:

def clean(self):     cd = self.cleaned_data      password1 = cd.get("password1")     password2 = cd.get("password2")      if password1 != password2:         #or might want tie validation password1 field         raise validationerror("passwords did not match")        return cd 

now, in views,

def register(request):    #blah...    form = userform(request.post or none)    if request.method == "post":        if form.is_valid(): #this call clean method            user = user.objects.create(...)            user.set_password(form.cleaned_data.get("password1"))            user.save()        else: #form invalid            print form.errors #you have error list here.  

Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -