You need to enable JavaScript to run this app. Django中inlineformset factory结合原生JS实现动态子表单仅保存最后一项问题
优惠活动
大模型
产品
解决方案
定价
更多

Django中inlineformset factory结合原生JS实现动态子表单仅保存最后一项问题

问题根因

  • 直接克隆现有DOM的逻辑没有修改字段的name属性,所有新增行的字段名和原生表单完全重复,浏览器提交同名字段时只会保留最后一条的值,后端仅能解析到最后一行的内容
  • 动态增删行后没有同步更新formset的TOTAL_FORMS计数,Django后端会严格按照management_form里声明的表单数量解析POST数据,超出计数的字段会被直接丢弃
  • 给单个表单项设置固定IDrelInputs,导致DOM中重复ID冲突,JS删除、选择元素的逻辑失效

分步修改方案

1. 模板结构调整

  • 移除表单项上固定重复的id="relInputs",替换为类选择器class="relInputs",符合HTML同ID唯一的规范
  • 在现有表单循环渲染结束后,新增隐藏的空白克隆模板,直接使用Django formset自带的empty_form渲染,避免自行手写结构出现字段遗漏:
{% for item in items.forms %}
  <!-- 原有循环渲染的表单项结构不变,仅把固定id改成class -->
  <div class="relInputs border p-2 rounded-lg mb-4 mt-3 inp">
    <button id="removeRow" type="button" class="bg-red-500 whiteCOLOR px-2 py-1 rounded mb-1">
      <i class="fas fa-trash"></i>
    </button>
    <div class="grid grid-cols-1 md:grid-cols-3 gap-2 mt-3">
      <div class="flex flex-wrap border grayBG rounded-tl-lg rounded-bl-lg">
        <p class="w-5/12 whiteBG flex scale-100 items-center justify-center grayCOLOR rounded-tl-lg rounded-bl-lg">item:</p>
        {{ item.item | add_class:'w-7/12 p-2 rounded-tl-lg rounded-bl-lg focus:outline-none text-right grayBG whiteCOLOR' }}
      </div>
      <div class="flex flex-wrap border grayBG rounded-tl-lg rounded-bl-lg">
        <p class="w-5/12 whiteBG flex scale-100 items-center justify-center grayCOLOR rounded-tl-lg rounded-bl-lg">quantity:</p>
        {{ item.quantity | add_class:'w-7/12 p-2 rounded-tl-lg rounded-bl-lg focus:outline-none text-right grayBG whiteCOLOR' }}
      </div>
    </div>
  </div>
{% endfor %}

<!-- 隐藏的空白克隆模板 -->
<div class="relInputs-template" style="display:none">
  <div class="relInputs border p-2 rounded-lg mb-4 mt-3">
    <button type="button" id="removeRow" class="bg-red-500 whiteCOLOR px-2 py-1 rounded mb-1">
      <i class="fas fa-trash"></i>
    </button>
    <div class="grid grid-cols-1 md:grid-cols-3 gap-2 mt-3">
      <div class="flex flex-wrap border grayBG rounded-tl-lg rounded-bl-lg">
        <p class="w-5/12 whiteBG flex scale-100 items-center justify-center grayCOLOR rounded-tl-lg rounded-bl-lg">item:</p>
        {{ items.empty_form.item | add_class:'w-7/12 p-2 rounded-tl-lg rounded-bl-lg focus:outline-none text-right grayBG whiteCOLOR' }}
      </div>
      <div class="flex flex-wrap border grayBG rounded-tl-lg rounded-bl-lg">
        <p class="w-5/12 whiteBG flex scale-100 items-center justify-center grayCOLOR rounded-tl-lg rounded-bl-lg">quantity:</p>
        {{ items.empty_form.quantity | add_class:'w-7/12 p-2 rounded-tl-lg rounded-bl-lg focus:outline-none text-right grayBG whiteCOLOR' }}
      </div>
    </div>
  </div>
</div>
  • 移除get_context_data里多余的data['items'].full_clean()调用,formset的is_valid()方法会自动完成全量验证,重复调用反而可能触发异常。

2. JS逻辑重写

完全替代原有克隆、删除逻辑,实现索引替换、计数同步、重排功能:

// 初始化当前表单索引值
let currentFormIndex = $("#id_items-TOTAL_FORMS").val();

// 新增行逻辑
$("#addRow").click(function () {
  // 从隐藏模板克隆新表单
  const newForm = $(".relInputs-template").clone().removeClass("relInputs-template").show();
  // 替换模板里的占位索引__prefix__为当前实际索引
  newForm.html(newForm.html().replaceAll("__prefix__", currentFormIndex));
  // 插入到表单容器中
  $("#relatiedInput").append(newForm);
  // 索引自增,同步更新management_form计数
  currentFormIndex++;
  $("#id_items-TOTAL_FORMS").val(currentFormIndex);
});

// 删除行逻辑
$(document).on('click', '#removeRow', function () {
  // 保证最少保留1行
  if ($("#relatiedInput > .relInputs:not(.relInputs-template)").length > 1) {
    $(this).closest('.relInputs').remove();
    // 删除后重排所有行的索引,避免索引断档
    resetFormIndexes();
  }
});

// 公共方法:重排所有现存表单项的索引,同步更新总计数
function resetFormIndexes() {
  const existingForms = $("#relatiedInput > .relInputs:not(.relInputs-template)");
  currentFormIndex = 0;
  existingForms.each(function () {
    // 重排当前行所有字段的name属性,保证索引连续
    $(this).find("[name]").each(function () {
      const oldName = $(this).attr("name");
      const newName = oldName.replace(/-\d+-/, `-${currentFormIndex}-`);
      $(this).attr("name", newName);
    });
    // 重排当前行所有字段的id属性,避免重复
    $(this).find("[id]").each(function () {
      const oldId = $(this).attr("id");
      const newId = oldId.replace(/-\d+-/, `-${currentFormIndex}-`);
      $(this).attr("id", newId);
    });
    currentFormIndex++;
  });
  // 更新management_form的总表单数
  $("#id_items-TOTAL_FORMS").val(currentFormIndex);
}

3. 视图逻辑修正

修正原有判断逻辑的错误,保证空行被正确过滤:

def form_valid(self, form):
    context = self.get_context_data()
    items = context['items']
    with transaction.atomic():
        self.object = form.save(commit=False)
        form.instance.admin = self.request.user
        if form.is_valid() and items.is_valid():
            # 先保存主表对象,拿到关联ID
            self.object = form.save()
            items.instance = self.object
            # 过滤空表单和标记删除的行,再保存子表
            for item_form in items:
                if item_form.cleaned_data and not item_form.cleaned_data.get("DELETE", False):
                    item_form.save()
        else:
            # 验证失败时带错误信息重新渲染页面
            return render(self.request, self.template_name, context)
    return super().form_valid(form)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.30 10:15:07