[Fixed]-How treat exception in django view?

1👍

The error you get is not due to not handling ValueError but due to not returning a HTTP response back to the client. The error is quite explicit:

ValueError: The view app.views.evaluation didn't return an HttpResponse object. It returned None instead.

First of all, the exception that is raised when you’re trying to save an entry to database with a unique = True contraint is IntegrityError.

Change your evaluation view to this:

# views.py

from django.db import IntegrityError

def evaluation(request):
    # form2 initialization
    form2 = EvalForm()

    if request.method == "POST":
        form2 = EvalForm(request.POST)
        if form2.is_valid():    
            post = form2.save(commit=False)
            try:
                post.save()  # if candidate exists, then IntegrityError will be raised
            except IntegrityError:
                # Handle error here. Maybe add a message or something
                # and pass it though the context
    # if its a GET method, form2 will be unbound (ready to filled with data)
    # if its a POST method, form2 will be filled with any potential errors
    return render(request, 'app/evaluation.html', {'criterions': form2,})
👤nik_m

Leave a comment