Django: CharField with a fixed length, how?

I liked having a fixed-length CharField in my model. In other words, I want only the specified length to be valid.

I tried to do something like

volumenumber = models.CharField('Volume Number', max_length=4, min_length=4) 

but this gives me an error (it seems that I can use both max_length and min_length at the same time).

Is there another quick way?

thank

EDIT:

Following some people's suggestions, I will be more specific:

My model is this:

 class Volume(models.Model): vid = models.AutoField(primary_key=True) jid = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal") volumenumber = models.CharField('Volume Number') date_publication = models.CharField('Date of Publication', max_length=6, blank=True) class Meta: db_table = u'volume' verbose_name = "Volume" ordering = ['jid', 'volumenumber'] unique_together = ('jid', 'volumenumber') def __unicode__(self): return (str(self.jid) + ' - ' + str(self.volumenumber)) 

I want volumenumber to be exactly 4 characters.

those. if someone inserts a β€œ4b” django, it throws an error because it expects a string of 4 characters.

So, I tried using

 volumenumber = models.CharField('Volume Number', max_length=4, min_length=4) 

but he gives me this error:

 Validating models... Unhandled exception in thread started by <function inner_run at 0x70feb0> Traceback (most recent call last): File "/Library/Python/2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/Library/Python/2.5/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Python/2.5/site-packages/django/core/management/validation.py", line 28, in get_validation_errors for (app_name, error) in get_app_errors().items(): File "/Library/Python/2.5/site-packages/django/db/models/loading.py", line 131, in get_app_errors self._populate() File "/Library/Python/2.5/site-packages/django/db/models/loading.py", line 58, in _populate self.load_app(app_name, True) File "/Library/Python/2.5/site-packages/django/db/models/loading.py", line 74, in load_app models = import_module('.models', app_name) File "/Library/Python/2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Users/Giovanni/src/djangoTestSite/../djangoTestSite/journaldb/models.py", line 120, in <module> class Volume(models.Model): File "/Users/Giovanni/src/djangoTestSite/../djangoTestSite/journaldb/models.py", line 123, in Volume volumenumber = models.CharField('Volume Number', max_length=4, min_length=4) TypeError: __init__() got an unexpected keyword argument 'min_length' 

This is not explicitly displayed if I use only "max_length" OR "min_length".

I read the documentation on the django website and it seems like I'm right (I can't use both together), so I ask if there is another way to solve the problem.

Thanks again

+53
django django-models
Mar 18
source share
4 answers

CharField database field instances only have the max_length parameter, as specified in docs . This is probably due to the fact that in SQL there is only the equivalent of character length restriction.

Field Field CharField objects , on the other hand, have the min_length parameter. Thus, you will have to write a custom ModelForm for this particular model and override the default admin model form using custom.

Something like that:

 # admin.py from django import forms ... class VolumeForm(forms.ModelForm): volumenumber = forms.CharField(max_length=4, min_length=4) class Meta: model = Volume class VolumeAdmin(admin.ModelAdmin): form = VolumeForm ... admin.site.register(Volume, VolumeAdmin) 
+39
Mar 18 '10 at 20:28
source share

You don’t even have to write custom. Just use the RegexValidator that comes with Django.

 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 Django Docs: class RegexValidator(\[regex=None, message=None, code=None\])

regex : a valid regex to match. For more information on regex in Python, check out this great HowTo: http://docs.python.org/howto/regex.html

message : the message is returned to the user in case of failure.

code : error code returned by ValidationError. It doesn’t matter for your use case, you can leave it.

Beware, the regex proposed by me will allow any characters, including spaces. To allow only alphanumeric characters, replace '.' with '\ w' in the regex argument. For other requirements, ReadTheDocs;).

+77
Aug 14 2018-12-12T00:
source share

The view is on the same lines as above, but for what it stands for, you can also go with the MinLengthValidator, which comes django. Worked for me. The code will 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)]) ... 
+50
Oct 18 '15 at 16:38
source share

You can write your own validator as suggested by @Ben. At the time of writing this answer, instructions for this can be found at https://docs.djangoproject.com/en/dev/ref/validators/.

The code will be something like this (copy by link):

 from django.core.exceptions import ValidationError def validate_length(value,length=6): if len(str(value))!=length: raise ValidationError(u'%s is not the correct length' % value) from django.db import models class MyModel(models.Model): constraint_length_charField = models.CharField(validators=[validate_length]) 
+16
May 19 '12 at 5:09
source share



All Articles