0

I have a django model and I want to access its name. I am using objects.get with id set to 1 because I know that there is only one file that has currently been uploaded to excel_upload class. below is how i go that path for the file.

However I a looking to try and access the name of the file. by name i mean the the string associated with the file. I know i can go into the admin panel and just click on excel_upload -> my_excel_file and then see the name. but I am looking for a way to access it in code.

the_uploaded_excel_file = excel_upload.objects.get(id=1)
excel_file_path_from_db = the_uploaded_excel_file.my_excel_file.path
print(excel_file_path_from_db)

my model looks like this:

class excel_upload(models.Model):
    my_excel_file = models.FileField()
    def __str__(self):
        return self.my_excel_file.name[:50]

When i do:

print(excel_upload.my_excel_file)

i get <django.db.models.fields.files.FileDescriptor object at 0x7fd730faa340>

and then when i try to access the name by doing:

print(excel_upload.my_excel_file.name)

i then get:

    print(excel_upload.my_excel_file.name)
AttributeError: 'FileDescriptor' object has no attribute 'name'
kitchen800
  • 197
  • 1
  • 12
  • 36
  • You can access the filename using `.name`, see https://stackoverflow.com/a/34575210/4151233 – Marco Jan 26 '21 at 13:23
  • i got an error that says: print(excel_upload.my_excel_file.name) AttributeError: 'FileDescriptor' object has no attribute 'name' – kitchen800 Jan 26 '21 at 15:46
  • Not sure what `excel_upload.my_excel_file.name` is. But you should call `.name` on a specific Model object. E.g. `the_uploaded_excel_file.my_excel_file.name` – Marco Jan 26 '21 at 17:01
  • hi @Marco i have updated the question to show you the errors that keep coming up. – kitchen800 Jan 26 '21 at 21:35
  • 1
    You have to grab this name from an object not from the class model. So first retrieve an object `the_uploaded_excel_file = excel_upload.objects.get(id=1)` and then `print(the_uploaded_excel_file.my_excel_file.name)`. Please also read [Class Names](https://www.python.org/dev/peps/pep-0008/#class-names) in the Style Guide for Python Code. – Marco Jan 26 '21 at 21:53
  • @Marco thanks i really appreciate it :) – kitchen800 Jan 26 '21 at 22:17

0 Answers0