django how to upload folder

11,340

There is newer topic which asks the same question and I have tried to answer:

Django directory upload get sub-directory names

Basically it is the default behavior of Django if you want to have different behavior you need to write your own upload handlers

Share:
11,340
Tengerye
Author by

Tengerye

Research engineer at ByteDance.

Updated on June 22, 2022

Comments

  • Tengerye
    Tengerye almost 2 years

    I know how to upload multiple files through django, but I have a problem when uploading a folder if there are subfolders in it. The django can't receive subfolders. I found the reason, because browser use '.' to represent a folder, but django can't parse it then stop parsing. Is there an elegant way to fix it?

    python code:

    def uploader_single(request):
        data = {}
        if request.method == 'POST':
            if True:
                for afile in request.FILES.getlist('file'):
                    new_file = UploadFileSingle(file = afile)
                    new_file.save()
    
                return HttpResponseRedirect('')
            else:
                print "form is not valid"
                return HttpResponseRedirect('')
        else:
            print 'not post'
    

    Python code:

    class UploadFileSingle(models.Model):
        file        = models.FileField(upload_to='files/%Y/%m/%d', models.FilePath)
        uploaded_at = models.DateTimeField(auto_now_add=True)
        models.FilePathField.recursive = True
        models.FilePathField.allow_folders = True
        updated_at  = models.DateTimeField(auto_now=True)
    
        def some_folder = FilePathField(path='some_path', recursive=True, allow_files=True, allow_folders=True,)'
    

    HTML code:

    <input type="file" name="file" multiple = "true" webkitdirectory="true" directory = "true"/>
    
  • Tengerye
    Tengerye over 10 years
    Thank you very much. But could you please explain how could I exactly apply filter on my case? Thank you.
  • Tengerye
    Tengerye about 10 years
    django filter can not do that. My conclusion is django can't do it yet.
  • Gagik Sukiasyan
    Gagik Sukiasyan over 7 years
    Nothing to do with the question
  • Stack
    Stack over 3 years
    It's much more recomended to write your own upload handlers