Skip to content

Instantly share code, notes, and snippets.

@cb109
Created September 1, 2023 10:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cb109/4039770a33ead38fb77789c107dd080f to your computer and use it in GitHub Desktop.
Save cb109/4039770a33ead38fb77789c107dd080f to your computer and use it in GitHub Desktop.
Django FileField / File .path VS .name
# 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