Django Forms cleaning_data缺少某些字段

时间:2014-06-20 06:35:13

标签: python django forms

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

forms.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

views.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'是必填字段。该值与其他字段一起明确显示在后期数据中。

无论我尝试过什么,clean_data dict中都不包含'password1'和'password2'。我已经尝试过为这两个字段使用各种其他名称,只是为了确保'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>

1 个答案:

答案 0 :(得分:1)

这是我在项目中如何做到这一点的一个例子:

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