我尝试了很多案例来解决这个错误" init ()至少需要2个参数(给定1个)"但一直无法解决它。
注意:我使用的是Django的默认身份验证用户模型,数据库是MySQL。
URLS.PY
url(r'^change-password$', ChangePasswordView.as_view()),
FORMS.PY
class PasswordChangForm(forms.Form):
new_password1 = forms.CharField(max_length=20,required=True)
new_password2 = forms.CharField(max_length=20,required=True)
def __init__(self, user, *args, **kwargs):
self.user = user
super(PasswordChangForm, self).__init__(*args, **kwargs)
def clean(self):
try:
print self.cleaned_data.get('new_password1')
print self.cleaned_data.get('new_password2')
password1 = self.cleaned_data.get('new_password1')
password2 = self.cleaned_data['new_password2']
if password1 and password2:
if password1 != password2:
raise forms.ValidationError('password_mismatch')
else:
try:
print "tryyy.."
print self.user
user = User.objects.get(username=self.user)
user.set_password(self.cleaned_data.get('new_password1'))
user.save()
return user
except User.DoesNotExist:
return forms.ValidationError('Oops Some thing went Wrong..')
except KeyError:
raise forms.ValidationError('The password field was blank.')
VIEWS.PY
class ChangePasswordView(UpdateView):
template_name = 'people/change_password.html'
form_class = PasswordChangForm
model = User
#When I use get_form, it prevents __init__ error. But in the forms.py "clean" method is never calling. This results no validation and not saving data in the DB
'''def get_form(self, form_class):
print "iam in getform..."
return form_class(self.request.user)'''
def get_object(self):
return User.objects.get(username=self.request.user)
'''def dispatch(self, request, *args, **kwargs):
return super(YourView, self).dispatch(request, *args, **kwargs)'''
def get_success_url(self):
print "get_success_url"
print self.request.user
return '/welcome'
def form_valid(self, form):
print "valid"
#instance = form.save(commit=False)
#instance.user = self.request.user
return super(ChangePasswordView, self).form_valid(form)
def form_invalid(self,form):
print "form_invalid"
print form.errors
return super(ChangePasswordView, self).form_invalid(form)
有谁可以帮我理解我做错了什么?
答案 0 :(得分:1)
我认为您的问题出在此处:(在get_form
方法中)
def get_form(self, form_class):
return form_class(self.request.user)
应该是
def get_form(self, form_class):
return form_class(user=self.request.user)
同样覆盖post方法(来自评论部分):
class ChangePasswordView(UpdateView):
....
def post(self, request, *args, **kwargs):
form= self.form_class(request.POST)
if form.is_valid():
#do something
else:
#raise error
return super(ChangePasswordView, self).post(request, *args, **kwargs)