A
A
Andrew Electis2018-06-09 09:07:26
Django
Andrew Electis, 2018-06-09 09:07:26

How to implement multiple file upload from a form in Django?

I need a minimal form with the ability to upload several files at a time, then I will save it in the model in the view.
Can you please tell me what to write in forms, views and template?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew Electis, 2018-06-09
@electis

class LoadNewForm(forms.Form):
    file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

def load_new(request):
    if request.method == "POST":
        newtrack = forms.LoadNewForm(request.POST, request.FILES)
        if newtrack.is_valid():
            files = newtrack.files.getlist('file')
            for f in files:
                print(f.name)
            data = {"header" : "Успешно загружены",}
        else:
            data = {"header" : "Ошибка проверки формы",}
    else:
        data = {
            "header"    : "Загрузить файлы",
            "form"      : forms.LoadNewForm(),}
    return render(request, "load_new.html", context=data)

{% if form %}
        <form method="POST" enctype="multipart/form-data">
            <div class="form-group">
            {% csrf_token %}
            {{ form }}
            <input class="btn btn-primary" type="submit" value="Send" >
            </div>
        </form>
    {% endif %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question