Как проверить, имеет ли файл расширение pdf
У меня есть метод для загрузки файлов. И я хочу проверить, является ли загруженный файл файлом pdf.
Поэтому я пробую следующим образом:
def post(self, request):
submitted_form = ProfileForm(request.POST, request.FILES)
content = ''
if submitted_form.is_valid():
uploadfile = UploadFile(image=request.FILES["upload_file"])
file_extension = os.path.splitext(uploadfile[1])
if file_extension in {'pdf'}:
print('Is pdf')
uploadfile.save()
with open(os.path.join(settings.MEDIA_ROOT,
f"{uploadfile.image}"), 'r') as f:
content = f.read()
print(content)
return render(request, "main/create_profile.html", {
'form': ProfileForm(),
"content": content
})
return render(request, "main/create_profile.html", {
"form": submitted_form,
})
Но затем я получаю эту ошибку:
TypeError at /
'UploadFile' object is not subscriptable
Вопрос: что я должен изменить?
Спасибо
Используйте str.endswith()
как указано @TomMcLean в комментарии выше, так:
Сначала введите имя файла в str
, затем примените к нему str.endswith()
, поскольку метод работает только со строковым типом.
Вставьте следующий код в представление:
name_of_file = str(request.FILES['upload_file'])
print("Now its type is ", type(name_of_file))
if name_of_file.endswith('.pdf'):
print('It is .pdf')
else:
print('It is .txt')
Используйте его следующим образом в представлении:
class CreateProfileView(View):
def get(self, request):
form = ProfileForm()
return render(request, "home/create_profile.html", {
"form": form
})
def post(self, request):
submitted_form = ProfileForm(request.POST, request.FILES)
content = ''
if submitted_form.is_valid():
uploadfile = UploadFile(image=request.FILES["upload_file"])
name_of_file = str(request.FILES['upload_file'])
print("Now its type is ", type(name_of_file))
if name_of_file.endswith('.pdf'):
print('It is .pdf')
else:
print('It is .txt')
uploadfile.save()
with open(os.path.join(settings.MEDIA_ROOT,
f"{uploadfile.image}"), 'r') as f:
content = f.read()
print(content)
return render(request, "home/create_profile.html", {
'form': ProfileForm(),
"content": content
})
return render(request, "home/create_profile.html", {
"form": submitted_form,
})