Django表单:验证消息未显示

时间:2012-12-18 17:00:43

标签: django django-forms

在以下示例中,任何人都可以发现我做错了什么。输入错误的详细信息(例如无效的电子邮件地址)时,验证消息不会出现在我的模板中。模板正在加载,没有错误。

我除了要在页面上打印的验证消息外,但由于某种原因,它突然停止工作。从下面的代码示例中可以看出,我将上下文中的表单传递回模板。这曾经工作,今天就停止了。

view.py

if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            # If form has passed all validation checks then continue to save member.
            user = User.objects.create_user(
                                            username=form.cleaned_data['username'],
                                            email=form.cleaned_data['email'], 
                                            password=form.cleaned_data['password']
                                            )
            user.save()
            #member = User.get_profile()
            #member.name = form.cleaned_data['name']
            #member.save()
            member = Member(
                            user=user,
                            name=form.cleaned_data['name']
                            )
            member.save()

            # Save is done redirect member to logged in page.
            return HttpResponseRedirect('/profile')
        else:
            # If form is NOT valid then show the registration page again.
            form = RegistrationForm() 
            context = {'form':form}
            return render_to_response('pageRegistration.html', context,context_instance=RequestContext(request))

form.py

class RegistrationForm(ModelForm):
    username = forms.CharField(label=(u'User Name'))
    email = forms.EmailField(label=(u'Email'))
    password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
    passwordConfirm = forms.CharField(label=(u'Confirm Password'), widget=forms.PasswordInput(render_value=False))

    class Meta:
        model = Member
        # Don't show user drop down.
        exclude = ('user',)


    def clean_username(self):
        username = self.cleaned_data['username']
        try:
                User.objects.get(username=username)
        except User.DoesNotExist:
                return username
        raise forms.ValidationError("Username already taken.")


    def clean(self):
        try:   
            cleaned_data = super(RegistrationForm, self).clean() 
            password = cleaned_data.get("password")
            passwordConfirm = cleaned_data.get('passwordConfirm')

            if password != passwordConfirm:
                raise forms.ValidationError("Password does not match, try again.")
            return cleaned_data
        except:
            raise forms.ValidationError("Error")

pageRegistration.html

<form action="" method="POST">
            {% csrf_token %}

            {% if forms.errors %}
            <p>
                correct some stuff
            </p>
            {% endif %}

            {{form}}
            <br>
            <input type="submit" value="submit">
        </form>  

3 个答案:

答案 0 :(得分:4)

因为,表单在else子句中没有验证,你的表单变量被覆盖了一个新的表单,它丢失了所有的错误

if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            # If form has passed all validation checks then continue to save member.
            user = User.objects.create_user(
                                            username=form.cleaned_data['username'],
                                            email=form.cleaned_data['email'], 
                                            password=form.cleaned_data['password']
                                            )
            user.save()
            #member = User.get_profile()
            #member.name = form.cleaned_data['name']
            #member.save()
            member = Member(
                            user=user,
                            name=form.cleaned_data['name']
                            )
            member.save()

            # Save is done redirect member to logged in page.
            return HttpResponseRedirect('/profile')
        return render_to_response('pageRegistration.html', context,context_instance=RequestContext(request))

答案 1 :(得分:1)

更新了CBV世界。

这就是造成我等效错误的原因:

class CreateView(generic.CreateView): # or generic.UpdateView

    def get_context_data(self, **kwargs):
        context_data = super(CreateView, self).get_context_data(**kwargs)
        # context_data['form'] = self.form_class # << this was the problematic override

答案 2 :(得分:0)

也许页面每次重新加载时都返回一个新表单。检查是否  views.py中的上下文变量包含'form':form