如何在Django 1.5中创建“使用密码确认”表单?我将创建一个禁用用户帐户的功能,但如果用户无法提供正确的密码,则不应禁用该帐户。我尝试使用FormView和form_class=AuthenticationForm
,但它显示了用户名和密码,我只想要密码,因为用户已经登录。
答案 0 :(得分:1)
写一个密码验证表:
forms.py
from django import forms
from django.contrib.auth.models import check_password
class ValidatePasswordForm(forms.Form):
password = forms.CharField(label="Your Password",
widget=forms.PasswordInput)
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(ValidatePasswordForm, self).__init__(*args, **kwargs)
def clean_password(self):
password = self.cleaned_data['password']
valid = check_password(password, self.user.password)
if not valid:
raise forms.ValidationError('Invalid password')
return password
views.py
from django.shortcuts import render_to_response
from django.template import RequestContext
from myapp.forms import ValidatePasswordForm
@login_required
def validate_password(request):
form = ValidatePasswordForm(request.POST or None, user=request.user)
if request.method == 'POST':
if form.is_valid():
# do something upon validation
# disable account
pass
request_dict = {'form': form}
return render_to_response('my_template.html',
request_dict, context_instance=RequestContext(request))