Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

upload multiple files in 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" />

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...