Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django models.FileField - store only the file name not any paths or folder references

I'm using Django's Admin site to manage some data - but not building a webapp. I need the file upload field to store only the file name in the database.

Right now I can get absolute paths like: /Users/me/uploads/file.png

Or using the upload_to parameter get something like this in the database: uploads/file.png

How can I get it to be this: file.png

EDIT:

I'm taking the sqlite database and using in another client - so having any paths in the db entry doesn't make sense in my case.

Thanks!

like image 980
gngrwzrd Avatar asked Apr 04 '13 18:04

gngrwzrd


People also ask

Where does Django store files?

By default, Django stores files locally, using the MEDIA_ROOT and MEDIA_URL settings. The examples below assume that you're using these defaults. However, Django provides ways to write custom file storage systems that allow you to completely customize where and how Django stores files.


1 Answers

I would keep the FileField and use python os.path.basename to extract the filename.

This can be encapsulated with a property

class MyModel(models.Model):
   file = models.FileField(...)

   @property
   def filename(self):
       return os.path.basename(self.file.name)
like image 127
luc Avatar answered Sep 20 '22 05:09

luc