S
S
SHADRIN2020-06-24 21:46:50
Django
SHADRIN, 2020-06-24 21:46:50

How to upload multiple Django files?

views.py

from django.views.generic.edit import FormView
from .forms import UploadForm
from .models import Attachment

class UploadView(FormView):
    template_name = 'form.html'
    form_class = UploadForm
    success_url = '/done/'

    def form_valid(self, form):
        for each in form.cleaned_data['attachments']:
            Attachment.objects.create(file=each)
        return super(UploadView, self).form_valid(form)


models.py
from django.db import models

class Attachment(models.Model):
    file = models.FileField(upload_to='')


forms.py
from django import forms
from multiupload.fields import MultiFileField

class UploadForm(forms.Form):
    attachments = MultiFileField(min_num=1)


upload.html
{% extends 'mainpage/homepage.html' %}

{% load static %}

{% block content %}
  <form enctype="multipart/form-data" method="post">
    {% csrf_token %}
    <input type="file" name="myfiles" multiple>
    <button type="submit">Upload</button>
  </form>

  {% if uploaded_file_url %}
    <p>File uploaded at: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p>
  {% endif %}

  <p><a href="">Return to home</a></p>
{% endblock %}


How to pass a list of uploaded files to views.py, all the docks just throw an example, but I don’t understand how to connect it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-06-25
@shadrin_ss

SHADRIN here is a link to the documentation Uploading multiple files . Specifically, in your case, you need to change the form field as follows

attachments = models.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))

this is the first, and the second field in your template is generally called differently, it should be like this
<form enctype="multipart/form-data" method="post">
    {% csrf_token %}
    {{ form.attachments }}
    <button type="submit">Upload</button>
</form>

Whether you're probably using an Ajax loading library is another matter. As I understood speech about normal POST request.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question