views层
def cal_view(request):
if request.method == 'GET':
#显示页面
return render(request,'cal.html')
elif reqeust.method == 'POST':
#处理数据
#拿x, 计算方法,y
x = request.POST.get('x')
#如果用户未输入x,将提示信息传给模板层显示
if not x:
error = 'Please give me x!'
dic = {'error':error}
return render(request,'cal.html',dic)
#将x转为整型,try一下用户可能输入不是数字的情况
try:
x = int(float(x))
except Exception as e:
error = 'The x is must be number !!'
dic = {'error':error}
return render(reqeust,'cal.html',dic}
op = request.POST.get('op')
#TODO 检查 y值是否有和是否为数字
y = request.POST.get('y')
if op == 'add':
result = x + y
elif op == 'sub':
result = x - y
elif op == 'mul':
result = x * y
elif op == 'dic':
result == x / y
return render(request,'cal.html',locals())
models层
<body>
{% if error %}
错误提示:{{ error }}
{% endif
<form action='/cal' method='POST'>
<input type='text' name='x' value='{{ x }}>
<select name='op'>
<!-- 使用selected属性设置默认下拉列表 -->
<option value='add' {% if op == 'add' %}selected{% endif %}> +加 </option>
<option value='sub' {% if op == 'sub' %}selected{% endif %}> -减 </option>
<option value='mul' {% if op == 'mul' %}selected{% endif %}> *乘 </option>
<option value='div' {% if op == 'div' %}selected{% endif %}> /除 </option>
</select>
<input type=text' name='y' value='{{ y }}'> = <span>{{ result }}</span>
<div>
<input type='submit' value='开始计算'>
</div>
</body>