【问题标题】:Get selected value in html select field for django在 django 的 html 选择字段中获取选定的值
【发布时间】:2020-07-17 22:45:33
【问题描述】:

大家好,我正在为我的大学运动员做一个网站,事情是在我的程序中,我创建了一个产品库,然后是这个产品的模型,用于库存控制,我的产品 html 中有一个问题,我创建html 中的一个选择字段来选择某人想要购买的模型,但我需要获取选择的值,因为是我的模型 pk 放入购物车。

<select>
{% for produtos in produtobase.get_produto %}
<option value="{{produtos.pk}}">{{produtos.name}}</option>
{%endfor%}
</select>

我需要在此代码中添加按钮以使添加购物车项目视图,在葡萄牙语“Adicionar_produto”中,这是按钮:

<a href="{% url 'Adicionar_produto' produtos.pk %}"><button class="btn-btn-primary">Adicionar ao Carrinho</button></a>

在 produtos.pk 中,我需要在我的 html 代码中发送所选字段的值,如果有人可以帮助我,请回答这个问题,这对我有很大帮助

【问题讨论】:

    标签: html django templatetags


    【解决方案1】:

    给你的选择标签一个像这样的ID:

    <select id="select-product">
    <options...
    </select>
    

    然后使用 javascript 使用该 id 来获取您想要的值

    document.getElementbyId('select-product').value
    

    将此值传递给您尝试在“a”标签中引用的 url。

    【讨论】:

      【解决方案2】:

      一种解决方案是将选择放在表单中

        <form action="{% url 'adicionar_carrinho' carrinho.id %}" method="post">
          <select id="select-product">
            <options...
          </select>
          <button type="submit" >Adicionar ao Carrinho</button>
        </form>
      

      在您的视图“adicinar_carrinho”中,从表单中调用这种方式,您可以获得带有选择 id 的 post 参数

      def adicionar_carrinho(request, carrihno_id):
          ...
          product_pk = request.POST['select_product']
          ...
      
          
      

      【讨论】:

        猜你喜欢
        • 2022-07-17
        • 1970-01-01
        • 1970-01-01
        • 2013-04-03
        • 2014-01-19
        • 2021-02-26
        • 2018-07-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多