Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

testing for empty/null string in django

I have a charfield with the following:

myString = models.CharField(max_length=50,null=True,blank=True)

In many of my objects, this particular string is often left blank, when created through the django admin interface. In MySQL, the column is VARCHAR(50) with default=NULL.

Whatever test I try to do in my views.py to detect blank values, always seems to evaluate to false whether the entry is blank or not:

myString is None
myString==""
len(myString)==0

How can I discriminate between blank and non-blank values for this field?

Thanks

EDIT:

Actual view is the following, I want to execute a block only if this field is not blank.

if myObject.myString:
     #do something

the block always executes, and I have tried all the above examples of testing for a blank field.

EDIT 2:

Scratch that, if myObject.myString: does indeed work.

like image 404
meepmeep Avatar asked Aug 09 '11 10:08

meepmeep


People also ask

Is empty string Django?

The Django convention is to use the empty string, not NULL. The default values of null and blank are False. Also there is a special case, when you need to accept NULL values for a BooleanField , use NullBooleanField instead.

How do I check if a field is empty in Django?

if not form. data['first_name']: checks for None or '' an empty string or False come to that.

What is NULL and blank in Django?

null = True. Means there is no constraint of database for the field to be filled, so you can have an object with null value for the filled that has this option. blank = True. Means there is no constraint of validation in django forms.

Is empty string nil?

nil? will only return true if the object itself is nil. That means that an empty string is NOT nil and an empty array is NOT nil.


3 Answers

if your d is either None or "" then simply check -

if d: 
    #do something
else:
    #do something else
like image 65
Srikar Appalaraju Avatar answered Oct 04 '22 00:10

Srikar Appalaraju


Some empty fields return empty strings while others return None. A nullable boolean field however, will return False when it has been set. This will not pass the test in Srikar's answer. A more robust solution is this:

if d in [None, '']:
    # This field is empty.
like image 23
Heston Liebowitz Avatar answered Oct 02 '22 00:10

Heston Liebowitz


myString is not a string -- it's a models.CharField. Show us your actual view where you're trying to do this.

If you've already got an instance of your model, you should just be able to do

if model_instance.myString:

to test if it's not blank.

like image 45
agf Avatar answered Oct 04 '22 00:10

agf