简体   繁体   中英

Python Django populate field in a model using another field in the same model

I have a User model. What I want is when a user registers, the slack field is filled with data from a function which uses users email as a parameter. (Basically slack should be something like "DS8ds9D" which is generated from email.

I have the function that does that "get_slack(email)" which I know works if run outside model with an email. The error I get is when I try to "makemigrations" saying the email from "get_slack(email)" is null.

class User(AbstractBaseUser, PermissionsMixin):

    email = models.EmailField(unique=True)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    date_joined = models.DateTimeField(default=timezone.now)

    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)
    slack = models.CharField(max_length=255, default=get_slack(email))

I think it is clear what I am trying to establish however my method using "default" may not be appropriate. Any suggestions? Thanks.

If you want to create the slack field when a user registers, you should override the default save method.

class User(AbstractBaseUser, PermissionsMixin):
    # ...

    def save(self, *args, **kwargs):
        self.slack = self.image    # do whatever processing you want
        super(User, self).save(*args, **kwargs)

Reference and Documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM