Imagine a real world issue on your website, you create a new user:


newuser = User.objects.create_user(data['login'],data['email'],data['password'])
newuser.is_active = False
newuser.save()

Associate it with a profile:


newmember = Member(user=newuser,activation_key=activation_key,
   key_expires=key_expires,sexe=data['sexe'])
newmember.save()

Then you want the user to activate that profile by email:


send_mail(email_subject, email_body, 'accounts@titi.com',[newuser.email])

Now imagine for some reasons your mail server can't handle that mail, Django will spawn an exception the account will be created but the user will never received the notification.

In Django there is an elegant solution

Add the TransactionMiddleware to your MIDDLEWARE_CLASSES in settings.py


MIDDLEWARE_CLASSES= (
....
'django.middleware.transaction.TransactionMiddleware', 

import transaction in your views.py


from django.db import transaction

then simply add @transaction.commit_on_success decorator to your view:


@transaction.commit_on_success
     def create_user(request):

Now each time your view will not return a code 200 (ok), Django will roll back all the creation made in the view, so the user can create the account again with the username !!