Django model - default charfield lowercase setting

How to set charfield to lowercase by default? This is my model:

class User(models.Model): username = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=64) name = models.CharField(max_length=200) phone = models.CharField(max_length=20) email = models.CharField(max_length=200) def __init__(self, *args, **kwargs): self.username = self.username.lower() 

I tried __init__ , but it does not work. I want to make the username lowercase every time a new record is saved. Thanks.

+12
django django-models
source share
3 answers

Just do it in the save method. those. override the save method of the Model class.

 def save(self, *args, **kwargs): self.username = self.username.lower() return super(User, self).save(*args, **kwargs) 
+17
source share

When overwriting, the save() method is a valid solution. I found it helpful to deal with this at the Field level and not at the Model level by rewriting get_prep_value() .

Thus, if you ever want to reuse this field in a different model, you can use the same consistent strategy. The logic is also separate from the save method, which you can also overwrite for different purposes.

For this case, you would do this:

 class NameField(models.CharField): def __init__(self, *args, **kwargs): super(NameField, self).__init__(*args, **kwargs) def get_prep_value(self, value): return str(value).lower() class User(models.Model): username = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=64) name = NameField(max_length=200) phone = models.CharField(max_length=20) email = models.CharField(max_length=200) 
+12
source share
 def save(self, force_insert=False, force_update=False): self.YourFildName = self.YourFildName.upper() super(YourFomrName, self).save(force_insert, force_update) 
-one
source share

All Articles