From e57eafaf9e47e943769459a9df0e6d098662ad1a Mon Sep 17 00:00:00 2001 From: Andreas Zweili Date: Mon, 5 Feb 2018 21:25:18 +0100 Subject: [PATCH] wrap the registration in a transaction Sometimes when the creation of the person object fails the user get's created anyway resulting in a user without a user profile. By wrapping both the user and profile creation in a transaction the user gets only created if the person profile worked as well. --- django/didgeridoo/webshop/views.py | 32 ++++++++++++++++-------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/django/didgeridoo/webshop/views.py b/django/didgeridoo/webshop/views.py index 32fab77..5b6a776 100644 --- a/django/didgeridoo/webshop/views.py +++ b/django/didgeridoo/webshop/views.py @@ -3,6 +3,7 @@ from django.shortcuts import get_object_or_404, render from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm +from django.db import transaction from webshop.models import (Article, Category, ArticleStatus, Person, City, Picture, CartPosition, ShoppingCart) from webshop.forms import RegistrationForm, AddToCartForm @@ -200,21 +201,22 @@ def registration(request): profile_form = RegistrationForm(request.POST) user_form = UserCreationForm(request.POST) if (profile_form.is_valid() and user_form.is_valid()): - pf = profile_form.cleaned_data - uf = user_form.cleaned_data - user = User.objects.create_user(uf['username'], - pf['email'], - uf['password2']) - user.last_name = pf['last_name'] - user.first_name = pf['first_name'] - user.save() - person = Person.objects.create( - salutation=pf['salutation'], - city=City.objects.get(zip_code=pf['zip_code'], - name=pf['city']), - street_name=pf['street_name'], - street_number=pf['street_number'], - user=user) + with transaction.atomic(): + pf = profile_form.cleaned_data + uf = user_form.cleaned_data + user = User.objects.create_user(uf['username'], + pf['email'], + uf['password2']) + user.last_name = pf['last_name'] + user.first_name = pf['first_name'] + user.save() + person = Person.objects.create( + salutation=pf['salutation'], + city=City.objects.get(zip_code=pf['zip_code'], + name=pf['city']), + street_name=pf['street_name'], + street_number=pf['street_number'], + user=user) return HttpResponseRedirect('/login/') else: profile_form = RegistrationForm