In my Django app, I have created a model with the id (primary key) as a CharField
of length 6. I am using a custom validator which allows the user to only enter integers only. Is there a way to add zeros before the input if it is less than the "six" character length specified in the field definition.
For example, the user enters value 1234 in the primary key field. Now I want that at save the pk field value should be saved as 001234.
I tried doing that at save
but two records are getting created, one with the input by the user and the other with the zero(s) added.
Is this at all possible to achieve what I am trying to do?
Edit
Here is what I am doing (seems quite low-tech to me though):
class Plant(models.Model):
plant_id = models.CharField(primary_key=True,..,)
plant_name = models.CharField(max_length=55, verbose_name="Plant/W.Area")
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
if len(self.plant_id) == 4:
ramp_up_obj_id = '00' + str(self.plant_id)
self.plant_id = str(ramp_up_obj_id)
super().save(*args, **kwargs)
The result on save is (as narrated above): For entered value of 1001, there two records created. One with 1001 and the other one as 001001.