upload multiple files in django

前端 未结 4 1937
忘了有多久
忘了有多久 2020-12-18 09:33

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 c

相关标签:
4条回答
  • 2020-12-18 10:05

    I was able to solve the multi uploads portion in the create view here: Django Class based UpdateView with Form for Multiple Uploaded Files , however, now the update get function is what I am currently stuck on.

    0 讨论(0)
  • 2020-12-18 10:19

    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>
    
    0 讨论(0)
  • 2020-12-18 10:23

    Answer from official django documentation

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

    https://docs.djangoproject.com/en/3.0/topics/http/file-uploads/#uploading-multiple-files

    0 讨论(0)
  • 2020-12-18 10:25

    views.py

    from django.shortcuts import render
    from django.http import HttpResponse
    # Create your views here.
    
    def Form(request):
        for x in request.FILES.getlist("files"):
            def process(f):
                with open('/Users/benq/djangogirls/upload/media/file_' + str(x), 'wb+') as destination:
                    for chunk in f.chunks():
                        destination.write(chunk) 
            process(x)
        return render(request, "index/form.html", {})
    

    urls.py

    from django.conf.urls import url
    from index import views
    
    urlpatterns = [
        url('form', views.Form),
    ]
    

    worked for me.

    0 讨论(0)
提交回复
热议问题