0

I have this form where I create submit buttons which each correspond to a Product object:

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

I want to get the name of the button the user clicks on, so I know which product was selected.

Other questions (like this one) that are related to this had buttons with fixed names, so it was easy to refer to them. My issue is that I'm not sure what the names of the buttons will be, so I can't refer to them directly in views.

user7758051
  • 304
  • 2
  • 5
  • 18
  • Check out this answer by Ayman: https://stackoverflow.com/questions/866272/how-can-i-build-multiple-submit-buttons-django-form – SLDem Jan 02 '21 at 20:07
  • In that situation, the name of the buttons are known and don't change, so you can refer to them by name in the function. In my situation, the name of the button is the id of a Product object from my list, which will be different every time someone loads the page, so I can't use that solution unfortunately. – user7758051 Jan 02 '21 at 20:25

1 Answers1

0

You can get the dynamic name of button clicked in view by using request.POST. You need to get the same product_list in the view and compare with the incoming product.id from template. your code will be like

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)

I am using value="Choose Product" because you are already using it in your form.

Sohaib
  • 566
  • 6
  • 15