Встроенные наборы форм Django - сохраните только первый набор форм - PullRequest
0 голосов
/ 12 апреля 2019

Я пытаюсь динамически добавлять формы, но после отправки сохранить только первую запись и игнорировать остальные.

Я новичок в 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 %}

Я ожидал, что форма сохранит все записи, но это не так. Что я могу сделать, чтобы сохранить все записи после отправки?

1 Ответ

0 голосов
/ 12 апреля 2019

formset нужен правильный префикс, добавьте имя formset в префикс вот это

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

если у вас есть какие-либо проблемы, пожалуйста, дайте мне знать

...