John Smith John Smith - 2 months ago 13
Javascript Question

How to check if Django object is None in javascript?

How do you check if a Django object is None in js?

I currently have a variable

person
that stores a Django object or None. In my js I have:

if ({{person}} != None) {
execute_function({{person}})
}


What seems to be the issue here?

Answer

John Smiths answer makes the most sense, check it in Django's templates. Actually better would be:

{% if person %}
    execute function
{% endif%}

If you need to check it using JavaScript, JavaScript uses null instead of None, so assuming that the JavaScript code is also in the Django html template (and not loaded as an external file) this should work.

if ({{person}} != null) {
    execute_function({{person}})
}

edit :

adding a bit more detail: That will probably be parsed to something like:

if (john != null){
    execute_function(john)
}

JavaScipt won't understand john , but it will understand the quoted version 'john' :

if ('john') != null){
    execute_function('john')
}

The easiest way to achieve this would be to add a model method to the Person model.

Class Person(models.Model):
    ...field definitions here.

    def quoted_name(self):
        return "'%s'" % self.name

Then in the template (and empty string evaluates to false):

if ({{person.quoted_name }}) {
    execute_function({{person.quoted_name }})
}
Comments