繁体   English   中英

Django 表单集未将所有 forms 保存到数据库

[英]Django formsets not saving all forms to the database

  1. 我有一个表单集可以一次渲染多个 forms。 默认情况下,仅渲染两个 forms。
  2. 使用 JavaScript,我将另外两个 forms 添加到表单集中,因此 forms 的总数现在是四个。
  3. 当我发送 POST 请求时,我的视图只将前两个对象保存到数据库中。 不保存使用 JavaScript 添加的 forms 中的数据。

我究竟做错了什么? 我的代码:

这是我的 forms.py 文件,我在其中定义我的表单集。

class AddAnswerForm(ModelForm):
    class Meta:
        model = Answer
        exclude = ['question']
        widgets = {
            'answer_text': forms.TextInput(attrs={'class': 'input'}),
        }

AnswerFormSet = modelformset_factory(Answer, form=AddAnswerForm, extra=2, max_num=4)

这是 JS 代码,我用它来向页面添加新的 forms(它不是我的代码,但它可以工作)。

<script>
  let answerForm = document.querySelectorAll(".answer-form")
  let container = document.querySelector("#question-form")
  let addButton = document.querySelector("#add-form")
  let totalForms = document.querySelector("#id_form-TOTAL_FORMS")

  let formNum = answerForm.length-1
  addButton.addEventListener('click', addForm)

  function addForm(e){
    e.preventDefault()

    let newForm = answerForm[0].cloneNode(true)
    let formRegex = RegExp(`form-(\\d){1}-`, 'g')

    formNum++
    newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form=${formNum}-`)
    container.insertBefore(newForm, addButton)

    totalForms.setAttribute('value', `${formNum+1}`)
  }
</script> 

这是我的观点。

class QuestionAddView(View):
    form_class = NewQuestionForm
    form_class_for_answers = AnswerFormSet
    template_name = 'questions/question_add.html'

    def get(self, request, *args, **kwargs):
        form = self.form_class()
        answers_form = self.form_class_for_answers(queryset=Answer.objects.none())

        return render(request, self.template_name, {'form': form, 'answers_form': answers_form})

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST, request.FILES)
        answers_form = self.form_class_for_answers(request.POST)
        print(request.POST)
        if form.is_valid() and answers_form.is_valid():
            new_question = form.save(commit=False)
            new_question.author = request.user
            new_question.save()
            print(answers_form)

            instances = answers_form.save(commit=False)
            print(instances)
            for instance in instances:
                print(instance)
                instance.question = new_question
                instance.save()

            return HttpResponseRedirect('/')

print(request.POST) 打印:

<QueryDict: {'csrfmiddlewaretoken': ['eTaR0N4LgG1WvfK3zshqOcEMYUMvXWkxctfS6OXD9E2rMbMe5VrlTVsBgnjoM2zd'], 'title': ['321321'], 'picture': [''], 'body': ['123123'], 'difficulty': ['None'], 'answer_explanation': ['12321'], 'form-TOTAL_FORMS': ['4'], 'form-INITIAL_FORMS': ['0'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['4'], 'form-0-answer_text': ['orage'], 'form-0-id': [''], 'form-1-answer_text': ['apple'], 'form-1-id': [''], 'form=2-answer_text': ['grapes'], 'form=2-id': [''], 'form=3-answer_text': ['pear'], 'form=3-id': ['']}>

print(answers_form) 打印这个。 所以,我假设 JS 脚本在做它的工作是正确的

<input type="hidden" name="form-TOTAL_FORMS" value="4" id="id_form-TOTAL_FORMS"><input type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS"><input type="hidden" name="form-MIN_NUM_FORMS" value="0" id="id_form-MIN_NUM_FORMS"><input type="hidden" name="form-MAX_NUM_FORMS" value="4" id="id_form-MAX_NUM_FORMS"><tr>
    <th><label for="id_form-0-answer_text">Answer text:</label></th>
    <td>
      
      <input type="text" name="form-0-answer_text" value="orage" class="input" maxlength="250" id="id_form-0-answer_text">
      
      
    </td>
  </tr>

  <tr>
    <th><label for="id_form-0-is_correct">Is correct:</label></th>
    <td>
      
      <input type="checkbox" name="form-0-is_correct" id="id_form-0-is_correct">
      
      
        <input type="hidden" name="form-0-id" id="id_form-0-id">
      
    </td>
  </tr><tr>
    <th><label for="id_form-1-answer_text">Answer text:</label></th>
    <td>
      
      <input type="text" name="form-1-answer_text" value="apple" class="input" maxlength="250" id="id_form-1-answer_text">
      
      
    </td>
  </tr>

  <tr>
    <th><label for="id_form-1-is_correct">Is correct:</label></th>
    <td>
      
      <input type="checkbox" name="form-1-is_correct" id="id_form-1-is_correct">
      
      
        <input type="hidden" name="form-1-id" id="id_form-1-id">
      
    </td>
  </tr><tr>
    <th><label for="id_form-2-answer_text">Answer text:</label></th>
    <td>
      
      <input type="text" name="form-2-answer_text" class="input" maxlength="250" id="id_form-2-answer_text">
      
      
    </td>
  </tr>

  <tr>
    <th><label for="id_form-2-is_correct">Is correct:</label></th>
    <td>
      
      <input type="checkbox" name="form-2-is_correct" id="id_form-2-is_correct">
      
      
        <input type="hidden" name="form-2-id" id="id_form-2-id">
      
    </td>
  </tr><tr>
    <th><label for="id_form-3-answer_text">Answer text:</label></th>
    <td>
      
      <input type="text" name="form-3-answer_text" class="input" maxlength="250" id="id_form-3-answer_text">
      
      
    </td>
  </tr>

  <tr>
    <th><label for="id_form-3-is_correct">Is correct:</label></th>
    <td>
      
      <input type="checkbox" name="form-3-is_correct" id="id_form-3-is_correct">
      
      
        <input type="hidden" name="form-3-id" id="id_form-3-id">
      
    </td>
  </tr>

print(instances) 给出:

[<Answer: orage>, <Answer: apple>]

所以,我的问题是:如何正确地将 JS 中创建的 forms 中的数据添加到数据库中?

查看您为第二个表单发送form-1-answer_text的帖子数据,第三个您发送带有等号form=2-answer_text ('=')

你需要更正你的js:

newForm.innerHTML = newForm.innerHTML.replace(formRegex, `form-${formNum}-`)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM