Django 我正在做一个计算器,在所有情况下都返回空值
这是views.py,c的值在浏览器上显示为null。num1是我的第一个html文本框的名称。Num2是我的第二个html文本框的名称Django 我正在做一个计算器,在所有情况下都返回空值,django,Django,这是views.py,c的值在浏览器上显示为null。num1是我的第一个html文本框的名称。Num2是我的第二个html文本框的名称 def calc(request): a=int(request.POST["num1"]) b=int(request.POST["num2"]) if 'add' in request.POST: c=a+b r
def calc(request):
a=int(request.POST["num1"])
b=int(request.POST["num2"])
if 'add' in request.POST:
c=a+b
return c
if 'sub' in request.POST:
c=a-b
return c
if 'mul' in request.POST:
c=a*b
return c
if 'div' in request.POST:
c=a/b
return c
def calprint(request):
c=calc(request)
return render(request,"result.html",{"result":c})
这是方法发布的HTML
<form action="calc" method="POST">
{% csrf_token %}
num 1 <input type="text" name="num1"><br>
num 2 <input type="text" name="num2"><br>
<input type="submit" value="add">
<input type="submit" value="sub">
<input type="submit" value="mul">
<input type="submit" value="div">
</form>
在代码中
if 'add' in request.POST:
c=a+b
return c
您检查request.POST是否有一个key==“add”的项
但在html表单中,您不提供操作提交的名称。对html进行此更改
<input type="submit" name="add" value="add">
<input type="submit" name="sub" value="sub">
<input type="submit" name="mul" value="mul">
<input type="submit" name="div" value="div">
在请求中没有添加
子项
和其他操作。以键
发布
,您可以打印它并查看。这就是为什么不选择任何操作,而函数返回None。在你的提交按钮中添加姓名实际上今天是我在django的第一天,我没有理解你说的话。你能帮我写代码吗
<input type="submit" name="add" value="add">
<input type="submit" name="sub" value="sub">
<input type="submit" name="mul" value="mul">
<input type="submit" name="div" value="div">