Django内联表单集-仅保存第一个表单集

时间:2019-04-12 03:43:51

标签: django python-3.x django-forms django-templates inline-formset

我正在尝试动态添加表单集,但是在提交表单集之后,仅保存第一条记录,而忽略其余记录。

我是django的新手,不知道django代码还是js代码中的问题。

models.py

class PvSystem(models.Model):
    gm_name = models.CharField(max_length=60, blank=True, null=True)
    gm_email = models.CharField(max_length=60, blank=True, null=True)

class Institution(models.Model):
    name = models.CharField(max_length=60, blank=True, null=True)
    tax_card = models.CharField(max_length=15, blank=True, null=True)
    pvsystem = models.ForeignKey(PvSystem, on_delete=models.CASCADE, 
    blank=True, null=True)

class OriginalInstitutions(models.Model):
    name = models.CharField(max_length=60, blank=True, null=True)
    tax_card = models.CharField(max_length=15, blank=True, null=True)
    pvsystem = models.ForeignKey(PvSystem, on_delete=models.CASCADE, 
    blank=True, null=True)

forms.py

class InstitutionForm(forms.ModelForm):
    name = forms.ChoiceField(choices=[])
    class Meta:
        model = Institution
        exclude = ()

    def __init__(self, *args, **kwargs):
        super(InstitutionForm, self).__init__(*args, **kwargs)
        cleans = OriginalInstitutions.objects.values_list('name', flat=True)
        self.fields['name'] = forms.ChoiceField(choices = [(name, name) for name in cleans])

class PvSystemForm(forms.ModelForm):
    class Meta:
        model = PvSystem
        exclude = ()

InstitutionFormSet = inlineformset_factory(PvSystem, Institution,
                                            form=InstitutionForm, extra=1)

views.py

class PVSystemList(ListView):
    template_name = 'pvsystem/pvsystem_list.html'
    model = PvSystem

class PVSystemDelete(DeleteView):
    template_name = 'pvsystem/pvsystem_confirm_delete.html'
    model = PvSystem
    success_url = reverse_lazy('pvsystem-list')
class PVSystemCreate(CreateView):
    template_name = 'pvsystem/pvsystem_form.html'
    form_class = PvSystemForm
    success_url = '/'
class PVSystemInstitutionCreate(CreateView):
    template_name = 'pvsystem/pvsystem_form.html'
    fields = ['gm_name','gm_email']
    model = PvSystem
    success_url = reverse_lazy('pvsystem-list')

    def get_context_data(self, **kwargs):
        data = super(PVSystemInstitutionCreate, self).get_context_data(**kwargs)
        if self.request.POST:
            data['institute'] = InstitutionFormSet(self.request.POST)
        else:
            data['institute'] = InstitutionFormSet()
        return data

    def form_valid(self, form):
        context = self.get_context_data()
        institute = context['institute']
        with transaction.atomic():
            self.object = form.save()

            if institute.is_valid():
                institute.instance = self.object
                institute.save()
        return super(PVSystemInstitutionCreate, self).form_valid(form)



class PVSystemUpdate(UpdateView):
    template_name = 'pvsystem/pvsystem_form.html'
    form_class = PvSystemForm
    success_url = '/'

class PVSystemInstitutionUpdate(UpdateView):
    template_name = 'pvsystem/pvsystem_form.html'
    model = PvSystem
    fields = ['gm_name','gm_email']
    success_url = reverse_lazy('pvsystem-list')

    def get_context_data(self, **kwargs):
        data = super(PVSystemInstitutionUpdate, self).get_context_data(**kwargs)
        if self.request.POST:
            data['institute'] = InstitutionFormSet(self.request.POST, instance=self.object)
        else:
            data['institute'] = InstitutionFormSet(instance=self.object)
        return data

    def form_valid(self, form):
        context = self.get_context_data()
        institute = context['institute']
        with transaction.atomic():
            self.object = form.save()

            if institute.is_valid():
                institute.instance = self.object
                institute.save()
        return super(PVSystemInstitutionUpdate, self).form_valid(form)

模板

{% extends "base.html" %}
{% load static %}

{% block title %}{% endblock %}
{% block content %}

    <h3>FormSet example</h3>
<form id="myForm" action="" method="post">{% csrf_token %}    
{{ institute.management_form }}
<div id="form_set">
    {{ form.as_p }}
    {% for form in institute.forms %}
        {{form.non_field_errors}}
            {{form.errors}}
        <table class='no_error'>
            {{ form }}
        </table>

    {% endfor %}

</div>
<input type="button" value="Add More" id="add_more">
<div id="empty_form" style="display:none">
    <table class='no_error'>
        {{ institute.empty_form }}
    </table>

</div>
<input type="submit" value="Save" id="save"/> <a href="{% url 'pvsystem-list' %}">back to the list</a>
</form>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="{% static 'formset/jquery.formset.js' %}"></script>
    <script type="text/javascript">
        $('#add_more').click(function() {
      var form_idx = $('#id_form-TOTAL_FORMS').val();
      $('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx));
      $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1);
    });
    </script>

    <!-- <script type="text/javascript">
      $(function() {
        $('#myForm tbody tr').formset({
          addText: 'add family member',
          deleteText: 'remove',
          prefix: '{{ formset.prefix }}'
        });
      })
    </script> -->
{% endblock %}

我希望该表单将保存所有记录,但事实并非如此。 提交后我该怎么做才能保存所有记录?

2 个答案:

答案 0 :(得分:0)

formset需要适当的前缀 在前缀中添加表单集名称 就是这样

    $('.form_set').formset({
         prefix: '{{ institute.prefix }}',
         addText: 'Add New',
         deleteText: 'Remove',
    })

如果您有任何问题,请告诉我

答案 1 :(得分:0)

对我来说,它适用于{1}以上的extra

赞:

ClassFormSet = inlineformset_factory(ClassA, ClassB,
                                             form=ClassForm, extra=2)