[Answered ]-Custom Model Field for formatting char field data

1👍

As @Rod Xavier said, you can use a RegexValidator for that. But, to be more precise, with a regex, you can allow both XXXX-XXXXX and XXXXXXXXX and then when you are saving format it with the dash if it is missing. If the entry is not 9 characters long or it is 10 characters without a dash, the RegexValidator will reject the field and the object won’t be saved.

from django.core.validators import RegexValidator
from django.db import models 

class MyModel(models.Model):
    # Notice the ? in the regex.
    factory_id = models.CharField(max_length=10, 
                                  validators=[
                                      RegexValidator(r'^[0-9]{4}-?[0-9]{5}$')
                                  ])

    def save(self, *args, **kwargs):
        """ This step is just formatting: add the dash if missing """
        if '-' not in self.factory_id:
            self.factory_id = '{0}-{1}'.format(
                 self.factory_id[:4], self.factory_id[4:])

        # Continue the model saving
        super(MyModel, self).save(*args, **kwargs)

1👍

You can use Django’s built-in Regex validator. from django.core.validators import RegexValidator

Example

factory_id = models.CharField(max_length=10, 
                              validators=[
                                  RegexValidator(r'^[0-9]{4}-{0,1}[0-9]{5}$')
                              ])

Since you want to save the field in XXXX-XXXXX format. You should then alter the model’s save() method.

def save(self, *args, **kwargs):
    if '-' not in self.factory_id:
        self.factory_id = '{0}-{1}'.format(self.factory_id[:4], self.factory_id[4:])
    super(MyModel, self).save(*args, **kwargs)

Leave a comment