django-post提交與顯示(小案例)
阿新 • • 發佈:2021-07-31
一個簡單的小案例post提交與輸出
分為載入頁面與顯示頁面
views.py
def cal(request): return render(request,'example.html') def result(request): info={} info['value1']=int(request.POST['first_value']) info['value2']=int(request.POST['second_value']) if request.POST['Calculation']=='add': info['result']=info['value1']+info['value2'] elif request.POST['Calculation']=='sub': info['result']=info['value1']-info['value2'] elif request.POST['Calculation']=='mul': info['result']=info['value1']*info['value2'] else: info['result']=info['value1']/info['value2'] a={'add':'加', 'sub':'減', 'mul':'乘', 'div':'除' } info['cal']=a[request.POST['Calculation']] return render(request,'result.html',info)
example.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>小例項</title> </head> <body> <form action="result/" method="POST"> {% csrf_token %} <input type="text" name="first_value" > </br> <select name="Calculation" > <option value="add">加</option> <option value="sub">減</option> <option value="mul">乘</option> <option value="div">除</option> </select></br> <input type="text" name='second_value'> </br> <input type="submit" vaule='開始計算'> </form> </body> </html>
result.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>顯示結果</title> </head> <body> <a href="{% url 'cal' %}">返回計算</a> </br> <span>{{value1}}</span> <span style="color: chartreuse;" >{{cal}}</span> <span>{{value2}}</span> <span style="color: rgb(245, 19, 19);">=</span> <span>{{result}}</span> </body> </html>
url.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('cal/',views.cal,name='cal'),
path('cal/result/',views.result,name='result')
]