form表单验证
1 class BallForm(forms.ModelForm): 2 class Meta: 3 model = Ball 4 fields = ["color", "description"] 5 6 def clean_description(self): 7 description = self.cleaned_data['description'] 8 if description == "123": 9 raise forms.ValidationError("hello boy") 10 return description
1 class Ball(models.Model): 2 color = models.OneToOneField("Colors") 3 description = models.CharField(u'描述', max_length=10) 4 5 def __unicode__(self): 6 return self.description
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>hello</title> 6 </head> 7 <body> 8 <p>hello</p> 9 <div class="panel panel-default"> 10 <form method="post"> 11 {% csrf_token %} 12 13 <p>{{ form.as_p }}</p> 14 <input class="btn btn-primary submit" type="submit" value="保存" /> 15 16 17 </form> 18 </div> 19 </body> 20 </html>