让我们完成上一节中的任务:
1.验证price>0:需要在Form中验证;
2. 验证title唯一:在Model中验证;
3. 验证image_url的扩展名:在Form中验证,还可以顺便在Model中将其改为URLField类型。
之前生成的scaffold中已经实现了属性不能为空的验证:
但是对于url格式,rul的后缀,title的唯一性都没有验证。首先在model中增加URL格式和title唯一性的校验:
from django.db import models class Product(models.Model): title = models.CharField(max_length=100,unique=True) description = models.TextField() image_url = models.URLField(max_length=200) price = models.DecimalField(max_digits=8,decimal_places=2)剩下的图片格式后缀、价格>0的校验需要在form中实现:
depot/depotapp/forms.py
#/usr/bin/python #coding: utf8 from django import forms from models import * import itertools def anyTrue(predicate, sequence): return True in itertools.imap(predicate, sequence) def endsWith(s, *endings): return anyTrue(s.endswith, endings) class ProductForm(forms.ModelForm): class Meta: model = Product def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) def clean_price(self): price = self.cleaned_data['price'] if price<=0: raise forms.ValidationError("价格必须大于零") return price def clean_image_url(self): url = self.cleaned_data['image_url'] if not endsWith(url, '.jpg', '.png', '.gif'): raise forms.ValidationError('图片格式必须为jpg、png或gif') return url ProductForm继承自ModelForm,可以根据model属性自动生成表单。在生成的ProductForm上增加了clean_price和clean_image_url验证。结果如下:
那么,表单是如何展现的呢?看一下template:
depot/depotapp/templates/depotapp/create_product.html
{% extends "base.html" %} {% block title %} 创建产品 {% endblock %} {% block content %} <table> <form action="" method="POST"> {% csrf_token %} {{form}} <tr> <td colspan="2" align="right"><input type="submit" value="Create"/></td> </tr> </form> </table> {% endblock %}{% csrf_token %}的作用是增加token表单项,避免重复提交。