Reputation: 225
I am following the link https://stackoverflow.com/a/965883/1657010 for extending the django user to a user profile.
#in models.py
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.OneToOneField(User)
emailId = models.CharField(max_length=200)
dateCreated = models.DateTimeField(blank=True, null=True)
#other fields here
def __str__(self):
return "%s's profile" % self.user
def create_user_profile(sender, instance, created, **kwargs):
if created:
profile, created = UserProfile.objects.get_or_create(user=instance)
post_save.connect(create_user_profile, sender=User)
#in settings.py
AUTH_PROFILE_MODULE = 'myapp.UserProfile'
What I am not sure is how do I create a user such that the UserProfile and User are both created and the custom fields in UserProfile such as emailId, dateCreated are populated?
In views.py I have the following
def register_user(request):
json_data = json.loads(request.raw_post_data)
email=json_data['email'].lower()
pwd = json_data['password']
#hard-coded values for testing
UserProfile.user = User.objects.create_user('john', email, pwd)
userProfile, created = UserProfile.objects.get_or_create(emailId=email)
userProfile.password=pwd
However, I get an error AttributeError: 'UserProfile' object has no attribute 'user_id'. I think I am mixing up the concepts somewhere here. Any help is appreciated.
Thanks for the replies. The code that you provided worked! I was also able to do the same using the following:
user = User.objects.create_user('john', email, pwd)
userProfile = user.get_profile()
userProfile.emailId = email
user.save()
userProfile.save()
Wondering if both are similar, or if there is any benefit of one over the other by using the get_profile()
Thanks again!
Upvotes: 0
Views: 354
Reputation: 37319
You're trying to assign directly to your UserProfile class rather than to an instance of it, here:
UserProfile.user = User.objects.create_user('john', email, pwd)
You want something like this:
new_user = User.objects.create_user('john', email, pwd)
userProfile, created = UserProfile.objects.get_or_create(user=new_user, defaults={'useremailId': email})
Upvotes: 2