0

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?

2
  • Is your javascript in a separate .js file that is in static files or in the HTML page that is being rendered? Commented Dec 15, 2017 at 0:23
  • @StuartDines no it is not Commented Dec 15, 2017 at 0:24

1 Answer 1

1

You will need to create a date object in JS.

<script>
    var dt = new Date("{{ dt.isoformat }}");
</script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.