2

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?

John Smith
  • 843
  • 2
  • 9
  • 21
  • 3
    Possible duplicate of [What is the equivalent of "none" in django templates?](http://stackoverflow.com/questions/11945321/what-is-the-equivalent-of-none-in-django-templates) – Harrison Aug 23 '16 at 01:55
  • Try `if ({{person}} != "None")`. or you can use a Django `{% if %}` instead of a JavaScript one. – elethan Aug 23 '16 at 02:33
  • you cannot access django objects with client side javascript – e4c5 Aug 23 '16 at 06:15
  • Its not a Django object by the time it is being interpreted as JavaScript. Django templates are parsed on the server and the results sent to the browser. When the browser loads the page, the JavaScript gets run. You can test for the text the django object will output to html in the JavaScript code. – wobbily_col Aug 23 '16 at 20:58

2 Answers2

6

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 }})
}
wobbily_col
  • 11,390
  • 12
  • 62
  • 86
  • Actually, you will probably need to conditionally quote the output of {{person}}, or JavaScript will treat it as an undeclared variable. Personally I would define a model method on person (in Django) to return a quoted version of what {{ person }} would output to the template. {{ person.quoted_name }} or something similar. – wobbily_col Aug 24 '16 at 07:54
  • Can you please clarify what you mean by quoted version or provide an example? – John Smith Aug 24 '16 at 19:43
0

This worked for me:

{% if person != None %}
    var p = ...
    ...
{% endif %}
John Smith
  • 843
  • 2
  • 9
  • 21