Search code examples
django-modelsdjango-formsdjango-databasedjango-users

Getting last created user to link user profile to in django


I've hit a bit of a wall when trying to add data to a UserProfile model created to hold user info beyond what is catered for in django's built in Auth component.

My question is how do I get an instance of the user just registered in order to create the the UserProfile? I thought it would be something like below:

# Registration form validation etc. is complete
cd = form.cleaned_data
user = User.objects.create_user(username=cd['username'], password=cd['password'])
new_user = user.save() # hoping this returns an instance of the user?
activation_key = some_random_generator()
new_profile = UserProfile(user=new_user, token=activation_key)
new_profile.save()

... but new_user is returning as None and I figure there must be an easy way to get access to the User just registered rather than re-querying the database based on the username/password?

I hope that is clear enough, thanks for any help/guidance.


Solution

  • Solved my own problem. Having a slow day learning python/django.

    When user.save() is called, the user object is updated with new information after database insertion - i.e. the newly generated user.id . So this user object itself can actually be passed to UserProfile().