我有一个小的Django计算器应用。我想在单击任何数字按钮时在文本框中显示值
<form action ="buttonClicked" method="POST">
{% csrf_token %}
<div class="calculator">
<input type="text" class="calculator-screen" value="0" disabled name = "text-box"/>
<div class="calculator-keys">
<button type="button" class="operator" value="+">+</button>
<button type="button" class="operator" value="-">-</button>
<button type="button" class="operator" value="*">×</button>
<button type="button" class="operator" value="/">÷</button>
<button type="button" value="7">7</button>
<button type="button" value="8">8</button>
<button type="button" value="9">9</button>
<button type="button" value="4">4</button>
<button type="button" value="5">5</button>
<button type="button" value="6">6</button>
<button type="submit" value="1" name="btn1">1</button>
<button type="button" value="2">2</button>
<button type="button" value="3">3</button>
<button type="button" value="0">0</button>
<button type="button" class="decimal" value=".">.</button>
<button type="button" class="all-clear" value="all-clear">AC</button>
<button type="button" class="equal-sign" value="=">=</button>
</div>
</div>
</form>
{% endblock %}
from django.shortcuts import render
from django.contrib import messages
def calc(request):
if request.method == 'POST':
#here i want to take the button value and display it on text box
return render(request, 'Calculator.html')
如果我按下按钮1,则它应该在文本框中显示1 ... 我该怎么办?
def calc(request):
if(request.POST.get('btn1')):
print('Button clicked')
return render(request, 'Calculator.html',{'val':100})
else:
return render(request, 'Calculator.html',{'val':0})
答案 0 :(得分:0)
我不确定是否可以看到该值,但是如果为按钮指定一个名称,则可以检查它是否在POST中。例如:
<div class="calculator-keys">
<button type="button" class="operator" value="+" name="btn_plus">+</button>
<button type="button" class="operator" value="-" name="btn_minus">-</button>
<button type="button" class="operator" value="*" name="btn_times">×</button>
<button type="button" class="operator" value="/" name="btn_divide">÷</button>
</div>
然后在视图中:
if 'btn_plus' in request.POST: ...
等