Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get uploaded file name in django

Tags:

python

django

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?

like image 405
Gaurav Pant Avatar asked Jan 03 '16 09:01

Gaurav Pant


People also ask

How do I find the path of an uploaded file in Python?

In order to obtain the Current Working Directory in Python, use the os. getcwd() method. This function of the Python OS module returns the string containing the absolute path to the current working directory.

What is request files in Django?

A view handling this form will receive the file data in request. FILES , which is a dictionary containing a key for each FileField (or ImageField , or other FileField subclass) in the form. So the data from the above form would be accessible as request. FILES['file'] . Note that request.


1 Answers

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

like image 171
Pynchia Avatar answered Sep 23 '22 02:09

Pynchia