Reputation: 422
I have to two models: CustomUser and Artist.
What I am trying to achieve is that, when i create a user it should automatically create an artist.
I don't want to add a OneToOne field in artist model. I just want to fill these fields: name, artist_category, artist_image and bio, using post_save when CustomUser is created.
class CustomUser(AbstractBaseUser, PermissionsMixin):
artist_choice = [
(0, 'celebrities'),
(1, 'singer'),
(2, 'comedian'),
(3, 'dancer'),
(4, 'model'),
(5, 'Photographer')
]
artist_category = models.IntegerField(choices=artist_choice, null=True)
mobile_number = PhoneNumberField(null=True)
city = models.CharField(blank=True, max_length=50)
bio = models.TextField(blank=True)
email = models.EmailField(max_length=100, unique=True)
name = models.CharField(max_length=100)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_superuser = models.BooleanField(default=False)
last_login=models.DateTimeField(null=True, blank=True)
date_joined = models.DateTimeField(auto_now_add=True)
country = CountryField()
USERNAME_FIELD = 'email'
EMAIL_FIELD='email'
REQUIRED_FIELDS=[]
objects=UserManager()
def get_absolute_url(self):
return "/users/%i/" % (self.pk)
class Artist(models.Model):
CHOICES = (
(0, 'celebrities'),
(1, 'singer'),
(2, 'comedian'),
(3, 'dancer'),
(4, 'model'),
(5, 'Photographer')
)
name = models.CharField(max_length=100)
artist_category = models.IntegerField(choices = CHOICES, null=True)
artist_image = models.ImageField(upload_to= 'media',null=True)
bio = models.TextField(max_length = 500)
def __str__(self):
return self.name
Upvotes: 0
Views: 59
Reputation: 2357
EDITED
Using Django Signals Post_save will work so just add the values to artist table via a dict.
Instance is the data that is saved to the CustomUser
model so you can
get specific elements of data via accessing instance
and create a dict with required data that can be passed to Artist
model.
Try This:
def create_artist(sender, instance, created, **kwargs):
if created:
data = {
'name' : instance.name,
'artist_category' : instance.artist_category,
'bio' : instance.bio
}
Artist.objects.create(**data)
post_save.connect(create_artist, sender=CustomUser)
Upvotes: 2