views:

480

answers:

1

What's the best way to implement the following:

### models.py
>>> from django.db import models
>>> from django.contrib.auth.models import User
# Create the client class.
>>> class Client(models.Model):
...     user = models.OntToOneField(User)
...     zip = ***???***()

### forms.py
>>> from django.forms import ModelForm
# Create the form class.
>>> class ArticleForm(ModelForm):
...     class Meta:
...         model = Client

I'm trying to get the end result to use the US Zip Codes Field form widget/validator using only modifications the models.py file... aka I don't want to do the following:

### forms.py
>>> from django.forms import ModelForm
>>> from django.contrib.localflavor.us.forms import USZipCodeField
# Create the form class.
>>> class ArticleForm(ModelForm):
...     class Meta:
...         model = Client
...     zip = USZipCodeField()

NOTE: It might be that the BEST way to accomplish it is in the forms.py file as shown above... If this is the case, I guess I'm missing the argument/benefit of having it there instead of as a custom model field (e.g., DRY?, loose coupling?) Any help on helping better understand the benefits of forms.py over models.py in this scenario would be greatly appreciated.

Thanks in advance! -Tom

+2  A: 

A zip code is just a string of numbers/letters, so there's no need to define a custom field for storing it in the database. There's no model-level validation in Django at the moment (although there's a Google Summer of Code project to add it), so a custom model field wouldn't add anything. The validation comes at the form level, which is why there's a custom form field.

Daniel Roseman