[Fixed]-How to add pair value to an array and send to view in django without using ajax

1👍

If I understand your point, that is possible with Django formsets in combination with jquery (see here). I use it too.

An example from formsets:

forms.py

from django import forms
class ContactForm(forms.Form):
     name= forms.CharField()
     email= forms.EmailField()

views.py

def test(request):

    from django.forms import formset_factory
    ContactFormSet = formset_factory(ContactForm)
    if request.method == 'POST':
        formset = ContactFormSet(request.POST)
        if formset.is_valid():
            for form in formset:
                name = form.cleaned_data.get('name')
                email= form.cleaned_data.get('email')
                #do something with the input data
    return render(request, 'test/test.html', {'formset':ContactFormSet})

test.html (related to here):

<form action="{% url 'test:test' %}" method="post">
<h3>My test</h3>
{{ formset.management_form }}
{% for form in formset.forms %}
    <div class='table'>
    <table class='no_error'>
        {{ form.as_table }}
    </table>
    </div>
{% endfor %}
<input type="button" value="Add More" id="add_more">
</form>
<script>
    $('#add_more').click(function() {
        cloneMore('div.table:last', 'form');
    });
function cloneMore(selector, type) {
    var newElement = $(selector).clone(true);
    var total = $('#id_' + type + '-TOTAL_FORMS').val();
    newElement.find(':input').each(function() {
        var name = $(this).attr('name').replace('-' + (total-1) + '-','-' + total + '-');
        var id = 'id_' + name;
        $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked');
    });
    newElement.find('label').each(function() {
        var newFor = $(this).attr('for').replace('-' + (total-1) + '-','-' + total + '-');
        $(this).attr('for', newFor);
    });
    total++;
    $('#id_' + type + '-TOTAL_FORMS').val(total);
    $(selector).after(newElement);
}
</script>
👤trantu

Leave a comment