#javascript #django #formset
Вопрос:
я пытаюсь реализовать два набора форм в одном представлении , один из наборов форм должен быть всплывающей модальной формой ,
class MobileCollection(models.Model): mobile = models.ForeignKey(ModelCategory,on_delete=models.PROTECT,related_name='model_category') qnt = models.IntegerField() price = models.DecimalField(decimal_places=3,max_digits=20) class Imei(models.Model): mobile = models.ForeignKey(MobileCollection,on_delete=models.PROTECT) imei = models.CharField(max_length=15,unique=True) serial_no = models.CharField(max_length=7,unique=True,blank=True,null=True) status = models.BooleanField(default=True) def __str__(self): return f'{self.mobile}-{self.imei}'
на странице мы добавляем новый экземпляр MobileCollection , и у каждой мобильной коллекции есть свой собственный набор imei , если qnt = 10, то мы должны добавить 10 imei
@login_required def create_collection(request): item_formset = mcollection(queryset=MobileCollection.objects.none()) imei_formset = imei_modelformset(queryset=Imei.objects.none(),prefix='imei') if request.POST: item_formset = mcollection(request.POST) imei_formset = imei_modelformset(request.POST,prefix='imei') if imei_formset.is_valid() and item_formset.is_valid() and request.user.is_superuser: for item in item_formset: item_obj = child.save(commit=False) item_obj.save() for imei in imei_formset: imei_obj = imei.save(commit=False) imei_obj.mobile = item_obj imei_obj.save() return JsonResponse({'success':True}) else: return JsonResponse({ 'success':False,'error_child_msg':item_formset.errors,'error_imei_msg':imei_formset.errors}) context = { 'item_formset':item_formset, 'imei_formset':imei_formset } return render(request,'storage/collection.html',context)
но он сохраняет только последнюю запись элемента и не сохраняет imei , будет сохранен только его экземпляр(из элемента) . это мои наборы форм
mcollection = modelformset_factory( MobileCollection,form=MobileCollectionForm,fields= ['mobile','qnt','price'],can_delete=True,extra=1) imei_modelformset = modelformset_factory(Imei,form=ImeiForm,fields= ['imei'],extra=1,can_delete=True)
const addNewRow = document.getElementById('add-more') const totalNewForms = document.getElementById('id_form-TOTAL_FORMS') addNewRow.addEventListener('click',add_new_row); function add_new_row(e){ if(e){ e.preventDefault(); } const currentFormClass = document.getElementsByClassName('child_forms_row') const countForms = currentFormClass.length const formCopyTarget = document.getElementById('form-lists') const empty_form = document.getElementById('empty-form').cloneNode(true); empty_form.setAttribute('class','child_forms_row') empty_form.setAttribute('id',`form-${countForms}`) const rgx = new RegExp('__prefix__','g') empty_form.innerHTML = empty_form.innerHTML.replace(rgx,countForms) totalNewForms.setAttribute('value',countForms 1) formCopyTarget.append(empty_form) const imeiBtn = document.getElementById('IMEIBTN') imeiBtn.setAttribute('id',`IMEIBTN-${countForms}`) $(`#IMEIBTN-${countForms}`).attr('data-target',`#IMEI${countForms}`) const my_modal = document.getElementById('IMEI0').cloneNode(true) my_modal.setAttribute('id',`IMEI${countForms}`) const main_modal = document.getElementsByClassName('allModal') main_modal.append(my_modal) }
lt;form action="" method="POST" id="create-collection"gt;{% csrf_token %} lt;/divgt; {{item_formset.management_form}} lt;div id="form-lists"gt; {% for mform in item_formset %} {{mform.id}} lt;div class="child_forms_row"gt; lt;div class="row no-gutters table-bordered"gt; lt;div class="col-md-3"gt; lt;div class="form-group"gt; {{mform.mobile | add_class:'form-control'}} lt;/divgt; lt;/divgt; lt;div class="col-md-1"gt; lt;div class="form-group"gt; {{mform.qnt}} lt;/divgt; lt;/divgt; lt;div class="col-md-1"gt; lt;div class="form-group"gt; {{mform.price}} lt;/divgt; lt;/divgt; lt;div class="col-md-1"gt; lt;div class="form-group row justify-content-center"gt; lt;button type="button" class="btn btn-info" name="" id="IMEIBTN-0" data-target="#IMEI0" data-toggle="modal"gt;IMEIlt;/buttongt; lt;/divgt; lt;/divgt; lt;/divgt; lt;/divgt; {% endfor %} lt;/divgt; lt;div id="empty-form" class="hidden"gt; lt;div class="row no-gutters table-bordered"gt; lt;div class="col-md-3"gt; lt;div class="form-group"gt; {{item_formset.empty_form.mobile | add_class:'form-control'}} lt;/divgt; lt;/divgt; lt;div class="col-md-1"gt; lt;div class="form-group"gt; {{item_formset.empty_form.qnt}} lt;div class="text-danger text-center" hiddengt;lt;/divgt; lt;/divgt; lt;/divgt; lt;div class="col-md-1"gt; lt;div class="form-group"gt; {{item_formset.empty_form.price}} lt;/divgt; lt;/divgt; lt;div class="col-md-1"gt; lt;div class="form-group row justify-content-center"gt; lt;button type="button" id="IMEIBTN" name="imei" class="btn btn-info" value="IMEI" data-target="#IMEI0" data-toggle="modal"gt;IMEIlt;/buttongt; lt;/divgt; lt;/divgt; lt;/divgt; lt;/divgt; lt;button type="button" class="btn btn-lg" id="add-more"gt;add new rowlt;/buttongt; lt;!-- /.row --gt; lt;div class="allModal"gt; lt;div id="IMEI0" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="my-modal-title" aria-hidden="true"gt; lt;div class="modal-dialog" role="document"gt; lt;div class="modal-content"gt; lt;div class="modal-header"gt; lt;h5 class="modal-title" id="my-modal-title"gt;IMEIlt;/h5gt; lt;p class="close" data-dismiss="modal" aria-label="Close"gt; lt;span aria-hidden="true"gt;amp;times;lt;/spangt; lt;/pgt; lt;/divgt; lt;div class="modal-body modal0"gt; {{imei_formset.management_form}} {% for imei in imei_formset %} lt;div class="row"gt; {{imei.imei | add_class:'form-control'}} lt;/divgt; {% endfor %} lt;/divgt; lt;/divgt; lt;/divgt; lt;/divgt; lt;/divgt; lt;div class="card-footer"gt; lt;div class="row justify-content-center"gt; lt;button type="submit" class="btn btn-lg btn-success"gt;savelt;/buttongt; lt;/divgt; lt;/divgt; lt;/formgt;
а также я не уверен , как написать jquery для imei_formset, если вы что-то знаете об этом, пожалуйста, дайте мне знать : я заплачу, если это потребуется