django 使用一个唯一ID保存多个表单

laawzig2  于 2023-02-10  发布在  Go
关注(0)|答案(1)|浏览(126)

我正在尝试通过单击save按钮,使用gen_form的唯一ID同时使用下面的模板保存spe_form的多个表单。您能帮助我吗?
该代码仅适用于一种spe_form保存,但不适用于多种格式

def preps(request, prep=None):
    
    if prep_General:
        info = Mprep.objects.get(id=prep)
    else:
        info = Mprep()
    
    # Handle form submissions
    if request.method == 'POST':
        # Instantiate the forms with submitted data
        gen_form = MGForm(request.POST, instance=info)
        spe_form = MSForm(request.POST, prefix='preps')

        if gen_form.is_valid() and spe_form.is_valid():
            gen_form.save()
            preps = spe_form.save(commit=False)
            preps.prep = info
            preps.save()
            messages.success(request, 'Information saved successfully')
            return redirect('preps_view', prep=info.id)
        else:
            messages.error(request, 'Error in saving information')
    else:

        gen_form = MGForm(instance=info)
        spe_form = MSForm(prefix='preps')

    context = {'gen_form': gen_form, 'spe_form': spe_form}
    return render(request, 'base.html', context)

<div class="container mt-5">

  <h1>Measurements Prep</h1>
  <form method="post">
    {% csrf_token %}
    <div class="form-row">
      <div class="form-group col-4">
        {{ gen_form.project|as_crispy_field }}
      </div>
      <div class="form-group col-4">
        {{ gen_form.cell|as_crispy_field }}
      </div>
      <div class="form-group col-4">
        {{ gen_form.sample|as_crispy_field }}
      </div>
    </div>
    <br>
    <table id="myTable" class="table" data-toggle="table" data-mobile-responsive="true" data-pagination="true"
      data-height="460">
      <tbody>
        <tr>
          <th>{{ spe_form_set.name|as_crispy_field }}</th>
          <th>{{ spe_form_set.value|as_crispy_field }}</th>
          <th>{{ spe_form_set.unit|as_crispy_field }}</th>
        </tr>
      </tbody>
      <button id="add-row-button" class="btn btn-primary mt-4">Add Row</button>
    </table>

    <input type="submit" class="btn btn-primary mt-4" value="Save">
  </form>

</div>

<script>
  document.getElementById("add-row-button").addEventListener("click", function () {
    var tableBody = document.getElementById("myTable");
    var newRow = document.createElement("tr");
    newRow.innerHTML = `
      <td>{{ spe_form_set.name|as_crispy_field }}</td>
      <td>{{ spe_form_set.value|as_crispy_field }}</td>
      <td>{{ spe_form_set.unit|as_crispy_field }}</td>
    `;
    tableBody.appendChild(newRow);
  });
</script>
xlpyo6sf

xlpyo6sf1#

您可以为prep示例设置id None,以将其保存为数据库中的新记录:

def preps(request, prep=None):
   ...
   if request.method == 'POST':
        ...
        if gen_form.is_valid() and spe_form.is_valid():
            gen_form.save()
            preps = spe_form.save(commit=False)
            preps.prep = info
            prep.id = None # <-- here
            preps.save()

相关问题