Using localflavor fields for Django model validation

new to django 1.2 comes model validation, which allows you to define a clean() method directly on your model to perform custom validation on each save() of that model.

to keep things nice and dry, it's often desirable to reuse the fields from the django.contrib.localfavor app, which includes phone number, postal code, social security number fields and more for dozens of countries. here's how we can reuse these built-in fields:

def clean(self):
    from import capostalcodefield
    self.zip_code = capostalcodefield().clean(self.zip_code)

in this example, we're validating the model's zip_code field against the built-in capostalcodefield. if validation fails, it will simply raise a validationerror like normal; otherwise, the value will be set to the cleaned version (usually the same as the input).