You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中无法获取商品数量输入框值(使用HTMX)

解决HTMX向Django视图发送请求时quantity始终为None的问题

核心问题分析

  1. 请求方式不匹配:按钮使用hx-get发送GET请求,但视图中用request.POST.get('quantity')获取参数——GET请求的参数存储在request.GET对象中,而非request.POST。
  2. HTMX未自动携带表单数据:默认情况下,HTMX不会将表单内的输入框数据附加到GET请求的查询参数中,需明确指定要包含的元素。
  3. 按钮类型冲突:按钮为type="submit",会触发浏览器默认的表单提交行为,与HTMX的请求逻辑产生冲突,可能导致参数丢失。

解决方案

方案一:改用POST请求(推荐,符合修改操作的语义)

  1. 修改HTML按钮:

    • 将hx-get替换为hx-post,与表单的method="post"保持一致
    • 将按钮类型改为type="button",避免浏览器默认提交行为
    • HTMX会自动收集表单内的所有数据(包括quantity和csrf_token)发送POST请求

    修改后的按钮代码:

    <button data-ripple type="button" hx-post="{% 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>
    
  2. 修改视图代码:

    • 对获取到的quantity进行类型转换和异常处理,避免None或非数值导致的错误
    product = Product.objects.get(slug=slug)
    # 获取quantity并转整数,默认值设为1
    quantity = request.POST.get('quantity')
    try:
        quantity = int(quantity) if quantity else 1
    except ValueError:
        quantity = 1  # 处理非数值输入的情况
    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()
    

方案二:继续使用GET请求(不推荐,添加购物车属于修改操作,应遵循REST语义用POST)

若坚持使用GET,需手动指定HTMX携带参数:

  1. 修改HTML按钮:

    • 添加hx-include="[name='quantity']",强制HTMX携带quantity输入框的值
    • 按钮类型改为type="button"
    <button data-ripple type="button" hx-get="{% url 'Add product page' product.slug %}" hx-trigger="click" hx-include="[name='quantity']" class="body-product__add-to-cart button button_cart">
        <span class="_icon-cart-plus">Add to cart</span>
    </button>
    
  2. 修改视图代码:

    • 从request.GET中获取参数并处理
    quantity = request.GET.get('quantity')
    try:
        quantity = int(quantity) if quantity else 1
    except ValueError:
        quantity = 1
    

排查技巧

打开浏览器开发者工具的Network标签,查看HTMX发送的请求:

  • 若请求中没有quantity参数:说明HTMX未正确携带输入框数据,检查hx-include或表单配置
  • 若请求中有quantity参数:说明视图中获取参数的方式错误,检查是用request.GET还是request.POST

内容的提问来源于stack exchange,提问作者Librin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 13:22:17