django - formset

故事扮演 提交于 2020-06-23 14:16:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!