0

I have a model with Field like key = CharField(max_length=100, blank=True)

when i check for the value after form submission like this.

if self.key is None: the condition fails

But when i check for if self.key == '' it works.

My question is why it doesn't works when i evaluate it to None and works when i use ''.

The None condition works only when i assign the values like this. key = CharField(max_length=100, null=True ,blank=True)

I read some posts where it states that when evaluating the CharField as blank=True an empty string '' is saved but they didn't shed any light why it does that. because as far i understand it should save a Null value.

Vignesh Krishnan
  • 743
  • 8
  • 15
  • Because if you type: type(self.key) you will get 'NoneType' in first case and 'str' in the second case, NoneType != str even if str is empty – inmate_37 Jul 26 '18 at 06:29
  • I know that None !=str but my question is why it saves it as an empty string when blank=True is given to a Field? – Vignesh Krishnan Jul 26 '18 at 07:09
  • Because blank=True only prevents from cases when type is None and not str, even empty str – inmate_37 Jul 26 '18 at 07:10
  • Possible duplicate of [Is there a difference between \`==\` and \`is\` in Python?](https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is-in-python) – JPG Jul 26 '18 at 07:11
  • 1
    Also, you can clear your doubts here https://stackoverflow.com/questions/8609192/differentiate-null-true-blank-true-in-django – ans2human Jul 26 '18 at 07:33

1 Answers1

1
null = True

is about database which means you can have an object from your model that the value of field is null.

blank= True

is about django forms and means when you fill a modelForm of this model you can pass empty string and its not necessary to fill this field in your form.

So when you add null = True for the objects that have no value for key in the database key is null and in consequence if self.key is None works but when you remove this option for the objects in the database that have no value for key in database the key is '' so your condition is not True.

Milad Khodabandehloo
  • 1,907
  • 1
  • 14
  • 24