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?
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.