Sprig Mendle Sprig Mendle - 4 months ago 41
Python Question

how do catch A 'UNIQUE constraint failed' 404 in django

how do i specifically catch a UNIQUE constraint failed 404 in the following code, i know i have to add something in the ( here? ) section

q = AnswerModel(user=user, yes_question=question_model)
except ( here? ):
return HttpResponseRedirect('/user/already_exists')

from django.db import IntegrityError

except IntegrityError:

This is what you need.

EDITED for @mbrochh:

from django.db import IntegrityError

except IntegrityError as e:
    if 'unique constraint' in e.message:
        #do something

Yes, you can be more precise but in question case UNIQUE failed is highly likely.