Search code examples
pythonhtmldjangodjango-viewshtmx

Can't get the value of input in Django


I need to get the quantity of products and then add it to the cart. I made an input field with the quantity and when I click 'add to cart' I want to send it to a Django view, but I get None type for some reason. I'm using htmx for dynamic requests.

views.py

product = Product.objects.get(slug=slug)
    quantity = request.POST.get('quantity')
    print(quantity)
    productId = product.pid

    customer = request.user.customer
    product = Product.objects.get(pid=productId)
    order, created = Order.objects.get_or_create(customer=customer, complete=False)

    orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)

    orderItem.quantity = quantity

    orderItem.save()

    if orderItem.quantity <= 0:
        orderItem.delete()

HTML code

<form method="post">{% csrf_token %}
    <div class="body-product__actions">
        <div data-quantity class="body-product__quantity quantity">
            <button data-quantity-minus type="button" class="quantity__button quantity__button_minus"></button>

            <div class="quantity__input">
                                    
            <input data-quantity-value='True' autocomplete="off" type="text" name="quantity" value="1"> <!-- here is the input im trying to get -->
            </div>
            <button data-quantity-plus type="button" class="quantity__button quantity__button_plus"></button>
            </div>
                            
                <button data-ripple type="submit" hx-get="{% url 'Add product page' product.slug %}" hx-trigger="click" class="body-product__add-to-cart button button_cart"><span class="_icon-cart-plus">Add to cart</span></button> <!-- This is the button that sends the htmx request -->

                            
            <a href="#" class="body-product__cicil border-button border-button_cicil">
            <img src="{% static 'mstore/img/icons/cicil.svg' %}" alt="cicil">
</a>
</div>
</form>

I tried to get the value with POST and GET requests, but the result is similar. I have similar code in my other project and it works perfectly.


Solution

  • You're using different methods for form and submit button, which you shouldn't do.

    Try adding hx-post="{% url 'Add product page' product.slug %}" to the form tag and remove hx-get from submit button.

    htmx will include all inputs included in the form and you should see your value in the POST.