I have a model employee, and while creating an instance I want to automatically set their email to "<first_name>.<last_name>@company.com". So, I wrote a manager to do the pre-processing:
class EmployeeManager(models.Manager):
def create(self, **kwargs):
name = kwargs['first_name']
surname = kwargs['last_name']
kwargs['email'] = f'{name}.{surname}@company.com'
return super(EmployeeManager, self).create(**kwargs)
class Employee(models.Model):
first_name = models.CharField(null=False, blank=False, default="employee", max_length=255)
last_name = models.CharField(null=False, blank=False, default="employee", max_length=255)
position = models.CharField(null=False, blank=False, default="SDE", max_length=255)
email = models.EmailField(null=False, default="[email protected]", unique=True)
phone = models.CharField(null=False, blank=False, default='1234567890', max_length=10, validators=[MinLengthValidator])
slack_id = models.UUIDField(null=False, blank=True, default = uuid.uuid4)
active = models.BooleanField(default=True)
objects = EmployeeManager()
def __str__(self) -> str:
return self.email
However, when I am creating an instance of this model using the admin interphase, the email is set to the default value ([email protected]) and not what I am feeding it in the new create() method. Why is this happening?
I suggest to use Save method on your model