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')
To handle unique constraint violations: Catch uniqueness exceptions thrown by the database at the lowest level possible — in the UnitOfWork class. Convert them into Result. Use the UnitOfWork in the controller to explicitly commit pending changes and see if there are any uniqueness constraint violations.
New in Django 4.0. Positional argument *expressions allows creating functional unique constraints on expressions and database functions. creates a unique constraint on the lowercased value of the name field in descending order and the category field in the default ascending order.
This means that your DB is expecting that field to have a value. So when it doesn't you get an error. null. If True, Django will store empty values as NULL in the database. Default is False.
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: # or e.args[0] from Django 1.10 #do something
Yes, you can be more precise but in question case UNIQUE failed
is highly likely.
IMHO, I would recommend to resolve this situation by get_or_create().
new_obj, created = AnswerModel.objects.get_or_create(user=user, yes_question=question_model) if created: do_something_for_new_object(new_obj) else: logging.error("Duplicated item.") return
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With