How to pass a value from a Django View to a JQuery Slider bar.

2,035 views
Skip to first unread message

7equiv...@gmail.com

unread,
Mar 4, 2013, 6:36:12 PM3/4/13
to django...@googlegroups.com
Hello, my goal is to use a Django powered website to control the brightness of a light. I am using a JQuery slider bar as a dimmer switch. When the JQuery slider bar loads, I need it to iniciate to a value I have in my database.

I already have my View, Model, and Template setup, and can pass variables from the View to the HTML part of the template. My Question is, How do I pass the variable from the View to the JQuery slider bar?

Thankyou for any help. I am new to Django, JQuery and pretty much all Web programming, my main experince is working with microcontollers and low level language between chips.

Shawn Milochik

unread,
Mar 4, 2013, 6:41:35 PM3/4/13
to django...@googlegroups.com
Probably consume the view with AJAX, doing a POST on the change event
of the slider.

http://api.jquery.com/category/ajax/

Put your result in a dictionary within your view and return it as JSON:

return HttpResponse(json.dumps(result), mimetype="application/json")

Gabriel

unread,
Mar 4, 2013, 6:50:39 PM3/4/13
to django...@googlegroups.com
If I understood it right, I think it would be enough to serve the javascript with the initialization
value hardcoded in it, right? Like using {{ }} tags.
Is there a way to do this if there's a separate .js file?

- Gabriel

--
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?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.



7equiv...@gmail.com

unread,
Mar 4, 2013, 7:23:04 PM3/4/13
to django...@googlegroups.com, g.ko...@gmail.com
Yes, Thankyou for helping me clean up my line of questioning, That is exactly what I want to know, can I use the {{ }} tags to do this, and can they be placed in a seperate .js file.

Michael Pimmer

unread,
Mar 4, 2013, 10:02:37 PM3/4/13
to django...@googlegroups.com
I usually keep a separate .js file in my templates where I set such javascript variables (preferrably as a hash or module). You can directly include it in the base.html template so you don't make 2 requests out of it.
The main javascript functionality should definitely go to the static files though.

7equiv...@gmail.com

unread,
Mar 5, 2013, 4:57:31 PM3/5/13
to django...@googlegroups.com, mpi...@nswrdn.com.au
Well, I definitly can't just throw a variable into the Javascript using the {{ }} tags. I tried it and it didn't work. I'm sure Shawn Milochik is correct about consuming the view with AJAX, however that is going to take sometime to learn and explore, as I am novice at this. It seems there should be an easy way for something so simple, I can pass a variable from a view to a template, but not from a view to a javascript file.

Gabriel

unread,
Mar 5, 2013, 5:05:01 PM3/5/13
to django...@googlegroups.com
You could use some small <script> tags inside your django template to set global values for your javascript objects from another file to read upon initialization. It may solve your problem.
There may be some more sophisticated ways of doing this, but I think this is easy/fast enough. Just be on the lookout for security issues.

If you're just looking to initialize a JS function with some value Django calculated on the server (like the starting point for the slider) I think you'll be ok.

- Gabriel

Tom Evans

unread,
Mar 5, 2013, 5:23:24 PM3/5/13
to django...@googlegroups.com
This is not true. You can render your javascript using a template if
you like, templates can be used to generate any textual format. A view
is simply a function that takes a request and produces a single
resource as a response.

However people don't normally dynamically generate their JS. This is
because it is not necessary, you simply include the data you want into
the HTML that the javascript will run against. You then use standard
JS methods to extract the data that you need and use it.

Eg, if you wanted to trigger an AJAX request each time someone clicked
a <li>, you might do something like this:

<ul>
<li>Hello World</li>
<li>Wibble<li>
</ul>

Your JS file may have something like this:

$('ul li').click(function(ev) {
$.getJSON( '{{ some-url }}', json_handler);
}

Obviously the "{{ some-url }}" would not work. Instead, the data can
be inserted in to the HTML element to which it refers:

<ul>
<li data-json-uri="/json/foo/bar/1">Hello World</li>
<li data-json-uri="/json/foo/bar/2">Wibble<li>
</ul>

and now the JS can be written to query that data:

$('ul li').click(function(ev) {
$.getJSON(ev.target.data('json-uri'), json_handler);
}

tl;dr - if you need data in your javascript files, insert it into the
HTML doc and extract it when you need it.

Cheers

Tom

7equiv...@gmail.com

unread,
Mar 5, 2013, 6:48:28 PM3/5/13
to django...@googlegroups.com
Alright guys, thanks for the input, I need something a bit more specific to my case due to my ignorance on the subject at hand, so I am posting the code for my View, Template, and JQuery.  So, basically I want to take the slider1 object value in the View, and place it in the Javascript where value = 37 has been coded.

////////////////////////////////// Here is my view //////////////////////////////////////
def slider_page(request):
 
  slider1 = Slider.objects.get(sliderID=1)
  variables = RequestContext(request, {'slider1': slider1})
  return render_to_response('slider_page.html', variables)
 
///////////////////////////////// Here is my Template //////////////////////////////////
 
{% block external %}
  <script type="text/javascript" src="/media/control.js"></script>
{% endblock %}
 
{% block content %}
  <br></br>
  <p>
    <label for="power">Intensity:</label>
    <input type="text" id="power" style="border:0; color:#f6931f; font-weight:bold;" />
  </p>
  <div id="slider_1"></div>
  <br></br>
{% endblock %}

////////////////////////////// Here is my JQuery //////////////////////////////////////

  $(function (){
    $( "#slider_1" ).slider({
      range: "min",
      value: 37,
      min: 0,
      max: 100,
      slide: function( event, ui ) {
        $( "#power" ).val(ui.value );
      }
    });
    $( "#power" ).val($( "#slider_1" ).slider( "value" ) );
    return false;
  });

Tom Evans

unread,
Mar 6, 2013, 10:00:37 AM3/6/13
to django...@googlegroups.com
Er, just put your jquery into your template. The JS is specific to
that page (or pages with a #slider_1 on it, I suppose), so simply
include it into the page:

{% block content %}
<br></br>
<p>
<label for="power">Intensity:</label>
<input type="text" id="power" style="border:0;
color:#f6931f;font-weight:bold;" />
</p>
<div id="slider_1"></div>
<br></br>
<script type='text/javascript>
$(function (){
$( "#slider_1" ).slider({
range: "min",
value: {{ slider1.value }},
min: 0,
max: 100,
slide: function( event, ui ) {
$( "#power" ).val(ui.value );
}
});
$( "#power" ).val($( "#slider_1" ).slider( "value" ) );
return false;
});
</script>
{% endblock %}


Alternatively, store the data on the slider HTML node and extract using JS:

{% block external %}
<script type="text/javascript" src="/media/control.js"></script>
{% endblock %}

{% block content %}
<br></br>
<p>
<label for="power">Intensity:</label>
<input type="text" id="power" style="border:0;
color:#f6931f;font-weight:bold;" />
</p>
<div id="slider_1" data-slider-value="{{ slider1.value }}"></div>
<br></br>
{% endblock %}

// separate JS file
$(function (){
$( "#slider_1" ).slider({
range: "min",
value: $(this).data('slider-value'),
min: 0,
max: 100,
slide: function( event, ui ) {
$( "#power" ).val(ui.value );
}
});
$( "#power" ).val($( "#slider_1" ).slider( "value" ) );
return false;
});

Cheers

Tom

7equiv...@gmail.com

unread,
Mar 7, 2013, 7:31:11 AM3/7/13
to django...@googlegroups.com, teva...@googlemail.com
 Hey, Thanks alot.... I tried to do that before and it didn't work(the slider bar disappeared) and on your suggestion tried again, still didn't work, however since you suggested it, I knew it had to be the right track, so I got rid of the variable in the Javascript and the slider bar came back, so from there I played with the the variables in the Views and got it to work.

So thank you so much for the help....

I am trying to implement control of GPIO pins and UART modules on a Raspberry Pi via a web interface.

Here's a short youtube video of my App and hardware, Thanks again!

http://www.youtube.com/watch?v=ebkxEL30bno

7equiv...@gmail.com

unread,
Mar 7, 2013, 7:58:27 AM3/7/13
to django...@googlegroups.com, teva...@googlemail.com
Now that I have that part working, I would like to make since of what was going on and why it didn't work in the first place. I have a question...

Let's say
(1) a page is requested, and the View renders_to_response  a template
(2) this template uses a {% include 'second_template.html' %}

Does the second_templates View get executed or does the Html just get added?


Daniel Roseman

unread,
Mar 7, 2013, 1:13:49 PM3/7/13
to django...@googlegroups.com, teva...@googlemail.com
Templates don't have views. It doesn't make sense to say if the "second_templates' view" gets executed, there's no such thing. Views (can) render templates, but the same template can be rendered by any of a number of views. Including just includes the rendered HTML of the template, using the current template context plus anything you add via `with`.
--
DR.

7equiv...@gmail.com

unread,
Mar 8, 2013, 4:35:57 AM3/8/13
to django...@googlegroups.com, teva...@googlemail.com
Thankyou Daniel, That's my name too.... I appreciate that, it clears things up and now I understand why the tinkering I did worked!
 
Thankyou  Tom, Gabriel, and everyone for the help...
 
Please follow my next post where I seek help one more time(Need slider to write to database), after that I'm going to tear my code down and build it back up, and examine so many details that have been lost on me. Django + Raspberry Pi + Microcontrolers = cool stuff!
 
Thanks again!
Reply all
Reply to author
Forward
0 new messages