django练习 模板层做个简单的计算器页面

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>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值