将错误消息返回到Django中的自定义窗体

时间:2015-05-31 11:46:24

标签: python django forms django-models django-forms

我的自定义注册表单中的字段如下所示:

<div class="form-group">
          {{ form.email.errors }}
        label for="{{form.email.id_for_label}}">
        <b>Email</b>
        </label>
          {{ form.email }}
</div>

我的views.py看起来像这样:

def registration(request):
    registered = False
    if request.method == 'POST':
        form = RegForm(data=request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            phone = form.cleaned_data['phone']
            password = form.cleaned_data['password']
            password2 = form.cleaned_data['password2']
            user = User()
            user.email = email
            user.username = email
            user.is_active = False
            user.set_password(password)
            user.save()
            return render(request, 'appname/index.html', {'registered': True})
    else:
        form = RegForm()
        render(request, 'appname/index.html', {'form': form})

forms.py:

class RegForm(forms.Form):
    email = forms.EmailField(error_messages={'required': 'Please enter your Email ID'})
    password=forms.CharField(widget=forms.PasswordInput())
    password2=forms.CharField(widget=forms.PasswordInput())
    phone= forms.CharField(label="Mobile Number",max_length=10)

#clean email field
    def clean_email(self):
        email = self.cleaned_data["email"]
        try:
            User._default_manager.get(email=email)
        except User.DoesNotExist:
            return email
        raise forms.ValidationError('duplicate email')

如果电子邮件已在数据库中存在,请说明如何将错误消息返回到自定义表单并将其显示在{{form.email.errors}}

的位置

修改
我在forms.py中使用了ValidationError,如果存在电子邮件则返回raise forms.ValidationError('duplicate email')。如何在自定义表单中显示此错误?

3 个答案:

答案 0 :(得分:1)

视图的逻辑似乎存在问题。

评估表单form.is_valid()时,将会引发ValidationError并在表单中提供错误。

如果表单无效,它似乎没有返回任何内容,或者使表单中包含模板中可用的错误。

def registration(request):
    registered = False
    if request.method == 'POST':
        form = RegForm(data=request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            phone = form.cleaned_data['phone']
            password = form.cleaned_data['password']
            password2 = form.cleaned_data['password2']
            user = User()
            user.email = email
            user.username = email
            user.is_active = False
            user.set_password(password)
            user.save()
            return render(request, 'appname/index.html', {'registered': True})
    else:
        form = RegForm()
    return render(request, 'appname/index.html', {'form': form})

此外,该标签似乎正在开放<

    <div class="form-group">
      {{ form.email.errors }}
    <label for="{{ form.email.id_for_label }}">
    <b>Email</b>
    </label>
      {{ form.email }}
    </div>

作为旁注,我建议在用户成功创建后用GET请求重定向用户,以避免任何用户意外地重新加载并发送另一个有效负载。 e.g。

return redirect('/confirmation/')

答案 1 :(得分:0)

您可以为email中的RegForm字段编写自定义清理程序。类似的东西:

class RegForm(forms.Form):
    # Everything as before.
    ...

    #clean email field
    def clean_email(self):
        email = self.cleaned_data["email"]
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError('duplicate email')
        return email

记录在案here

答案 2 :(得分:0)

回答我自己的问题。我是一个新手,因此花了很多时间和精力来解决这个问题。 我在观点中忽略了这一点:

if form.is_valid():
    #do something, add user ot DB
    return render(request, 'mudramantri/index.html', {'registered': True})
else:
    return render(request, 'mudramantri/index.html', {'form': form})

因为,当表单无效时,我没有返回表单,视图为空,因此错误。