Django CMS has its own User model but you might need to add attributes and other properties to it (like an avatar, right ?). The easiest way to do that is to extend that model with another model (we’ll call it UserProfile) and link them together using a one-to-one relationship.
Creating the UserProfile model
Nothing special here, I’m sure you know how it works.
1 2 3 4 5 6 7 |
class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='user_profile', primary_key=True) avatar = models.ImageField(upload_to='uploads/avatars/%Y/%m/%d/') website = models.URLField(default='', blank=True) def __str__(self): return 'Profile of user: {}'.format(self.user.username) |
Creating a UserProfile when creating a User
Each User needs to have a UserProfile object. To make sure that applies to every user, we’ll create a UserProfile each time a User is created. To do that. we’ll use the post_save signal (signals doc).
Just under the UserProfile code, you can add that code
1 2 3 4 5 6 7 8 9 |
def create_profile(sender, **kwargs): """ Listen to post_save signal to create a UserProfile whenever a User is created """ user = kwargs["instance"] if kwargs["created"]: user_profile = UserProfile(user=user) user_profile.save() post_save.connect(create_profile, sender=User) |
And you’re pretty much good to go. You can access the user’s UserProfile using user.user_profile.