Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

upload multiple files in django

Tags:

django

I am new to django, I am trying to upload more than one file from the browser and store them somewhere in computer storage but I am not storing them successfully with this code please help me out to find my mistake or improvements that I can do. Thanks in advance to help.

views.py

    from django.shortcuts import render
    from django.http import HttpResponse
    # Create your views here.

    def Form(request):
        return render(request, "index/form.html", {})

    def Upload(request):
        for count, x in enumerate(request.FILES.getlist("files")):
            def process(f):
                with open('/Users/benq/djangogirls/upload/media/file_' + str(count), 'wb+') as destination:
                    for chunk in f.chunks():
                        destination.write(chunk) 
            process(x)
        return HttpResponse("File(s) uploaded!")

app/urls.py

from django.conf.urls import url
from index import views

urlpatterns = [
    url(r'^form/$', views.Form),
    url(r'^upload/$', views.Upload)
]

form.html

<form method="post" action="../upload/" entype="multipart/form-data"> {% csrf_token %}
<input type="file" name="files" multiple />
<input type="submit" value="Upload" />

like image 210
Amandeep Dhiman Avatar asked Sep 16 '16 06:09

Amandeep Dhiman


People also ask

How do I import files into Django?

Django provides built-in library and methods that help to upload a file to the server. The forms. FileField() method is used to create a file input and submit the file to the server. While working with files, make sure the HTML form tag contains enctype="multipart/form-data" property.

What is FileField in Django?

FileField is a file-upload field. Before uploading files, one needs to specify a lot of settings so that file is securely saved and can be retrieved in a convenient manner. The default form widget for this field is a ClearableFileInput.

What is SimpleUploadedFile?

class SimpleUploadedFile(InMemoryUploadedFile): """ A simple representation of a file, which just has content, size, and a name. """ def __init__(self, name, content, content_type="text/plain"): content = content or b"" super().


1 Answers

my model to save Document

class Document(models.Model):
  file = models.FileField('Document', upload_to='mydocs/')

  @property
  def filename(self):
     name = self.file.name.split("/")[1].replace('_',' ').replace('-',' ')
     return name
  def get_absolute_url(self):
     return reverse('myapp:document-detail', kwargs={'pk': self.pk})

you can try a django create view in my code i use this DocumentCreateView

class DocumentCreate(CreateView):
   model = Document
   fields = ['file']

   def form_valid(self, form):
     obj = form.save(commit=False)
     if self.request.FILES:
        for f in self.request.FILES.getlist('file'):
            obj = self.model.objects.create(file=f)

   return super(DocumentCreate, self).form_valid(form)

my form html file

<script>
  $(document).ready(function(){
    $('#id_file').attr("multiple","true");

  })
 </script>
<form method="post" enctype="multipart/form-data" action="">{% csrf_token %}
 {{ form.file }}
 <input type="submit" value="upload" />

</form>
like image 60
Dimitris Kougioumtzis Avatar answered Nov 09 '22 15:11

Dimitris Kougioumtzis