当发生ValidationError时,Django形成clean()方法不会引发错误

时间:2017-12-05 18:10:20

标签: django forms validation

我正在尝试通过覆盖clean()方法为我的表单创建自定义验证器,并且由于某种原因,验证错误未正确引发。这是我的代码:

forms.py

from django import forms
from django.contrib.auth import get_user_model

class EmailForm(forms.Form):
    email_field = forms.EmailField(label='E-mail address', max_length=128)

    def clean(self):
         cleaned_data = super(EmailForm, self).clean()
         email = cleaned_data.get('email')

         try:
            u = get_user_model().objects.get(email=email)
            raise forms.ValidationError("E-mail already in database.")
            print('validation error raised')
        except:
            pass

views.py

from django.shortcuts import render
from django.contrib import messages

from .forms import EmailForm

def email_form(request):
    if request.method == 'POST':
        form = EmailForm(request.POST)

        # If the form is valid...
        if form.is_valid():
            messages.add_message(request, messages.SUCCESS, "Kaboom! Your referral e-mail was sent. Hang tight - we'll be sure to let you know when your friend makes a purchase.")
        else:
            messages.add_message(request, messages.ERROR, 'Error!')
   else:
       form = EmailForm()

   return render(request, 'template.html', {'form': form})

template.html

<form action="{% url 'form-process' %}" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit" />
</form>

当我提交此表单时,输入应该引发验证错误(即,已经与我的数据库中的用户关联的电子邮件地址),我获得了成功&#39;消息而不是错误。关于它的最奇怪的部分是提出了验证错误&#39;在我的控制台中打印 - 但由于某种原因,表单进程和form.is_valid()传递为True。

任何人都可以告诉我为什么当输入重复的电子邮件时,form.is_valid不会在下面的代码中输出错误?

1 个答案:

答案 0 :(得分:1)

它不能引发异常,因为你捕获的是除外。

def clean(self):
     cleaned_data = super(EmailForm, self).clean()
     email = cleaned_data.get('email')

     users = get_user_model().objects.filter(email=email)
     if users.count():
         raise forms.ValidationError("E-mail already in database.")