John Smith John Smith - 1 month ago 7x
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

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

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

What seems to be the issue here?


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) {

edit :

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

if (john != null){

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

if ('john') != null){

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'" %

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

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