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

Django动态添加表单行后提交按钮异常问题求助

问题修复方案

1. 修正按钮事件绑定范围

核心问题大概率是提交按钮被误触发了添加行的JS逻辑——之前按钮不在row容器中时,选择器未命中,位置变更后触发了错误逻辑。

  • 给添加行的按钮设置专属类名,比如add-product-row:
    <button type="button" class="btn btn-primary add-product-row">添加产品行</button>
    
  • 修改JS事件委托,仅针对该类按钮触发添加逻辑:
    $(document).on('click', '.add-product-row', function(e) {
      e.stopPropagation();
      // 你的添加行逻辑代码
    });
    

2. 明确提交按钮类型

确保提交按钮的type属性设为submit,避免与添加按钮的逻辑混淆:

<button type="submit" class="btn btn-success">提交表单</button>

3. 规范添加行函数的事件处理

在添加行的函数中,阻止事件冒泡和默认行为,避免影响表单提交:

function addRow(e) {
  e.preventDefault();
  e.stopPropagation();
  
  // 处理Django表单集的隐藏字段更新
  const totalForms = $('#id_product_set-TOTAL_FORMS');
  const formCount = parseInt(totalForms.val());
  
  // 克隆模板行并替换字段的__prefix__标记(Django表单集要求)
  const newRow = $('.form-row-template').clone().removeClass('form-row-template').show();
  newRow.find('[name], [id]').each(function() {
    const name = $(this).attr('name').replace('__prefix__', formCount);
    const id = $(this).attr('id').replace('__prefix__', formCount);
    $(this).attr({'name': name, 'id': id});
  });
  
  // 插入新行并更新表单总数
  $('#product-rows-container').append(newRow);
  totalForms.val(formCount + 1);
}

4. 检查Django表单集隐藏字段

提交后出现None值行,是因为表单集的TOTAL_FORMS、INITIAL_FORMS等隐藏字段未正确更新,导致Django识别出多余空行。确保每次添加行后,同步更新id_product_set-TOTAL_FORMS的数值(如上代码所示)。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 04:51:00