2016-04-23 78 views
1

我有一個由電子郵件和名稱字段組成的Django表單。我想驗證名稱的字符數超過8個。我已經使用了下面的代碼。但它不起作用。以Django形式進行字段驗證

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}) 
+1

請修復您的縮進。 –

+0

做到了。對不起.. – user2375245

+0

你確定窗體中的縮進與你的實際文件中的縮進相同嗎? –

回答

0

您需要爲您的驗證方法,使用正確的名稱。 Django表單將調用格式爲clean_<fieldname>的方法。

此外,您似乎對您正在驗證的字段感到困惑;您的電子郵件驗證方法應該被稱爲clean_email,並且應該通過form.cleaned_data['email']訪問電子郵件值,名稱應該被稱爲clean_name並訪問form.cleaned_data['name']

+0

非常感謝你..它已解決。 – user2375245

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 
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