How do I catch/except registration errors with Django?

I want to be able to return a message to the user when they try to register but their registration fails. I have tried all of the following methods:

  try:
    user = User.objects.create_user(username, email, password)
  except User.DoesNotExist
    print "aaaa"

  try:
    user = User.objects.create_user(username, email, password)
  except IntegrityError
    print "aaaa"

Of course, neither of the above work. How do I properly throw an exception?

Answers


I had the same problem some time ago, here's my solution:

try:
    user = User.objects.get(username=new_username)
    # ERROR! user already exists!
    # if you're using a form you could do:
    # raise forms.ValidationError('Already exists a user with this username!')        
except User.DoesNotExist:
    # We're good!, lets create the user
    user = User.objects.create_user(username, email, password)

I'd suggest using the The Messages Framework.

Also, I can't imagine creating a user throwing DoesNotExist. The whole idea is that the user doesn't exist, so if that's thrown, there are some serious problems going on.

Be aware also that the default backend for the messages framework is to store messages against a session, which won't work for registration (as no user is logged in), so I'd suggest looking into one of the other backends.


Need Your Help

Object Oriented MySQL Statements, PHP

php mysql oop

So far i have got the code below which works lovely when trying an update, delete or select statement. However I run into problems when I try to use an insert. If someone could point me in the corr...

Python - How to append the same XML element multiple times with lxml.objectify

python lxml

I have the following XML that I am trying to recreate with the lxml.objectify package