Unsupported operand type(s) for /: 'NoneType' and 'NoneType'


I am using Django 1.8.3 and Python 3.4.3

I know this has been answered many times, but none of the answers are specific to my situation and I am still learning Python, so I am having difficulty piecing a solution together to what is a common error.

I have a custom tag that applies division and float on two objects. This works as expected if the fields being divided don't have initial values of '0', which is what is producing a 'None' value.

What I am trying to accomplish is to filter out the None or ignore initial values of '0' and just return a simple string message or an integer of '0'.

def average(num1, num2):
    return round(float(num1 / num2), 2)

Here is a small snippet of one of my template fields and the tag that is performing the function.

    <td>{% average total_traffic.Q1 total_sales.Q1 %}</td>

And the error message:

Exception Type: TypeError
Exception Value:    
unsupported operand type(s) for /: 'NoneType' and 'NoneType'
Exception Location: /Users/charlessmith/Documents/Development/nfy/reportly/reportly/dashboard/templatetags/simple_tag.py in average, line 8

As always; thank you for your help.


Why not add an if statement which checks for '0' or None?

By : blasko

Just implement a simple type/value check for num1 and num2:

def average(num1, num2):
    if num1 and num2 and num1 != 0 and num2 != 0:
        return round(float(num1 / num2), 2)
    return 'Your error message'

This video can help you solving your question :)
By: admin