How do i save all inline forms that adding by javascript?

后端 未结 1 617
青春惊慌失措
青春惊慌失措 2021-01-07 08:11

I am having problem saving inline forms. It does save default forms. But whenever i add new inline forms, It doesnt save. What am i missing? can anyone show me the mistake?

相关标签:
1条回答
  • 2021-01-07 09:05

    Well I can't see any mistakes, but maybe you can use easier solution to add new form, so that you won't have to use jquery formset at all.

    Formset class has nice attribute called empty_form: https://docs.djangoproject.com/en/1.4/topics/forms/formsets/#empty-form

    You can pass it as "empty_form" context variable and add this script inside template:

    <script type="text/template" id="row-template">
      <tr>
        {% for field in empty_form %}
          <td>{{ field }}</td>
        {% endfor %}
      </tr>
    </script>
    
    <script type="text/javascript">
      var formset = {};
    
      $(function() {
        $('.btn-add-extra-form').click(function() {
          formset.$total = $('#id_rows-TOTAL_FORMS');
          formset.$initial = $('#id_rows-INITIAL_FORMS');
          formset.templateRowStr = $('#row-template').html();
    
          formset.newTotal = parseInt(formset.$total.val());
          formset.appendRowStr = formset.templateRowStr.replace(/__prefix__/g, formset.newTotal);
          formset.$total.val(formset.newTotal + 1);
          $('.table-inline-rows tbody').append(formset.appendRowStr);
        });
      });
    </script>
    

    There.. no need to use jquery formset :) and that's the only changes I'm making, I'm not adding any extra code, django takes care of everything.

    0 讨论(0)
提交回复
热议问题