[Answer]-How can i perform validation on uploaded file in django

1👍

The example below is based on the Basic file uploads example in the django docs. You can have a function in this example called check_pdf that does your validation on the pdf file and returns true/false based on whether it is valid. Depending on that you redirect the user to a success or invalid pdf page. This is the simplest way of doing it. You could do more and present specific error messages using the forms apis.

from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            if check_pdf(request.FILES['file'].name):
                return HttpResponseRedirect('/success/url/')
            else:
                return HttpResponseRedirect('/invalid_pdf/url/')
    else:
        form = UploadFileForm()
    return render_to_response('upload.html', {'form': form})

Leave a comment