问题
please someone can explain for me a bit more about formset with its template , all my formsets only save the last form a appreciate your helps
class Name(models.Model):
name = models.CharField(unique=True,max_length=50)
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
forms.py
class NameForm(ModelForm):
class Meta:
model = Name
fields = '__all__'
NameFormSet = modelformset_factory(Name,form=NameForm,extra=1,max_num=10)
my template
<button class="btn-block mt-1 border-left border-right shadow-lg" id="add_more">+</button>
<div class="dup col-12" style="border-top:1px solid white;border-radius: 30px;">
<form method="POST">{% csrf_token %}
{{formset.management_form}}
<div class="row mx-auto p-2" class="div1">
<div class="input-group inp mx-auto col-12 col-sm-10 p-1 col-md-5 div2 dynamic-form">
{% for form in formset.forms %}
{{form.name | add_class:'col-12' | attr:'id:add'}}
{% if form.name.errors %}
<div class="text-center text-light bold">{{form.name.errors}}</div>
{% endif %}
{% endfor %}
</div>
</div>
<div class="col-12 col-sm-7 col-md-3 mx-auto">
<button class="s btn-block mt-1 border-left border-right shadow-lg">insert</button>
</div>
</form>
<script>
$('#add_more').click(function() {
cloneMore('.dynamic-form:last', 'add');
});
</script>
<script>
function cloneMore(selector, type) {
var newElement = $(selector).clone(true);
var total = $('#add_' + type + '-TOTAL_FORMS').val();
newElement.find(':input').each(function() {
var name = $(this).attr('name').replace('-' + (total-1) + '-','-' + total + '-');
var id = 'add_' + name;
$(this).attr({'name': name, 'add': id}).val('').removeAttr('checked');
});
newElement.find('label').each(function() {
var newFor = $(this).attr('for').replace('-' + (total-1) + '-','-' + total + '-');
$(this).attr('for', newFor);
});
total++;
$('#add_' + type + '-TOTAL_FORMS').val(total);
$(selector).after(newElement);
}
</script>
someone explain please , and why my forms only save the last one!? i much appreciate your helps ..
来源:https://stackoverflow.com/questions/62299126/django-formset