Answer the question
In order to leave comments, you need to log in
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))
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
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 questionAsk a Question
731 491 924 answers to any question