Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

python - Writing Customized functions in django views

how can I return error from a python function and display it in Django temaplate. I have a code base that is similar to the following structure:

In Views.py:

def calculate(num1, num2):
    result = int(num1) + int(num2)
    return result

def home(request):
    if request.method == POST:
       user_input_1 = request.POST.get('user_input_1 ')
       user_input_2 = request.POST.get('user_input_2 ')

       calculator = calculate(user_input_1 , user_input_2 )
       context = {
           'calculator' : calculator 
        }
       return render(request, 'home.html', context)
    return render(request, 'home.html')

So in the case were the user enters a letter instead of a digit, I want to display an error in the django template telling the user about the error. Right now when error occurs the code crashes. I know that I can write a try and except to handle the error but I don't know how to display the exact error message on the HTML template. Any Ideas on how to go about this please?

question from:https://stackoverflow.com/questions/65842295/writing-customized-functions-in-django-views

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

try this

def calculate(num1, num2):
   result = ''
   try: 
       result = int(num1) + int(num2)
   except Exception as e:
       result = str(e.args)
   return result    

def home(request):
    if request.method == POST:
       user_input_1 = request.POST.get('user_input_1 ')
       user_input_2 = request.POST.get('user_input_2 ')

       calculator = calculate(user_input_1 , user_input_2 )
       context = {
           'calculator' : calculator 
        }
       return render(request, 'home.html', context)
    return render(request, 'home.html')

this will get your job done.

More about python exceptions

https://docs.python.org/3/tutorial/errors.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...