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

2

7

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!

Mayman answered 4/4, 2013 at 18:54 Comment(0)
K
4

The upload_to arg of the FileField can be a callable. see the docs

If you really need to only store the file name, I think you can do something like this. I did'nt try myself but I think it works.

def only_filename(instance, filename):
    return filename

class MyModel(models.Model):
    file = models.FileField(upload_to=only_filename)
Kavanaugh answered 5/4, 2013 at 5:44 Comment(0)
K
13

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)
Kavanaugh answered 4/4, 2013 at 19:6 Comment(3)
The os.path.basename is what you're looking for, but luc's answer here really encapsulates it in a very django/pythonesque way.Custard
This actually won't help - we're using the sqllite database in another client so I'd like any paths taken out completely.Mayman
I think it is more clear to post the edit into another answerKavanaugh
K
4

The upload_to arg of the FileField can be a callable. see the docs

If you really need to only store the file name, I think you can do something like this. I did'nt try myself but I think it works.

def only_filename(instance, filename):
    return filename

class MyModel(models.Model):
    file = models.FileField(upload_to=only_filename)
Kavanaugh answered 5/4, 2013 at 5:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.