django-post提交与显示(小案例)

一个简单的小案例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')
]
posted @ 2021-07-30 20:34  yescarf  阅读(144)  评论(0编辑  收藏  举报