I want to show the exact filename of a user-uploaded file in a page, but I haven't found a sort of out-of-the-box way to do it, and I'd like to know if it exists or what could be a better way to do it.
1.- I can't split a string with Django's template language. I found there is a truncatechars
filter, but that won't work for me because filenames have different lengths and, if they get truncated, I get an ellipsis at the end.
2.- In the only answer to this question, the user says FileField
objects have a filename
attribute. However, there is no filename
attribute defined here or here and, actually, if I do the same ModelObject.field_name.filename
, I get AttributeError: 'FieldFile' object has no attribute 'filename'
.
Possible solutions I have found:
I see I can define a custom template filter that can do
string.split('/')[-1]
, but I'm not sure if that's kind of an overkill for this. Also, note that, if this method is used, I could end up showing the user a different filename in the case in which they uploaded a file with the same name of an existing file in their user directory inside the media directory, because Django will have renamed it. This is not what I want ideally. I can find ways to ensure the user does not do this, but I'm looking for a way that avoids it in itself.I have also thought about creating a new model field just to store the filename gotten from
UploadedFile.name
, but again, I'd like to know about a better way.
I think it's possible I'm missing something here, but I haven't found it.