'Empty CharField with null=True returns NoneType Django 1.8

As fas as I understand, this CharField must return null when it's not filled with data, but instead it returns None.

  number_of_likes = models.CharField(max_length=1000, blank=False, null=True)

The main issue for me is when I want to incriminate previous value, I get such sort of problem

int() argument must be a string, a bytes-like object or a number, not 'NoneType'

How should I handle it?

object.number_of_likes = previus_number_of_likes  + 1


Solution 1:[1]

As others have pointed out, null doesn't exist in python, None is the way to represent null values. That said, there are several ways you could address your issue:

Option 1: Change your field definition to:

 number_of_likes = models.IntegerField(default=0)

Option 2: If you don't want to change the field, you could:

 object.number_of_likes = int(object.number_of_likes) + 1 if object.number_of_likes else 1

Hope this helps

Solution 2:[2]

Just to check I did a python manage.py shell and typed

>>> null

and got:

NameError: name 'null' is not defined

I don't think there's a null, except when a None is stored into the database.

Solution 3:[3]

null may not have public availabilty but exists as a property when using models.Integerfield although Django docs has explicitly said that it is best to avoid using it with Charfield - https://docs.djangoproject.com/en/4.0/ref/models/fields/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 damores
Solution 2 pragman
Solution 3 SarathKumar95