mysqldjangooperationalerror

Django - grabbing error message from MySQL trigger via handling OperationalError


I have a table in MySQL with a trigger which validates a data and in case of critical value signals an error message.

Here's the trigger code:

CREATE TRIGGER `supermarkets_schema`.`legal_entities_BEFORE_INSERT`
BEFORE INSERT ON `supermarkets_schema`.`legal_entities`
FOR EACH ROW
BEGIN
    DECLARE parent_inn, parent_ogrn, parent_temp_leg_address VARCHAR(300);

    IF some_condition THEN
        SIGNAL sqlstate '45001' set message_text = 'My error msg' 
END

Now, I want to grab this error message in Django and show it on a Django template page.

Here's what I try to do:

import django.db

try:
   legal_entities_details_instance.legal_entities = legal_entities_form.save()
except OperationalError as e:
   return render_to_response("error_handling/main.html", {"message": e.message})

But unfortunately, I can't make Django to handle it correctly. Can it happen because I import an incorrect package for OperationalError? Help me please with that !!!


Solution

  • You haven't imported OperationalError before using it in your code:

    from django.db import OperationalError
    

    You might actually want to catch DatabaseError instead of OperationalError (which is a subclass of DatabaseError).