Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model - set default charfield in lowercase

How to set default charfield in lowercase? 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 the __init__ but it doesn't work. I want to make the username in lowercase every time new record saved. Thanks.

like image 812
Krisnadi Avatar asked Mar 31 '16 10:03

Krisnadi


2 Answers

While overwriting save() method is a valid solution. I found it useful to deal with this on a Field level as opposed to the Model level by overwriting get_prep_value() method.

This way if you ever want to reuse this field in a different model, you can adopt the same consistent strategy. Also the logic is separated from the save method, which you may also want to 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) 
like image 127
Danil Avatar answered Sep 20 '22 13:09

Danil


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

def save(self, *args, **kwargs):     self.username = self.username.lower()     return super(User, self).save(*args, **kwargs) 
like image 45
Avinash Raj Avatar answered Sep 22 '22 13:09

Avinash Raj