We are trying to redirect to our checkout.html page which requires an id in its arguments to get to, but we are trying to get to it using Javascript.
In out store.html page
{% for item in product %}
<div class="col-md-3">
<div class="card" style="width: 90%; margin: 5px 5px;">
<a href="Product/{{item.id}}"><img src="{{item.image.url}}" class="card-img-top"></a>
<div class="cart-footer text-center">
<button onclick="redirect()">Order</button>
</div>
</div>
</div>
{% endfor %}
<script>
function redirect() {
var url = "{% url 'Checkout' %}";
var id = $(this).item('id');
window.location.href = url + "/" + id;
}
</script>
We know we can just use a regular button like
<button onclick="window.location.href='Checkout/{{item.id}}'">Order</button>
Which is how we had it before, but we're trying to get it through Javascript for future use How do you get a specific objects' id in javascript?
urls.py
path('', views.Store, name= "Store"),
path('Checkout/<id>', views.createlocation, name="Checkout"),
path('Product/<id>', views.product_details, name="Product")
In Your Template :
.
.
{{ item|json_script:"item_obj" }}
<button onclick="redirect()">Order</button>
.
.
Then In your JS function
function redirect() {
var url = "{% url 'Checkout' %}";
const item = JSON.parse(document.getElementById('item_obj').textContent);
window.location.href = url + "/" + item[id];
}
Checkout this example from doc