Django cleaned_data.get('obj')方法不返回任何内容 [英] Django cleaned_data.get('obj') method returns none
问题描述
我正在用django写一些密码确认表。但是我很困惑,因为 self.cleaned_data.get('confirm_password')
始终不返回任何值,因此我的密码永远不会相互匹配。
I'm doing a little password confirmation form in django. But Im confused as the self.cleaned_data.get('confirm_password')
always returns none and hence my passwords never match to one another.
在 forms.py
def clean_password(self):
password = self.cleaned_data.get("password")
confirm_password = self.cleaned_data.get("confirm_password")
if password != confirm_password:
print(password)
print(confirm_password)
raise forms.ValidationError(
"Password and password confirmation does not match"
)
return password
self.cleaned_data .get('password')
返回键入的密码,但confirm_password不返回。
self.cleaned_data.get('password')
returns the typed password but the confirm_password doesnt.
在 view.py
当我在清理之前看到收到的数据时,confirm_password会按原样显示
In the view.py
when I see the received data before cleaning, the confirm_password shows as it is
......................user = UserRegister(request.POST)
print(request.POST.get('confirm_password'))
if user.is_valid():
print('valid')..........................
这可能是什么原因?
在 forms.py
中有表单声明部分
first_name = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'First Name'}))
last_name = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'Last Name'}))
username = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'Username'}))
email = forms.EmailField( required=True, widget=forms.widgets.EmailInput(attrs={'placeholder': 'Email'}))
password =forms.CharField(required=True, widget=forms.widgets.PasswordInput())
confirm_password =forms.CharField(required=True, widget=forms.widgets.PasswordInput())
class Meta:
model=User
fields=['first_name','last_name','username','email','password','confirm_password']
推荐答案
clean_fieldname
按字段声明顺序调用的方法,因此目前 clean_password
被称为 cleaned_data
不包含 confirm_password
。您可以使用 clean_confirm_password
方法执行此验证:
clean_fieldname
methods called in order of fields declaration, so at the moment clean_password
is called cleaned_data
does not contain confirm_password
. You can perform this validation in clean_confirm_password
method:
def clean_confirm_password(self):
password = self.cleaned_data.get("password")
confirm_password = self.cleaned_data.get("confirm_password")
if password != confirm_password:
print(password)
print(confirm_password)
raise forms.ValidationError(
"Password and password confirmation does not match"
)
return password
或仅使用 clean
方法进行验证,该方法需要访问多个表单字段。
or just use clean
method for validation that requires access to multiple form fields.
这篇关于Django cleaned_data.get('obj')方法不返回任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!