3

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

我排除了要在页面上打印的验证消息,但是由于某种原因,这突然停止工作。正如您从下面的代码示例中看到的那样,我将上下文中的表单传递回模板。这曾经有效,今天刚刚停止。

视图.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))

表格.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>  
4

3 回答 3

5

因为,表单在 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))
于 2012-12-18T17:04:38.160 回答
2

为 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
于 2014-05-13T05:24:11.137 回答
0

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

于 2018-10-21T10:48:24.413 回答