Django表单中的字段验证

时间:2016-04-23 14:49:56

标签: django python-2.7

我有一个由电子邮件和名称字段组成的Django表单。我想验证名称超过8个字符。我使用了以下代码。但它没有用。

class SignUpForm(forms.ModelForm):
    class Meta:
        model=SignUp
        fields=('email','name')
    def emailValidation(self):

        name=self.cleaned_data.get('name')
        if len(name) <=8:
            raise forms.ValidationError("name cannot be less than 8")

models.py

class SignUp(models.Model):
    name=models.CharField(max_length=200)
    email=models.EmailField()
    timestamp=models.DateTimeField(auto_now_add=True, auto_now=False)
    updated=models.DateTimeField(auto_now=True,auto_now_add=False)
    def __unicode__(self):
        return self.name

views.py

def home(request):
    form=SignUpForm(request.POST or None)                                           
    if form.is_valid():                                             

        instance=form.save(commit=False)
        instance.save()
        print instance.timestamp
    return render(request, 'home.html',{'form':form})

3 个答案:

答案 0 :(得分:1)

在SignUpForm中,在函数emailValidation中,您尚未返回“name”。另一个主要错误是您必须将函数命名为clean_(field_name)而不是emailValidation。 应该这样做我猜:

class SignUpForm(forms.ModelForm):
    class Meta:
        model=SignUp
        fields=('email','name')
    def clean_name(self):

        name=self.cleaned_data.get('name')
        if len(name) <=8:
            raise forms.ValidationError("name cannot be less than 8")
        return name

答案 1 :(得分:0)

您需要为验证方法使用正确的名称。 Django表单将调用格式为clean_<fieldname>的方法。

你似乎对你正在验证哪个领域感到困惑;您的电子邮件验证方法应该调用clean_email,并且应该通过form.cleaned_data['email']访问电子邮件值,并且应该将名称称为clean_name并访问form.cleaned_data['name']

答案 2 :(得分:0)

这样的事情可能会给你一些指导。

class RegistrationForm(forms.ModelForm):
    """
    Form for registering a new account.
    """
    firstname = forms.CharField(label="First Name")
    lastname = forms.CharField(label="Last Name")
    phone = forms.CharField(label="Phone")
    email = forms.EmailField(label="Email")
    password1 = forms.CharField(label="Password")
    password2 = forms.CharField(label="Password (again)")
    min_password_length = 8

class Meta:
    model = User
    fields = ['firstname', 'lastname', 'phone', 'email', 'password1', 'password2']

def clean_email(self):
    email = self.cleaned_data['email']
    if User.objects.filter(email=email).exists():
        raise forms.ValidationError(u'Email "%s" is already in use! Please log in or use another email!' % email)
    return email

def clean_password1(self):
    " Minimum length "
    password1 = self.cleaned_data.get('password1', '')
    if len(password1) < self.min_password_length:
        raise forms.ValidationError("Password must have at least %i characters" % self.min_password_length)
    else:
        return password1

def clean(self):
    """
    Verifies that the values entered into the password fields match

    NOTE: Errors here will appear in ``non_field_errors()`` because it applies to more than one field.
    """
    cleaned_data = super(RegistrationForm, 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("Passwords didn't match. Please try again.")
    return self.cleaned_data

def save(self, commit=True):
    user = super(RegistrationForm, self).save(commit=False)
    user.set_password(self.cleaned_data['password1'])
    if commit:
        user.save()
    return user