django 里面的cleaned_data少了数据

用djang写一个用户注册,在req.POST中传入了4个参数

clipboard.png
然后form里面的data显示也是这几个数据

clipboard.png

但是在form.is_valid()时发现,
self.cleaned_data里面没有了enpassword,但是self.data里面还有

clipboard.png

为什么呢
代码如下:
forms.py

from django import forms

class UserForm(forms.Form):

email=forms.EmailField(label='邮箱')

username=forms.CharField(max_length=20,label='用户名')

password=forms.CharField(max_length=20,label='密码')

enpassword=forms.CharField(max_length=20,label='确认密码')

def clean_password(self):

password=self.cleaned_data['password']

enpassword=self.cleaned_data['enpassword']

if password==enpassword:

return password

else:

raise forms.ValidationError('Please re-enter your password.')

view.py

def registe_view(req):

if req.method=='POST':

form=UserForm(req.POST)

if form.is_valid():

username=form.cleaned_data['username']

email=form.cleaned_data['email']

password=form.cleaned_data['password']

enpassword=form.cleaned_data['enpassword']

user=authenticate(username=username,email=email,password=password)

user=User.objects.create_user(username=username,email=email,password=password)

user.save()

context={'title':'注册','status':'成功'}

return render(req,'redirect.html',context=context)

else:

form=UserForm()

return render(req,'login/registe.html',context={'form':form,'value':'注册'})

html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>{{ value }}</title>

</head>

<body>

<form method="post" enctype="multipart/form-data">

{% csrf_token %}

{% for field in form %}

<p class="fieldWrapper">

{{ field.label_tag }}{{ field }}

{{ field.errors }}

</p>

{% endfor %}

<input type="submit" value="{{ value }}">

</form>

</body>

</html>

回答:

看了很久都没看出哪里有问题啊。233...
也没看见你在哪里执行了 clean_password 这个类函数。

    def clean_password(self):

password=self.cleaned_data['password']

enpassword=self.cleaned_data['enpassword']

if password==enpassword:

return password

else:

raise forms.ValidationError('Please re-enter your password.')

不明白上面代码里面的 return password 什么意义。
建议修改成:

    def clean(self):

cleaned_data = super(UserForm, self).clean()

password=cleaned_data['password']

enpassword=cleaned_data['enpassword']

if not password==enpassword:

raise forms.ValidationError('Please re-enter your password.')

回答:

改成clean_enpassword,改成clean不会跳提示信息,不知道为什么

回答:

请问一下你解决了嘛. 我也遇到同样的问题了 ,我是只取到password的值,没有username的值 好急啊

以上是 django 里面的cleaned_data少了数据 的全部内容, 来源链接: utcz.com/a/160352.html

回到顶部