Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

Getting Django model name of uploaded file

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'
question from:https://stackoverflow.com/questions/65897853/getting-django-model-name-of-uploaded-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...