Edgar Navasardyan Edgar Navasardyan - 1 year ago 157
Python Question

Django exception handling cancels non-atomic transaction mode

Best described by example.
Consider the following code (Django 1.9)


def error_generating_view(request):
modelA = ModelA(...)
if (some_bad_condition)
return json_error_msg ('Some custom message')
return HttpResponse(True)

View in other module

def json_error_msg(error_message):
return JsonResponse(json.dumps(error_message, ensure_ascii=False), status = 500, safe = False)

Django seems to through an exception to client-side, but the problem here is that modelA instance is saved, although I set up
. It looks like I am doing something wrong with exception handling syntax.

Could anyone point to what exactly I should rectify here to make Django through customized exception message to client and simultaneously treat the entire view as terminated incorrectly so that the transaction is rolled back ?

Answer Source

Use transaction.atomic decorator, not transaction.non_atomic_requests - by using transaction.non_atomic_requests you're telling Django, that this request should NOT be wrapped in transaction (every change is auto-commited to the database)

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