Question

I know how to mutiple file upload in djnago. I use:

<form enctype="multipart/form-data" action="" method="post">
    {% csrf_token %}
    <p>Press control to upload more than image at same time</p>
    <input type="file" name="myfiles" multiple>
    <input type="submit" name="upload" value="Upload">
</form>

but what I want is a single file upload, but permit user to click in a"+" button and automatic create a new file upload, permit user upload mutiple files. like attach a file in hotmail.

Was it helpful?

Solution

You're looking for a FormSet - a set of multiple forms, and some JavaScript to populate new forms.

https://docs.djangoproject.com/en/dev/topics/forms/formsets/

Here are some references to JS code that will help dynamically build the HTML for new forms:

Dynamically adding a form to a Django formset with Ajax


Setting up the formsets is easy (it's documented everywhere), but you might want help with the JS part:

I actually use a different method to dynamically add forms. I set up a hidden div with formset.empty_form which comes with easily replaceable __prefix__es in its attributes:

var form_count = {{ formset.total_form_count }};
$('#add_form').click(function() {
    var form = $("#empty_form").html().replace(/__prefix__/g, form_count);
    $('#forms').append(form);
    form_count++;
    $('#id_form-TOTAL_FORMS').val(form_count);
});


<div id="empty_form" style="display:none;">
    {{ formset.empty_form.as_p }}
</div>
<div id="add_form">Add another form</div>
<form id="forms">
    {{ formset.management_form }}
    {% for form in formset %}
        {{ form.as_p }}
    {% endfor %}
</form>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top