How to check if whether a file has extension pdf or not?

Question:

I have a method for uploading files. And I want to check if the uploaded file is a pdf file.

So I try it like this:

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,
        })

But then I get this error:

TypeError at /

'UploadFile' object is not subscriptable

Question: what I have to change?

Asked By: mightycode Newton

||

Answers:

Use str.endswith() as stated by @TomMcLean in above comment, so:

At first, typecast file name into str then apply str.endswith() on it as the method only works on string type.

Attach following code in the view:

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')

Use it like this in the view:

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,
        })
Answered By: Sunderam Dubey