我正在尝试允许用户更改密码。如果表单填写正确,则会更改。但如果不是,那么没有任何警告或任何东西,我只是被重定向到同一页面。我不明白为什么,我也使用相同的方法用于其他形式。
我的表格:
class PasswdForm(forms.Form):
New_password = forms.CharField(widget=forms.PasswordInput(), label='New password', max_length=30)
Repeat_new_password = forms.CharField(widget=forms.PasswordInput(), label='Repeat new password', max_length=30)
class Meta:
fields = ('New_password', 'Repeat_new_password')
def clean_new_password(self):
p1 = self.cleaned_data.get('New_password')
print ("p1", p1)
if len(p1) <= 6:
print ("Password is too short. Minimum 6 symbols.")
raise forms.ValidationError(
('Password is too short. Minimum 6 symbols.'))
return p1
我实际上可以在终端上看到这些打印件。
我的网址:
url(r'^loggedin/profile/passwd/$', 'userprofile.views.user_profile_passwd'),
我的功能:
@login_required
def user_profile_passwd(request):
args = {'full_name': request.user.username}
args.update(csrf(request))
if request.method == 'POST':
form = PasswdForm(request.POST)
if form.is_valid():
if form.cleaned_data['New_password'] == form.cleaned_data['Repeat_new_password']:
user = request.user
passw = make_password(form.cleaned_data['New_password'])
user.password = passw
user.save()
return render(request,'profile.html')
else:
messages.warning(request, "Your password was not changed.")
args['form'] = PasswdForm()
return render(request, 'passwd.html', args)
else:
form = PasswdForm()
args = {'full_name': request.user.username}
args.update(csrf(request))
args['form'] = PasswdForm()
return render(request, 'passwd.html', args)
有谁知道可能出现什么问题?
这也是我的html模板中的噱头:
{% block content %}
<section>
<h2>Change password:</h2>
<form action="/accounts/loggedin/profile/passwd/" method="post"autocomplete="off">{% csrf_token %}
<ul>
{{form.as_ul}}
</ul>
<input type="submit" name="submit" value="Save changes">
</form>
</section>
{% endblock %}
答案 0 :(得分:3)
当您的表单无效时,您将为args
分配一个新的空表单。这就是你没有看到错误的原因。
if request.method == 'POST':
form = PasswdForm(request.POST)
if form.is_valid():
#...
else:
messages.warning(request, "Your password was not changed.")
args['form'] = form #instead of PasswdForm()
return render(request, 'passwd.html', args)
请在PEP 8上阅读,特别是Method Names and Instance Variables 您的表单字段不应以大写字母开头。