Johnny Metz
Johnny Metz

Reputation: 6055

parse python datetime object in javascript within django app

I'm passing the following variable to a template:

from django.utils import timezone
dt = timezone.now()
print(type(dt))  # <class 'datetime.datetime'>

Everything works fine if I use it in my HTML directly:

{{ dt | date:'D d M Y' }}

which renders to Thu 14 Dec 2017.

However when I try to access the variable in my javascript I get an error:

<script>
  {{ dt | safe }}
</script>

Uncaught SyntaxError: missing ) after argument list

Furthermore, I get a slightly different error when I try to render a list of datetime objects:

dt_list = [timezone.now() for _ in range(3)]

and within my js:

<script>
  console.log({{ dt_list | safe }})
</script>

Uncaught SyntaxError: Unexpected token <

So my question is how can I convert a python datetime object to something I can use in JS?

Upvotes: 0

Views: 218

Answers (1)

Stuart Dines
Stuart Dines

Reputation: 758

You will need to create a date object in JS.

<script>
    var dt = new Date("{{ dt.isoformat }}");
</script>

Upvotes: 1

Related Questions