1

I am creating a website in which the user uploaded a zip file. This zip file is the unzipped, saved inside my project folder. Then I want to retrieve these files and saved it into my Model.

I managed to unzip the file in a folder inside my DJango project but now I do not know how to pass them into my views so that they can be saved in the Models.

views.py

def homeupload(request):
    if request.method == "POST":
        my_entity = Uploading()
        my_zip_file = request.FILES["my_uploads"]
        with zipfile.ZipFile(my_zip_file, 'r') as zip_ref:
            zip_ref.extractall('media/documents/')
        my_entity.my_uploads = "RETRIEVE THE UNZIPPED FILE FOLDER FROM media/documents/"
        my_entity.save()
        messages.success(request, "File uploaded correctly")
        return redirect('homeupload')
    return render(request, 'uploadings/homeupload.html')

models.py

class Uploading(models.Model):
    my_uploads = models.FileField(upload_to="documents/")
Magofoco
  • 5,098
  • 6
  • 35
  • 77
  • You can only save **one** file in one instance of `Uploading`. So you want to cycle through the files in the folder and create one instance of your model for each file? – dirkgroten Oct 09 '19 at 14:19
  • The unzipped file create a folder. Can't I upload the folder? If not, yes, I will have to iterate. However, now I am missing how I can get the file from the media/documents path – Magofoco Oct 09 '19 at 14:23
  • the whole thing gets extracted into /documents/ so if it has a directory structure, that whole directory structure will appear inside /documents/. Make sure there's nothing else in /documents/ (or add a new sub-directory to be sure) and then you can `os.walk()` through the directory (https://stackoverflow.com/questions/19587118/iterating-through-directories-with-python) – dirkgroten Oct 09 '19 at 14:27
  • I thought that `os.walk()` give me the location of the directory or file not the content of it. In other words, it return the path in string not the bytes. I am going to try. – Magofoco Oct 09 '19 at 14:28
  • It returns you the paths for each file, then of course you'll need to open each file and assign it to your model. – dirkgroten Oct 09 '19 at 14:31
  • Thanks. However this will return me the bytes of the file, not the file itself. If I unzip a folder containing the pdf, this pdf is saved inside `media/documents`. Then I can find its path and `.read()` it. This return me bytes that I can save in my model BUT, this does not save it as `.pdf`. I get the content of it, not the content in the file extensions. – Magofoco Oct 09 '19 at 15:34
  • https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.fields.files.FieldFile.save – dirkgroten Oct 09 '19 at 15:38

0 Answers0