134đź‘Ť
request.FILES['filename'].name
From the request
documentation.
If you don’t know the key, you can iterate over the files:
for filename, file in request.FILES.iteritems():
name = request.FILES[filename].name
79đź‘Ť
file = request.FILES['filename']
file.name # Gives name
file.content_type # Gives Content type text/html etc
file.size # Gives file's size in byte
file.read() # Reads file
- [Django]-Django syncdb and an updated model
- [Django]-Django – what is the difference between render(), render_to_response() and direct_to_template()?
- [Django]-How to repeat a "block" in a django template
22đź‘Ť
NOTE if you are using python 3.x:
request.FILES
is a multivalue dictionary like object that keeps the files uploaded through an upload file button. Say in your html code the name of the button (type=”file”) is “myfile” so “myfile” will be the key in this dictionary. If you uploaded one file, then the value for this key will be only one and if you uploaded multiple files, then you will have multiple values for that specific key. If you use request.FILES['myfile']
you will get the first or last value (I cannot say for sure). This is fine if you only uploaded one file, but if you want to get all files you should do this:
list=[] #myfile is the key of a multi value dictionary, values are the uploaded files
for f in request.FILES.getlist('myfile'): #myfile is the name of your html file button
filename = f.name
list.append(filename)
of course one can squeeze the whole thing in one line, but this is easy to understand
- [Django]-How about having a SingletonModel in Django?
- [Django]-How to get the domain name of my site within a Django template?
- [Django]-Django + Ajax
7đź‘Ť
The answer may be outdated, since there is a name
property on the UploadedFile
class. See: Uploaded Files and Upload Handlers (Django docs). So, if you bind your form with a FileField
correctly, the access should be as easy as:
if form.is_valid():
form.cleaned_data['my_file'].name
- [Django]-How to reset Django admin password?
- [Django]-Inject errors into already validated form?
- [Django]-Readonly models in Django admin interface?
5đź‘Ť
Worked for me on Python 3.8, Django 3.2
print(request.FILES.items())
for filename, file in request.FILES.items():
print(filename, file)
request.FILES.iteritems()
was throwing AttributeError
for me.
- [Django]-How to get the current language in Django?
- [Django]-How do I convert a Django QuerySet into list of dicts?
- [Django]-Location of Django logs and errors