【问题标题】:Handle non-submit input types in django在 django 中处理非提交输入类型
【发布时间】:2021-08-13 05:00:57
【问题描述】:
好的,所以我有两个输入标签,类型为按钮。
<div class="buttons-for-trade-or-sell" style="display: flex; position:relative;left: 33px; top:14px">
<div class="button-to-trade">
<input type="button" class="trade-btn" id="button-to-select-trade" name="trade1" value="Trade"></input>
</div>
<div class="button-to-sell">
<input type="button" class="sell-btn" id="button-to-select-sell" name= "trade2" value="Sell"></input>
</div>
我的问题是如何将选择的按钮发送到服务器端代码。例如,如果选择了 trade-btn,我希望布尔值在我看来设置为 true。然后从那里我会相应地处理它。基本上,我如何将选择的按钮发送到服务器端?
谢谢。
【问题讨论】:
标签:
python
html
python-3.x
django
ajax
【解决方案1】:
有多种方法可以解决这个问题。其中之一是使用纯javascript,并在form 中嵌入一个隐藏的form_type,指定表单是trade 还是sell,并将每个按钮分配给具有不同输入参数的函数。
<from id="my_form" action="#" method="POST">
{% csrf_token %}
<input id='form_type' name='form_type' value='' class='d-none' style='display: None;'>
<div class="buttons-for-trade-or-sell" style="display: flex; position:relative;left: 33px; top:14px">
<div class="button-to-trade">
<input type="button" onclick="update_value_and_submit('trade');" class="trade-btn" id="button-to-select-trade" name="trade1" value="Trade"></input>
</div>
<div class="button-to-sell">
<input type="button" onclick="update_value_and_submit('sell');" class="sell-btn" id="button-to-select-sell" name= "trade2" value="Sell"></input>
</div>
</form>
<script>
function update_value_and_submit(val){
let ftype = document.getElementById('form_type');
ftype.value = val;
let my_form = document.getElementById('my_form');
my_form.submit();
}
</script>