Skip to main content
 首页 » 编程设计

python之Django Forms cleaned_data 缺少某些字段

2025年05月04日28qq号

我使用 Django 客户用户模型为用户注册创建的表单有一个奇怪的问题。我正在运行 Django 1.6.5。

表单.py

class SignupForm(forms.ModelForm): 
    password1 = forms.CharField(widget=forms.PasswordInput, 
                                label=_('Password'), 
                                max_length=50) 
    password2 = forms.CharField(widget=forms.PasswordInput, 
                                label=_('Repeat password'), 
                                max_length=50) 
 
    class Meta: 
        model = RegisteredUser 
        fields = ("firstname", "lastname", "email", "password1", "password2",) 
 
    def clean_email(self): 
        existing = RegisteredUser.objects.filter(email__iexact=self.cleaned_data['email']) 
        if existing.exists(): 
            raise forms.ValidationError(_('A user with that email already exists.')) 
        return self.cleaned_data['email'] 
 
    def clean(self): 
        cleaned_data = super(SignupForm, self).clean() 
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: 
            if self.cleaned_data['password1'] != self.cleaned_data['password2']: 
                raise forms.ValidationError(_('The two passwords did not match.')) 
        return cleaned_data 

View .py

class SignUpView(FormView): 
    template_name = 'core/signup.html' 
    form_class = SignupForm 
    success_url = None 
 
    def post(self, request, *args, **kwargs): 
        form = self.get_form(self.get_form_class()) 
        if form.is_valid(): 
            return self.form_valid(request, form) 
        else: 
            return self.form_invalid(form) 
 
    def form_valid(self, request, form): 
        new_user = self.register(request, **form.cleaned_data) 
        success_url = self.get_success_url(request, new_user) 
 
        try: 
            to, args, kwargs = success_url 
            return redirect(to, *args, **kwargs) 
        except ValueError: 
            return redirect(success_url) 
 
 
 
    def register(self, request, **cleaned_data): 
        RegisteredUser.objects.create_user(email=cleaned_data['username'], 
                                           firstname=cleaned_data['firstname'], 
                                           lastname=cleaned_data['lastname'], 
                                           password=cleaned_data['password2']) 

表单返回无效,表示“password1”和“password2”是必填字段。该值与其他字段一起清楚地显示在发布数据中。

无论我尝试过什么,'password1' 和 'password2' 都不包含在 cleaned_data 字典中。我已经尝试为这两个字段使用各种其他名称,只是为了确保“password2”不会与其他任何内容发生冲突。

我可能忽略了一些非常简单的事情:-)

谢谢!

迈克

编辑 1 - 正在使用的模板(抱歉 div-hell!):

<section class="container"> 
        <div class="row"> 
            <div class="col-md-6 col-sm-6"> 
                <h2>Create an <strong>Account</strong></h2> 
                <form class="white-row" method="post" action="#"> 
                    {% csrf_token %} 
                    <div class="row"> 
                        <div class="form-group"> 
                            <div class="col-md-12 col-sm-12"> 
                                <label>Firstname</label> 
                                <input type="text" class="form-control" name="firstname"> 
                            </div> 
                        </div> 
                    </div> 
                    <div class="row"> 
                        <div class="form-group"> 
                            <div class="col-md-12 col-sm-12"> 
                                <label>Lastname</label> 
                                <input type="text" class="form-control" name="lastname"> 
                            </div> 
                        </div> 
                    </div> 
                    <div class="row"> 
                        <div class="form-group"> 
                            <div class="col-md-12 col-sm-12"> 
                                <label>Email</label> 
                                <input type="email" class="form-control" name="email"> 
                            </div> 
                        </div> 
                    </div> 
                    <div class="row"> 
                        <div class="form-group"> 
                            <div class="col-md-6 col-sm-6"> 
                                <label>Password</label> 
                                <input type="password" class="form-control" name="passsword1"> 
                            </div> 
                            <div class="col-md-6 col-sm-6"> 
                                <label>Repeat password</label> 
                                <input type="password" class="form-control" name="passsword2"> 
                            </div> 
                        </div> 
                    </div> 
                    <div class="row"> 
                        <div class="col-md-12 col-sm-12"> 
                            <input type="submit" value="Sign up" class="btn btn-primary pull-right push-bottom" data-loading-text="Loading..."> 
                        </div> 
                    </div> 
                </form> 
            </div> 

请您参考如下方法:

这是我如何在我的项目中执行此操作的示例:

表单.py:

class NewUserForm(forms.Form): 
    username = ... 
    password1 = forms.CharField(widget=forms.PasswordInput, required=True) 
    password2 = forms.CharField(widget=forms.PasswordInput, required=True) 
 
    def clean_password2(self): 
        password1 = self.cleaned_data.get("password1", "") 
        password2 = self.cleaned_data.get("password2", "") 
        if password1 and password2:  # If both passwords has value 
            if password1 != password2: 
                raise forms.ValidationError(_(u"Passwords didn't match.")) 
        else: 
            raise forms.ValidationError(_(u"Passwords can't be blank.")) 
        return password2 

views.py:

@login_required 
def add_user(request): 
    ''' Adds new user ''' 
 
    if request.method == 'POST': 
        form = NewUserForm(request.POST) 
        if form.is_valid(): 
            user = form.save() 
            # TODO: Save in temporary table 
            return HttpResponse('SUBMIT') 
    else: 
        form = NewUserForm() 
 
    return render_to_response('add_user.html', {'form': form}, context_instance=RequestContext(request)) 

模板(表单示例):

<form action="." method="post" id="add_user_form"> 
{% csrf_token %} 
    {{ form.username }} 
    {{ form.password1 }} 
    {{ form.password2 }} 
    {{ form.usertype }} 
 
    <input type="submit" value="{% trans 'Save' %}" class="default"/> 
 
</form> 

{% csrf_token %} :你需要把它放在你使用的每一个表单中

action="." :这使得发布到实际页面

{{ form.VARIABLE_NAME}} 您需要像这样设置表单的输入,在 View 中创建表单,发送到模板,并将其用作 Django 变量使用{{ }}。要为您的其中一个字段设置输入,例如 password1,就像我在上面写的那样 {{ form.password1}},您也可以使用 {{ form.errors}} 检查所有表单错误,或 {{form.VARIABLE_NAME.errors}} 检查模板中的确切字段错误