Aaron - 9 months ago 46
Python Question

# Set the length of a model field to a length of 5

I am using Django and I want to set one of my fields in my database to only allow numbers that are 5 integers long. I found max_length, is there a length?

Here is my code

zip_code = models.IntegerField(max_length=5)


Is there a way to

zip_code = models.IntegerField(length=5)


Force user to enter 5 numbers.

It doesn't make sense to use max_length with an IntegerField.
If you are storing zip codes, it would be better to use a CharField, so that you can store zip codes that begin with zero.
CharFields do not have a min_length option, but Django does have a MinLengthValidator. However, it would be simpler to use a RegexValidator, then you can use a regex to allow only digits, and check that the input is exactly 5 digits long.
zip_code = models.CharField(max_length=5, validators=[RegexValidator(r'^[0-9]{5}\$')])

Another option would be to use the USZipCodeField from django-localflavor.