我想在django中按特定数字按钮时看到该值

时间:2019-08-18 18:14:43

标签: python html django view

我有一个小的Django计算器应用。我想在单击任何数字按钮时在文本框中显示值

我的HTML代码

 <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="*">&times;</button>
          <button type="button" class="operator" value="/">&divide;</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 %}

我的view.py

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')

Calc

如果我按下按钮1,则它应该在文本框中显示1 ... 我该怎么办?

解决了我的问题

View.py

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})

1 个答案:

答案 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">&times;</button>
      <button type="button" class="operator" value="/" name="btn_divide">&divide;</button>
    </div>

然后在视图中:

if 'btn_plus' in request.POST: ...