0

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.

TheSprinter
  • 338
  • 1
  • 12
  • 1
    You can follow this [link](https://stackoverflow.com/questions/17355888/saving-original-file-name-in-django-with-filefield) – Akash Joshi Oct 13 '20 at 10:44
  • @AkashJoshi If I understood correctly, this is basically doing something similar to the second possible solution I posted (creating a new model field) but renaming the file with `uuid`. Since I am okay not renaming the file myself, then I could just set my `original_filename` field in my `upload_to` function right when I enter it, correct? – TheSprinter Oct 13 '20 at 11:04
  • 1
    Yes perfect, as there are multiple ways to achieve that, this is one of them :) In this, you don't need to worry about the uploaded file name and appending `uuid`, just add a new field name and save that. – Akash Joshi Oct 13 '20 at 11:09

0 Answers0