Home > other >  How to I get the path to a file with Django?
How to I get the path to a file with Django?

Time:06-14

I am currently using Django's forms to create a FileField that allows the user to upload a file. However, after I select the file, it creates an object of type django.core.files.uploadedfile.InMemoryUploadedFile, which is a copy of the original file.

How would I go about to get the original path of this file so I can either modify or replace it?

# forms.py

class UploadFile(forms.Form):
    file = forms.FileField(label="Select File: ", required=True)
# views.py

def get_path(response):
    context = {}

    if response.method == "POST":
        form = UploadFile(response.FILES)

        if form.is_valid():
            file = form.cleaned_data["file"]
            # Is there a  way to get the original file path or should I just not use FileField?
            print("The File Path Here")

CodePudding user response:

temporary_file_path function

if form.is_valid():
    file = form.cleaned_data["file"]
    print(file.temporary_file_path())

CodePudding user response:

Not sure why you'd want to try modifying an InMemoryUploadedFile file path. However, just keep in mind the term "InMemory".

The file has not been saved as yet, so there will be no path associated with the file before saving. To my knowledge (I stand corrected if I'm wrong here), InMemoryUploadedFile do not have a path attribute either, but content/file, a filename, etc.; in which the filename can be modified. You can see the doc here.

You could make modifications to the filename though if you wish by doing the following:

if form.is_valid():
     form.cleaned_data["file"].name = "modify.txt"  # or to whatever filename and extension you want.
     form.save()  # If you have a save method defined
     

However, you could get a little creative in saving the file to a specific path within the media folder though. For example:

# forms.py

import os
from django.conf import settings

class UploadFile(forms.Form):
     file = forms.FileField(label="Select File: ", required=True)

     # The save method that will save the file to a specific location in the media folder.
     def save(self):  
          filename = file.name
          folder = 'uploaded/'
    
          # Create the folder if it doesn't exist.
          try:
               os.mkdir(os.path.join(settings.MEDIA_ROOT, folder))
          except:
               pass

          # Save the uploaded file inside that folder.
          file_path = os.path.join(settings.MEDIA_ROOT, folder, filename)
    
          with open(file_path, 'wb ') as destination:  
               for chunk in file.chunks():
                    destination.write(chunk)

# view.py

def get_path(response):
     if response.method == "POST":
          form = UploadFile(response.FILES)

          if form.is_valid():
               file = form.cleaned_data["file"]
               # file.name = "modify.txt"  # Can modify here if necessary...
               
               form.save()

               
  • Related