Wandering Digital
Wandering Digital

Reputation: 1868

Updating user profile after user create in Django

I've extended the user object using the 1.4x method by adding a custom "profile" model and then instantiating it on user save/create. During my registration process I'd like to add additional information to the profile model. The view successfully renders, but the profile model doesn't save. Code below:

    user = User.objects.create_user(request.POST['username'], request.POST['email'], request.POST['password'])
    user.save()

    profile = user.get_profile()
    profile.title = request.POST['title']
    profile.birthday = request.POST['birthday']

    profile.save()

Upvotes: 1

Views: 5481

Answers (2)

Yousuf Jawwad
Yousuf Jawwad

Reputation: 3097

update your models.py with this code

from django.db.models.signals import post_save
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)

now when you do

user.save()

it will automatically create a profile object. then you can do

user.profile.title = request.POST['title']
user.profile.birthday = request.POST['birthday']
user.profile.save()

hope it helps.

Upvotes: 6

fakhir hanif
fakhir hanif

Reputation: 665

user is an instance of User model. And it is seems like you are trying to get an instance which is already exists. It depends on what you returning from user.get_profile. You have to initiate UserProfile instance. The simpler way could be like this:

user_profile = UserProfile.objects.create(user=user)
user_profile.title = request.POST['title']
...
.
.
user_profile.save()

Upvotes: 1

Related Questions