Sprig Mendle Sprig Mendle - 5 days ago 7
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

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

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

Comments