CharField with fixed length, how?
Solution 1:
Kind of along the same lines as above, but for what it's worth you could also go ahead with MinLengthValidator which django supplies. Worked for me. The code would look something like this:
from django.core.validators import MinLengthValidator
...
class Volume(models.Model):
volumenumber = models.CharField('Volume Number', max_length=4, validators=[MinLengthValidator(4)])
...
Solution 2:
You don't even have to write a custom one. Just use the RegexValidator
which Django supplies.
from django.core.validators import RegexValidator
class MyModel(models.Model):
myfield = models.CharField(validators=[RegexValidator(regex='^.{4}$', message='Length has to be 4', code='nomatch')])
From the Django Docs: class RegexValidator(\[regex=None, message=None, code=None\])
regex
: A valid regular expression to match. For more on regex in Python check this excellent HowTo:
http://docs.python.org/howto/regex.html
message
: The message returned to the user in case of failure.
code
: error code returned by ValidationError. Not important for your usage case, you can leave it out.
Watch out, the regex suggested by me will allow any characters including whitespace. To allow only alphanumeric characters, substitute the '.' with '\w' in the regex argument. For other requirements, ReadTheDocs ;).