A
A
Andrew2020-02-20 17:10:47
Django
Andrew, 2020-02-20 17:10:47

How to handle ValueError and ValidationError exceptions in Django?

Hello!

There is a django application, not rest. In the service layer, where the user file is processed, exceptions are thrown with their own text.
Type:

if column_name not it data_columns:
    raise ValueError("Упс... Столбец {} отсутствует в талице".format(column_name))

Question: how to return this message to the user in the html template?

Prompt or direct to the source. Everywhere only form error handling.

views.py
def index(request):
    if request.method == "POST":
        excel_file = request.FILES["excel_file"] 
        df = read_file_to_df(excel_file) # парсинг файла 
        file_url = write_to_excel(df)

        context = {"file_url": file_url}
        return render(request, 'calcdist/index.html', context)


def read_file_to_df(file):
    data = pd.read_excel(file)
    if column_name not in data.columns:
        raise ValueError("Упс... В твоем файле не найден столбец {}".format(column_name))
    return data

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew, 2020-02-21
@fugro

I found the answer for myself here
ValueError and ValidationError come with server error 500.
Custom message can be obtained via sys.exc_info()
error_type - error type
tb - traceback

def server_error(request):
    import sys, traceback

    error_type, error, tb = sys.exc_info()

    context = {
        'error_message': error
    }

    response = render_to_response('calcdist/index.html', context)
    response.status_code = 500
    return response

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question