Created
September 1, 2023 10:53
-
-
Save cb109/4039770a33ead38fb77789c107dd080f to your computer and use it in GitHub Desktop.
Django FileField / File .path VS .name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Django's models.FileField stores FieldFile objects. These have both .name | |
# and .path attributes, which however are not exactly intuitive: | |
my_instance.my_filefield.name | |
# E.g. whatever/123/foo.png | |
# Returns the path relative to MEDIA_ROOT, not the filename! | |
# For the filename do e.g. os.path.basename(my_instance.my_filefield.name) | |
my_instance.my_filefield.path | |
# E.g. /var/www/media/whatever/123/foo.png | |
# Returns the absolute filepath! | |
# When populating a model instance's FileField attribute, make sure pass | |
# either a File() or ContentFile() object directly, or alternatively, a | |
# filepath that is relative to MEDIA_ROOT, like above. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment