Reputation: 1673
I am trying to get the product id using request.post in Django. I am currently testing using the console, but the only product_id value I am returned is 1.
This is the particular function in the view:
def test_view(request):
cart_obj, new_obj = Cart.objects.new_or_get(request)
my_carts_current_entries = Entry.objects.filter(cart=cart_obj)
products = Product.objects.all()
if request.POST:
product_id = request.POST.get('product_id')
entry_quantity = request.POST.get('entry_quantity')
product_obj = Product.objects.get(id=product_id)
print(product_id)
# print(entry_quantity)
# Entry.objects.create(cart=cart_obj, product=product_obj, quantity=product_quantity)
return render(request, 'carts/test.html', {'cart_obj': cart_obj, 'my_carts_current_entries': my_carts_current_entries,
'products': products})
This is the html on the template.
<form method="POST">
<br>
{% csrf_token %}
{% for product in products %}
{{ product.name }} <br>
<button>Add to Basket</button>
{{ product.id }}
<input type="hidden" name='product_id' value='{{ product.id }}'>
<br>
{% endfor %}
</form>
Upvotes: 1
Views: 1932
Reputation: 1213
Your problem is that you have as many <input>
tags within 1 <form>
as many products you have displayed. They all have the same name, so you always get the value of the first one.
I'd recommend getting rid of <input>
and attaching the value of product.id
to the button itself (or <input type="submit">
to be exact). Here's the more descriptive explanation:
How can I build multiple submit buttons django form?
An alternative would be to change your code to have multiple forms, like that:
{% for product in products %}
<form method="POST">
{% csrf_token %}
{{ product.name }}
<br/>
<button>Add to Basket</button>
{{ product.id }}
<input type="hidden" name='product_id' value='{{ product.id }}'>
</form>
<br/>
{% endfor %}
Upvotes: 2