gpt4 book ai didi

django - 扩展 form.is_valid()

转载 作者:行者123 更新时间:2023-12-03 11:59:38 27 4
gpt4 key购买 nike

我正在学习 Django,并且偶然发现了一些我需要帮助的东西:

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

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

所以基本上,我正在检查是否 pw1 == pw2 ,
检查后,我希望将用户的密码设置为password1。
我最初使用的线路 user.set_password(user.password1)但它提示 User 对象没有 password1 ,但是当我使用 password 时它起作用了.

这是为什么?谢谢。

最佳答案

理想情况下,您应该使用 clean方法,永远不要碰is_valid方法。

像这样的东西:

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

现在,在意见中,
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.

关于django - 扩展 form.is_valid(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30227119/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com