15

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.

meepmeep
  • 3,018
  • 7
  • 33
  • 47
  • `myString` is not a string -- it's a `models.CharField`. Show us your actual view where you're trying to do this. – agf Aug 09 '11 at 11:12
  • 1
    so what does `print myString` or the equivalent show right before that `if` statement? You need to give us more info. – agf Aug 09 '11 at 11:46
  • turns out the above does work, but needed to restart apache to get the altered code to execute. Oops. – meepmeep Aug 09 '11 at 12:02

4 Answers4

18

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

if d: 
    #do something
else:
    #do something else
Srikar Appalaraju
  • 71,928
  • 54
  • 216
  • 264
13

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.
Heston Liebowitz
  • 1,625
  • 17
  • 12
3

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.

agf
  • 171,228
  • 44
  • 289
  • 238
1

In the case where your variable is either None or '' (blank), you can just handle both of the conditions as follows

if my_string:
  # neither None nor blank
thisshri
  • 632
  • 8
  • 18