Я работаю над шаблоном, который генерирует динамически несколько строк.
Когда я отправляю форму, я не могу получить всю сгенерированную строку из шаблона. Сохраняется только последний.
Я думаю, что мне чего-то не хватает, чтобы получить данные из сгенерированных строк.
Вот мой код:
модели. 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
<div data-role="dynamic-fields">
{{ form_Product.management_form }}
<div class="form-inline" style="margin-left: -15px">
<div class="form-group col-md-2">
{{ form_Product.quantity }}
</div>
<div class="form-group col-md-2">
{{ form_Product.serialNumber }}
</div>
<div class="form-group col-md-2">
<button class="btn btn-danger" data-role="remove">
<span class="fas fa-minus"></span>
</button>
<button class="btn btn-primary" data-role="add">
<span class="fas fa-plus"></span>
</button>
</div></div></div>
views.py
def form_exhibit_c(request):
template_name = 'supportContract/ExhibitCtemplate.html'
if request.method == 'GET':
formset = ProductFormset(request.GET or None)
form_SupportContract = SupportContractForm(request.GET or None)
form_ProductDescription = ProductDescriptionForm(request.GET or None)
elif request.method == 'POST':
formset = ProductFormset(request.POST)
form_SupportContract = SupportContractForm(request.POST)
form_ProductDescription = ProductDescriptionForm(request.POST)
form_SupportContract.save(commit=False)
form_ProductDescription.save(commit=False)
if formset.is_valid():
for form in formset:
serialNumber = form.cleaned_data.get('serialNumber')
if serialNumber :
p = Product.objects.create(serialNumber=serialNumber, quantity='1')
else:
form_SupportContract = SupportContractForm()
form_ProductDescription = ProductDescriptionForm()
formset = ProductForm()
return render(request, template_name, {'form_Product' : formset, 'form_ProductDescription': form_ProductDescription, 'form_SupportContract' : form_SupportContract})
dynamicFields.js
// Remove button click
$(document).on(
'click',
'[data-role="dynamic-fields"] > .form-inline [data-role="remove"]',
function(e) {
e.preventDefault();
$(this).closest('.form-inline').remove();
});
// Add button click
$(document).on(
'click',
'[data-role="dynamic-fields"] > .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);
});
});