javascript — динамические поля Django — невозможно получить данные из нескольких добавленных строк — данные ManagementForm отсутствуют или были изменены

Динамические поля Django — невозможно получить данные из нескольких добавленных строк — данные ManagementForm отсутствуют или подделаны

Я работаю над шаблоном, который генерирует динамически несколько строк.

Я получаю значение исключения: [‘Данные ManagementForm отсутствуют или были подделаны’], когда я отправляю форму.

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

Вот мой код:

models.py

 class Product(models.Model): contractNumber = models.ForeignKey('SupportContract', on_delete=models.SET_NULL, null=True) serialNumber = models.CharField(max_length=800, null=True) reference = models.ForeignKey('ProductDescription', on_delete=models.SET_NULL, null=True) quantity = models.IntegerField() def __str__(self): return str(self.serialNumber) if self.serialNumber else '' 

form.py

 class ProductForm(forms.ModelForm): contractNumber = forms.ModelChoiceField(required=False, queryset=SupportContract.objects.all().order_by('number'), label='contractNumber', widget=forms.TextInput(attrs={'class': 'form-control','placeholder': 'Contract number'})) serialNumber = forms.CharField(required=True, label='serialNumber',widget=forms.TextInput(attrs={'class': 'form-control','placeholder': 'Enter serial number'})) reference = forms.ModelChoiceField(required=False, queryset=ProductDescription.objects.all().order_by('name'), label='reference',widget=forms.TextInput(attrs={'class': 'form-control','placeholder': 'Product descrition'})) quantity = forms.IntegerField(initial=1, required=True, label='quantity',widget=forms.NumberInput(attrs={'class': 'form-control','placeholder': 'Enter a quantity'})) class Meta: model = Product fields = '__all__' def clean(self): super().clean() contractNumber = self.cleaned_data.get('contract_number') serialNumber = self.cleaned_data.get('serial_number') reference = self.cleaned_data.get('product_reference') quantity = self.cleaned_data.get('quantity') ProductFormset = formset_factory(ProductForm, extra=1) 

template.html

 {amp}lt;div data-role="dynamic-fields"{amp}gt; {{ form_Product.management_form }} {amp}lt;div class="form-inline" style="margin-left: -15px"{amp}gt; {amp}lt;div class="form-group col-md-2"{amp}gt; {{ form_Product.quantity }} {amp}lt;/div{amp}gt; {amp}lt;div class="form-group col-md-2"{amp}gt; {{ form_Product.serialNumber }} {amp}lt;/div{amp}gt; {amp}lt;div class="form-group col-md-2"{amp}gt; {amp}lt;button class="btn btn-danger" data-role="remove"{amp}gt; {amp}lt;span class="fas fa-minus"{amp}gt;{amp}lt;/span{amp}gt; {amp}lt;/button{amp}gt; {amp}lt;button class="btn btn-primary" data-role="add"{amp}gt; {amp}lt;span class="fas fa-plus"{amp}gt;{amp}lt;/span{amp}gt; {amp}lt;/button{amp}gt; {amp}lt;/div{amp}gt;{amp}lt;/div{amp}gt;{amp}lt;/div{amp}gt; 

views.py

 def form_exhibit_c(request): ProductFormset = modelformset_factory(Product, form=ProductForm, extra=1) if request.method == 'POST': form_SupportContract = SupportContractForm(request.POST) form_ProductDescription = ProductDescriptionForm(request.POST) form_Product = ProductFormset(request.POST) form_SupportContract.save(commit=False) form_ProductDescription.save(commit=False) if form_ProductDescription.is_valid() and form_SupportContract.is_valid() and form_Product.is_valid() : tmp_supportContract = form_SupportContract.save(commit=False) tmp_ProductDescription = form_ProductDescription.save(commit=False) try: local_product = ProductDescription.objects.get(vPartNumber__icontains=tmp_ProductDescription.vPartNumber) except ProductDescription.DoesNotExist: raise Http404("error") except ProductDescription.MultipleObjectsReturned: raise Http404("Error") tmp_supportContract.excelFileLink = "__path_to_excel_file" tmp_ProductDescription.name = local_product.name tmp_supportContract.save() try: local_supportContact = SupportContract.objects.filter(number__icontains=tmp_supportContract.number).order_by('id').first() except ProductDescription.DoesNotExist: raise Http404("error") except SupportContract.MultipleObjectsReturned: raise Http404("error") form_Product.contractNumber = local_supportContact.number try: form_Product.contractNumber = SupportContract.objects.filter(number__icontains=tmp_supportContract.number).order_by('id').first() except ProductDescription.DoesNotExist: raise Http404("error") except SupportContract.MultipleObjectsReturned: raise Http404("error") form_Product.save() else: form_SupportContract = SupportContractForm() form_ProductDescription = ProductDescriptionForm() form_Product = ProductForm() return render(request, 'supportContract/ExhibitCtemplate.html', {'form_Product' : form_Product, 'form_ProductDescription': form_ProductDescription, 'form_SupportContract' : form_SupportContract}) 

dynamicFields.js

  // Remove button click $(document).on( 'click', '[data-role="dynamic-fields"] {amp}gt; .form-inline [data-role="remove"]', function(e) { e.preventDefault(); $(this).closest('.form-inline').remove(); }); // Add button click $(document).on( 'click', '[data-role="dynamic-fields"] {amp}gt; .form-inline [data-role="add"]', function(e) { e.preventDefault(); var container = $(this).closest('[data-role="dynamic-fields"]'); new_field_group = container.children().filter('.form-inline:first-child').clone(); new_field_group.find('input').each(function(){ if (this.name == 'quantity') { $(this).val('1'); }else{ $(this).val(''); } }); container.append(new_field_group); }); }); 
Понравилась статья? Поделиться с друзьями:
JavaScript & TypeScript
Adblock
detector