【问题标题】:Get the name of the submit button that was clicked in django获取在 django 中被点击的提交按钮的名称
【发布时间】:2021-04-09 02:40:33
【问题描述】:

我在这个表单中创建提交按钮,每个按钮对应一个产品对象:

<form action="/costcorrect/product_choice" method="post">
    {% csrf_token %}
      {% for product in product_list %}    
      <div class="product">
        <img src="{{product.image_url}}" alt="{{product.name}}">
        <h2>{{product.name}}</h2>
        <input type="submit" name="{{product.id}}" value="Choose Product"> 
      </div>
      {% endfor %}
    </form>

我想获取用户点击的按钮的名称,这样我就知道选择了哪个产品。

与此相关的其他问题(如this one)具有固定名称的按钮,因此很容易引用它们。我的问题是我不确定按钮的名称是什么,所以我不能直接在视图中引用它们。

【问题讨论】:

  • 查看 Ayman 的回答:stackoverflow.com/questions/866272/…
  • 在这种情况下,按钮的名称是已知的并且不会更改,因此您可以在函数中通过名称来引用它们。在我的情况下,按钮的名称是我列表中 Product 对象的 id,每次有人加载页面时都会有所不同,因此很遗憾我无法使用该解决方案。

标签: django django-forms


【解决方案1】:

您可以使用request.POST 获取视图中单击的按钮的动态名称。您需要在视图中获得相同的product_list,并与来自模板的传入product.id 进行比较。你的代码会像

for product in product_list:
    for key, value in request.POST.items():
        if product.get('id') == key and value == 'Choose Product':
            print('key => ', key)
            print('value => ', value)

我正在使用value="Choose Product",因为您已经在表单中使用了它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    相关资源
    最近更新 更多