Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if django form data is None, ' ' (empty string), or False

if form.data['first_name'] is None:
    return True
else: 
   return False  

I'm trying to check if this first_name field is blank or "None". But if the field happens to be blank the following will return ( u'' ) along with false. Any other solution for determining if this specific form field is blank or none? And why this happens?

like image 269
Dap Avatar asked Nov 05 '13 16:11

Dap


People also ask

Is none in Django template?

first_name is None %} causes syntax error in Django template. Your hint mixes presentation and logic by putting HTML in your model, doing exactly the opposite of what you are trying to teach.

Is NULL true Django?

If a string-based field has null=True , that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it's redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL.

What is difference between NULL and blank in Django?

In Very simple words, Blank is different than null. null is purely database-related, whereas blank is validation-related(required in form). If null=True , Django will store empty values as NULL in the database . If a field has blank=True , form validation will allow entry of an empty value .


1 Answers

The problem is that by checking for:

 if form.data['first_name'] is None:

you only check if the value is None, whereas:

if not form.data['first_name']:

checks for None or '' an empty string or False come to that.

What you could also do is:

return bool(form.data.get('first_name', False))

In this case if form.data['first_name'] is not present it will return False, if the value is None or '' this will also return False, if the value is True or 'a string' it will return True.

like image 163
Matt Seymour Avatar answered Sep 28 '22 18:09

Matt Seymour