[Fixed]-Testing for empty/null string in django

18đź‘Ť

âś…

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

if d: 
    #do something
else:
    #do something else

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.

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

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

Leave a comment