Django – Validator to check the emptyness of file field

The other day My Team had some problem in the validation of the file field, the requirement was simple, they had to check whether the file field is empty or not. The problem sounds somewhat simple. I said just go with a simple ‘if’ and that’s the end of the problem.

But they were unable to do that.. and finally I had to sit with them to solve the problem. It wasn’t that simple as I had realized. We are using a custom validator, which takes two argument- a ‘field_data’ and ‘all_data’. The ‘all_data’ is python dictionary which includes all the fields of the form.

The problem I faced was, non-availability of the file field in the ‘all_data’ dictionary. After fighting with the code, I found a solution. The code looks like this (I am pasting only custom validator code snippet):

Let’s assume that the file field name (model name ) is ‘pdfFile’. We can use python dictionary’s method called ‘has_key ‘. The output of the ‘has_key’ method is boolean. (True or False)

def validatorsName(field_data, all_data):
if all_data.has_key('pdfFile') and all_data['pdfFile'] != "" :
elif not all_data.has_key("pdfFile_file"):
raise validators.ValidationError("The pdf file field is empty")

Let me explain above python code (sorry about the indentation ). The first ‘if’ statement is to check whether the file field already has link or not. If the file field is not empty, ‘all_data’ dictionary includes one key called ‘pdfFile_file’ (‘pdfFile’ key includes the existing link and ‘pdfFile_file’ includes the currently entered link). If the second condition fails it means that the file field is empty.

Read More