Sprig Mendle Sprig Mendle - 1 year ago 97
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')

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download