Skip to content

Instantly share code, notes, and snippets.

@vitorfs
Last active November 14, 2023 12:11
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vitorfs/cbe877156ba538a20c53c9a1cea29277 to your computer and use it in GitHub Desktop.
Save vitorfs/cbe877156ba538a20c53c9a1cea29277 to your computer and use it in GitHub Desktop.
from django.db import transaction
@transaction.atomic
def create_user_view(request):
if request.method == 'POST':
user_form = UserCreationForm(request.POST)
profile_form = ProfileForm(request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.refresh_from_db() # This will load the Profile created by the Signal
profile_form = ProfileForm(request.POST, instance=user.profile) # Reload the profile form with the profile instance
profile_form.full_clean() # Manually clean the form this time. It is implicitly called by "is_valid()" method
profile_form.save() # Gracefully save the form
else:
user_form = UserCreationForm()
profile_form = ProfileForm()
return render(request, 'core/user_form.html', {
'user_form': user_form,
'profile_form': profile_form
})
@MiniGunnR
Copy link

Maybe mention in a comment that this doesn't redirect to a success page or logs in the user automatically.

@boharabb
Copy link

boharabb commented Nov 2, 2020

'User' object has no attribute 'Profile'
, how to solve this problem

@RinkuMonani
Copy link

'User' object has no attribute 'Profile'
, how to solve this problem

user.'p'rofile not user.'P'rofile

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment