3
I have a code on Django
where I want to upload a file from a form.
At a given precise moment check if the index exists "arquivo"
within the variable request.FILES
I did it using the method has_key
as follows (do not notice if the code is ugly, because I am a beginner in the python
):
import os
def upload(request):
data = {}
if request.method == 'POST':
if request.FILES.has_key('arquivo'):
files = request.FILES['arquivo']
path = 'upload'
if not os.path.exists(path):
os.makedirs(path)
upload_path = path + '/' + files.name;
with open(upload_path, 'w') as upload:
upload.write(files.read())
data["teste"] = "dados enviados"
else:
data["teste"] = "arquivo não preenchido"
else:
data["teste"] = "não enviado"
return render(request, 'upload.html', data)
However, rather than checking whether a specific index exists, I would like to know what is the best way to check whether request.FILES
is empty.
I had devised two ways to try to do this:
1) example:
if request.FILES:
#faça alguma coisa
2) example:
if len(request.FILES) is not 0:
#faça alguma coisa
But I don’t know if this is appropriate. I’m learning the language now and I don’t want to start by sniffing.
That is: Is there any better way to check whether request.FILES
is empty?
if request.FILES:
, simply. It is not wrong to do otherwise, although his second example shouldn’t wearis not
, and yes!=
.– mgibsonbr