Xonal
Xonal

Reputation: 1350

How to execute code in Django if an error occurs?

One of the views that I call works with two database tables. It attempts to find an object in the first table. If the object isn't found, I get a Server Error (500). I'm not sure what the code would look like, but I want to insert some code into the view that will execute if the Server Error occurs so that I can tell it to try to find the object in the second table.

Current Code:

@csrf_exempt
@login_required
def addEvent(request):
    event_id = request.POST['event_id']
    user = request.POST['profile']
    event = Event.objects.get(event_id = event_id)
    if event.DoesNotExist:
        event = customEvent.objects.get(event_id = event_id)
    user = Profile.objects.get(id = user)
    user.eventList.add(event)

    return HttpResponse(status = 200)

Upvotes: 0

Views: 106

Answers (1)

miki725
miki725

Reputation: 27861

Most likely you are getting 500 error because you are not finding a record in the first table. To fix that, you just have to catch the DoesNotExist Exception (Mentioned here):

try:
    obj = FooModel.objects.get(...)
except FooModel.DoesNotExist:
    try:
        obj = OtherModel.objects.get(...)
    except OtherModel.DoesNotExist:
        raise Http404

or you can simplify this by using a shortcut:

try:
    obj = FooModel.objects.get(...)
except FooModel.DoesNotExist:
    obj = get_object_or_404(OtherModel, ...)

Upvotes: 2

Related Questions