12

Problem Background I am new to django. I am trying to upload the file from client and save it. For this pupose i have created below model.

from django.db import models
class UploadFile(models.Model):
    uploadfile = models.FileField(upload_to='toProcess/')

I am using this model as below to save the file.

newfile = UploadFile(uploadfile = request.FILES['file'])
newfile.save()

It is saving file. But now I want to process saved file. In django, if the file with the same name alreday exists then it is adding some unique postfix to the original file name. I am happy with this approch and do not want to write a new method to create a unique filename.

Probelm- How to get the new unique name calculated by django for a file?

Mean If I will upload a same file two times say "abc.pdf" then it will save the first uploaded file as "abc.pdf" and second uploaded file as "abc_somesuffix.pdf". How to know what is the name of saved file?

Gaurav Pant
  • 4,029
  • 6
  • 31
  • 54

1 Answers1

15

As far as I know, the filename is stored in the name attribute of the model field, in your case

newfile.uploadfile.name

and the path of the file is stored in

newfile.uploadfile.path

Please see the official Django docs for further reference, as well as many other SO Q&A (e.g. this one)

In case you want to adopt your own format for the file name you can specify a callable in the upload_to parameter of the model field, as explained here

Community
  • 1
  • 1
Pynchia
  • 10,996
  • 5
  • 34
  • 43