I am learning Django, and i stumbled upon something that I need help 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 do not match'
return False
else:
return True
def is_valid(self):
valid = super(UserForm,self).is_valid()
password_matched = self.password_matched()
if valid and 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, I am checking if pw1 == pw2
,
after checking, I wish to set the user's password to password1.
I initially used the line user.set_password(user.password1)
but it complained that User object doesn't have password1
, yet it worked when I used password
.
Why is that? Thanks.
The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.
form. cleaned_data returns a dictionary of validated form input fields and their values, where string primary keys are returned as objects. form. data returns a dictionary of un-validated form input fields and their values in string format (i.e. not objects).
non_field_errors () This method returns the list of errors from Form. errors that aren't associated with a particular field. This includes ValidationError s that are raised in Form. clean() and errors added using Form.
{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.
You should be ideally using the clean
method for this, and never be touching the is_valid
method.
Something like this:
def clean(self):
cd = self.cleaned_data
password1 = cd.get("password1")
password2 = cd.get("password2")
if password1 != password2:
#Or you might want to tie this validation to the password1 field
raise ValidationError("Passwords did not match")
return cd
Now, in the views,
def register(request):
#blah...
form = UserForm(request.POST or None)
if request.method == "POST":
if form.is_valid(): #This would call the clean method for you
user = User.objects.create(...)
user.set_password(form.cleaned_data.get("password1"))
user.save()
else: #Form is invalid
print form.errors #You have the error list here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With