Django data to Javascript

6,424 views
Skip to first unread message

drakko

unread,
Oct 15, 2013, 8:46:17 AM10/15/13
to django...@googlegroups.com
Hello!

I'm new to Django and Javascript and so I need some help with passing list from django template to Javascript.

The list is available in template (template.html) by using 

{% for shbf in should_have_found_list %}

but I have no idea how to access this list from Javascript.

The should_have_found_list is created in context.py file like:

should_have_found_list = ShouldHaveFound.objects.filter(enabled=1)

and passed to template in view.py as a part of dictionary:

return render_to_response(template_name, RequestContext(request, {
        'form': form,
        'fields': simplejson.dumps(form.field_mapping),
    }))

I would appreciate some guidance :)

Thank You,
Drakko

Larry Martell

unread,
Oct 15, 2013, 11:45:09 AM10/15/13
to django...@googlegroups.com
You can embed js anywhere in your template, e.g.:

{% for shbf in should_have_found_list %}
    <script type="text/javascript">
        my_js_function(shbf);
    </script>
{% endfor %} 

Scot Hacker

unread,
Oct 15, 2013, 11:54:50 AM10/15/13
to django...@googlegroups.com


On Tuesday, October 15, 2013 8:45:09 AM UTC-7, Larry....@gmail.com wrote:


You can embed js anywhere in your template, e.g.:

{% for shbf in should_have_found_list %}
    <script type="text/javascript">
        my_js_function(shbf);
    </script>
{% endfor %} 

I think you meant to write:

        my_js_function({{shbf}});

Another take on this, should you need it, is to send JSON directly over from the django view or model method into the template. Here's how I solved that recently:

        importance_options = json.dumps(dict(BundleNode.importance_options))

That will convert a Django queryset into a JSON object. Then, in your JS template, something like:

    var $options_obj = {{importance_options|safe}};

Season to taste.

./s

Bill Freeman

unread,
Oct 15, 2013, 11:58:29 AM10/15/13
to django-users
I'd probably put the script tag outside the for loop.

But I don't see where you're passing should_have_found_list to the context.  If it's an item (top level) in form.field_mapping, then it needs to be something like:

  ...
  {% for shbr in form.field_mapping.should_have_found_list %}
  ...


I don't understand why you are JSON encoding form.field_mapping for the fields template variable.  There could be perfectly valid reasons.  But if that was supposed to make should_have_found_list available in JavaScript, it could work, but you would have to do something with the fields variable inside a script tag, such as use it in a var statement to initialize a variable (var fields = {{ fields }};), and then dereference it in JS.


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CACwCsY4PvmRLOkpCrsRps4xLixqRbjkeMhqdvoOuS%2B3g9-RgEA%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.

Larry Martell

unread,
Oct 15, 2013, 12:02:43 PM10/15/13
to django...@googlegroups.com
On Tue, Oct 15, 2013 at 9:54 AM, Scot Hacker <scot....@gmail.com> wrote:


On Tuesday, October 15, 2013 8:45:09 AM UTC-7, Larry....@gmail.com wrote:


You can embed js anywhere in your template, e.g.:

{% for shbf in should_have_found_list %}
    <script type="text/javascript">
        my_js_function(shbf);
    </script>
{% endfor %} 

I think you meant to write:

        my_js_function({{shbf}});

Yes - not enough coffee yet.

drakko

unread,
Oct 16, 2013, 3:39:17 AM10/16/13
to django...@googlegroups.com
Thanks for help. I will try some of these ideas :)

I don't understand why you are JSON encoding form.field_mapping for the fields template variable.
This was like that when I got this code. I am just continuing to develop this app. 

But accessing should_have_found_list in template has no problems. I have separate JS file that contains functions (event handlers for buttons etc.). I can't figure out (total newbie in JS :D ) how to access (or pass) should_have_found_list there. (Sorry I wasn't clear enough in my first post)

Drakko

Bill Freeman

unread,
Oct 16, 2013, 10:14:39 AM10/16/13
to django-users

On Wed, Oct 16, 2013 at 3:39 AM, drakko <gund...@gmail.com> wrote:
...
 
But accessing should_have_found_list in template has no problems. I have separate JS file that contains functions (event handlers for buttons etc.). I can't figure out (total newbie in JS :D ) how to access (or pass) should_have_found_list there. (Sorry I wasn't clear enough in my first post)

Things that the template context knows are available when the template is rendered.  That is, when the template is turned into (in this case) an HTML document (represented as a string).  This happens on the server.

The only thing sent to the browser is that HTML document, notwithstanding that that stuff in that HTML document may cause the browser to load other stuff (like images, javascript files, and CSS files).

But, specifically, the template context is not automatically included in any way.

If you have a template context variables that you wish to reference from the javascript (which runs in the browser, long after template rendering is complete) then you must arrange that the HTML document contain, within a suitable script tag, javascript code that sets a javascript variable to a javascript literal.  For example, if template context variables "count" and "name" have, respectively, values 1 and "Joe", you might write something like this in your template:

    <script type="text/javascript">
       var ct = {{ count }},
            nm = "{{ name }}";
    </script>

Which becomes, in the HTML sent to the bowser:

    <script type="text/javascript">
       var ct = 1,
            nm = "Joe";
    </script>

Now those values are available to the javascript running in the browser as "ct" and "nm".  (You don't have to use different variable names.  I just wanted it to be clear which were template context variables and which were javascript variables).

But note that not all python objects can be sent this way.  You can't, for example, just send a queryset and expect to be able to use its "filter" method from javascript.

You have two choices for sending more complex objects who's ultimate parts are representable as javascript scalars.  If they can be JSON encoded, then that *IS* a javascript object literal.  Or you can iterate through the object (and subobjects) rendering each by hand, including suitable javascript object syntax separators and wrappers, like brackets, braces and commas.

Note, too, that my first code above does not work if the name variable contains a double quote, since:

    nm = "Joe "the schmoe" Gogo";

isn't valid javascript.  The json built into modern pythons is willing to encode a string as a suitable javascript object literal, with all necessary escaping and with the quotes built in (even though this isn't legal JSON - formally the top level object must be a javascript array or object).  So if the name template context variable had been created in the view thusly:

    ...
    name = json.dumps(obj.name),
    ...

then the following is correct:

    <script type="text/javascript">
       var ct = {{ count }},
            nm = {{ name }};
    </script>

Note that the quotes have been removed.

[It might be useful to have a json dumps template filter.  Perhaps there's one I haven't found.]

drakko

unread,
Oct 22, 2013, 8:36:57 AM10/22/13
to django...@googlegroups.com
Thanks!!!

This helped a lot. Now it is working as I was hoping :)

drakko
Reply all
Reply to author
Forward
0 new messages