Reputation: 7091
New to Django here, found this function in the user profile model of code someone passed to me, but I can not for the life of me find it in the documentation, nor can I find it anywhere else in his code. But everything including user authentification seems to work, so not sure where this is create_new_user_and_profile
is coming from? Also, not sure if this is the best way to do users, can anyone give some tips?
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
class UserProfile(models.Model):
user = models.OneToOneField(User)
office_number = models.IntegerField(null=True)
def initialize_static_fields(self, office_number):
user = models.OneToOneField(User)
self.office_number = office_number
def create_new_user_and_profile(username, email, password, office_number):
u = User.objects.create_user(username, email, password)
u.get_profile().initialize_static_fields(office_number)
Upvotes: 0
Views: 101
Reputation: 22459
The user model has a create_user method, however it does not create a profile by default, you could use a signal to create a profile each time a new User is created, e.g.
def create_profile(sender, instance, created, **kwargs):
profile = None
if created:
profile, created = Profile.objects.get_or_create(user=instance)
post_save.connect(create_profile, sender=User)
The method added to your model is a custom method which creates a user and triggers create_user_profile, which is then complemented with extra info. IMO, this method should not be part of the CalscopeUserProfile and likely belongs in a (form)view (private) or service function.
Upvotes: 1