请帮助解决问题。
我用密码更改的形式制作了一个页面。但是在第一次启动时(在用户将数据输入表单之前)提示“是必填字段”。
仅当用户错误地提交完整的表单时,我才需要显示这些提示。
urls.py:
urlpatterns = patterns('drummersaransk',
url(r'^$', 'views.page'),
url(r'^userprofile/password_page/', 'views.password_page'),
url(r'^userprofile/password_page_changed/', 'views.password_page_changed'),
url(r'^admin/', include(admin.site.urls)),
)
views.py:
@login_required
def password_page(request):
if request.method == 'POST':
form = ChangePasswordForm(request.POST, request=request)
if form.is_valid():
username = User.objects.get(username__exact=request.user.username)
username.set_password(form.cleaned_data.get('password1'))
username.save()
return HttpResponseRedirect('/userprofile/password_page_changed/')
else:
form = ChangePasswordForm(request.POST or None, request=request)
t = loader.get_template('password_page.html')
c = RequestContext(request, {
'form': form,
}, [custom_proc])
return HttpResponse(t.render(c))
password_page.html:
{% extends "page_base.html" %}
{% block title %}User profile - pass{% endblock %}
{% block content %}
<h2>pass page</h2>
{% for field in form %}
{{ field.error }}
{% endfor %}
<form action="/userprofile/password_page/" method="POST">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="send" />
</form>
{%endblock%}
forms.py:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.forms import ModelForm
from drummersaransk.models import UserProfile
class ChangePasswordForm(forms.Form):
password_old = forms.CharField(max_length=30, widget=forms.PasswordInput())
password1 = forms.CharField(widget=forms.PasswordInput())
password2 = forms.CharField(widget=forms.PasswordInput())
def __init__(self, post, request, *args, **kwargs):
self.post = post
self.request = request
super(ChangePasswordForm, self).__init__(post, request, *args, **kwargs)
def clean_password_old(self):
cleaned_data = self.cleaned_data
password_old = cleaned_data.get("password_old")
if not self.request.user.check_password(password_old):
raise forms.ValidationError("old Password is not correct")
else:
return password_old
def clean(self):
cleaned_data = self.cleaned_data
password1 = cleaned_data.get("password1")
password2 = cleaned_data.get("password2")
if password1 != password2:
raise forms.ValidationError("Passwords must be same")
else:
return cleaned_data
答案 0 :(得分:1)
如果不是POST,您不应该将位置参数中的任何内容传递给表单。
form = ChangePasswordForm(request=request)
修改强>
正如我所说,你在ChangePasswordForm的定义中做了一些奇怪的事情。您接受了post
和request
个参数 - 即使您根本没有真正使用post
- 而且,更糟糕的是,您已经过了将它们放到超类的__init__
方法上,即使它没有预料到它们。
这样做的方法是仅接受request
,但要在kwargs中这样做。这样,您就不会更改功能签名,您可以选择是否将其传递给超类。
class ChangePasswordForm(forms.Form):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(ChangePasswordForm, self).__init__(*args, **kwargs)