Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django date to javascript at the template

What would be the easy way of achieving such below? selected_date comes from django context as a python date :

<script type="text/javascript">
    var selected_year = {{ selected_date|date:"Y" }}
    var selected_month = {{ selected_date|date:"m" }} - 1;
    var selected_day = {{ selected_date|date:"d"}}
    var selected_date = new Date(selected_year, selected_month, selected_day);
    alert(selected_date);
</script>
like image 778
Hellnar Avatar asked Feb 22 '11 09:02

Hellnar


People also ask

Can I use JavaScript in Django template?

Adding JavaScript to Our Django TemplateWe can add JavaScript to our template using an inline <script> tag or an external JavaScript file. Let's create a app. js file, put it in a js folder that you need to create in the static folder of your application.

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What is Forloop counter in Django?

A for loop is used for iterating over a sequence, like looping over items in an array, a list, or a dictionary.

What are template tags in Django?

The template tags are a way of telling Django that here comes something else than plain HTML. The template tags allows us to to do some programming on the server before sending HTML to the client.


2 Answers

I've had a lot of success with the isoformat function in python:

var selected_date = new Date("{{ selected_date.isoformat }}")
like image 95
Exelian Avatar answered Oct 19 '22 21:10

Exelian


The accepted answer may generate an incorrect date depending on locale.

In FF console:

>>> n = new Date('2011-01-01');
Date {Fri Dec 31 2010 16:00:00 GMT-0800 (PST)}

It's therefore preferable to pass Y,m,d integers to the Date constructor.

I use a template filter to generate the date constructor:

@register.filter(name='jsdate')
def jsdate(d):
    """formats a python date into a js Date() constructor.
    """
    try:
        return "new Date({0},{1},{2})".format(d.year, d.month - 1, d.day)
    except AttributeError:
        return 'undefined'
like image 43
rych Avatar answered Oct 19 '22 20:10

rych