Like we can access a variable in the JS part like "{{vaiable_name}}". How can we update the value of variable_name inside the javascript?
Let's say code will look like this,
{% if variable_name %}
<p> Condition is true </p>
{% endif %}
One way is to inject a small Javascript through the Django template engine, with {{variable}} substitution.
My own base.html contains
<script type="text/javascript"> $(document).ready( function() {
{% block onready_js %}{% endblock onready_js %}
});
</script>
and then in any template extending base.html where I want to pass variable values, I can simply code
{% block onready_js %}
/* some JS with Django substitutions */
var foo = "{{foo}}";
...
{% endblock %}
The one thing you have to remember is that your JS must not contain consecutive open- or close-braces without a space between them!
(If the block is not defined, then the base.html defines a null function to be executed when the document is ready)
you can add a span tag with an id and then target the id within javascript
<span id='django_variable_id'>{{variable_name}}</span>
<script>
function update_django_variable(new_var){
/* get the span element */
var span = document.getElementById('django_variable_id');
/* set new var here */
span.innerText = new_var;
}
</script>
or will also work as long as there are no other variables with this name
<span id='var_{{variable_name}}'>{{variable_name}}</span>
<script>
function update_django_variable(new_var){
/* get the span element */
var span = document.getElementById('var_{{variable_name}}');
/* set new var here */
span.innerText = new_var;
}
</script>
Related
I want to implement below using javascript so row click it will get index and display object of this index.
in django template this is working.
<div>{{ project.0.customer_name}}</div>
<div>{{ project.1.customer_name}}</div>
but the below javascript are not working even I get the correct ID.
var cell = row.getElementsByTagName("td")[0];
var id= parseInt(cell.innerHTML);
// not working
document.getElementById('lblname').innerHTML = '{{ project.id.customer_name}}';
// this is also working but what I want is dynamic base on row click
document.getElementById('lblname').innerHTML = '{{ project.1.customer_name}}';
display django object using index in javascript.
You have to understand what is happening with your code:
Templates like this are processed on the server:
'{{ project.id.customer_name}}'
I believe you do not have project.id on your server side, so you get None in the above line, and the moustache tag becomes smth like an empty string, and actual JavaScript code is like this:
document.getElementById('lblname').innerHTML = '';
It is only now that JS code is executed, and you can imagine what it will do.
What you want is processing moustache tags after the id variable has been set in JS, which is not how stuff works (at least, if you don't have some crazy tool chain).
One way of achieving what you want is to provide the whole project object (or array) to JavaScript by doing the following:
<script>
const project = {{ project|safe }};
</script>
A complete Django template could look like this (I used <span>s instead of table cells:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>django test</title>
</head>
<body>
{% block content %}
{% for item in project %}
<span data-id="{{ forloop.counter }}">{{ forloop.counter }}</span>
{% endfor %}
<div id="output" style="display: flex; flex-direction: column-reverse;">
</div>
<script>
const project = {{ project|safe }};
const spans = document.getElementsByTagName('span');
const output = document.getElementById('output');
const onSpanClick = (event) => {
const id = parseInt(event.target.getAttribute('data-id'), 10) - 1; // forloop.counter is 1-based, JS arrays are 0-based
const div = document.createElement('div');
div.innerHTML = project[id].customer_name;
output.appendChild(div);
}
Array.from(spans).forEach(span => {
span.addEventListener('click', onSpanClick);
})
</script>
{% endblock %}
</body>
</html>
Another way is the AJAX way: you create an API endpoint on your server side, so that an URL like example.com/api/customer_name/?id=999 responds to you with the name of customer id=999 when you click on some element and trigger an XMLHttpRequest with param id=999.
I've got something like this in my Django template:
<script>
var selected_direction = $("#id_direction").val();
{% for bus_stop in bus_stops %}
{% if bus_stop.direction == selected_direction %}
// Do something //
{% endif %}
{% endfor %}
</script>
I can do everything with bus_stops until it reaches the {% if %} statement. How can i compare javascript variable with django variable?
/Edit
Maybe the question was not constructed properly. However i solved my problem by doing this:
<script>
var selected_direction = $("#id_direction").val();
var temp_direction;
{% for bus_stop in bus_stops %}
temp_direction = "{{ stop.direction }}";
if (temp_direction == selected_direction){
////////
///////
}
{% endfor %}
</script>
you can compare this condition
{% if bus_stop.direction == selected_direction %}
by converting you template value to js value, and compare it in js if condition as follows.
if(selected_direction == '{{bus_stop.direction}}')
{
//code here
}
Here is a post that explains how they work together. There is a injection risk involved with this. Maybe make an ajax call for your data and do everything in javscript.
I am passing a data in the form of a dictionary from views.py to results.html in Django framework. The dictionary has the following format
'tweet': (tweet_analysis, tweet_id)
now in results.html, called by the views.py,
I am trying to Embed all the tweets that are passed to results.html, but the following code only displays one embedded tweet.
dicPositive: This is the dictionary containing all the tweets data
{% for tweet, tweet_feel in dicPositive.items %}
<div id="tweet" tweetID="{{tweet_feel.1}}"></div>
<script sync src="https://platform.twitter.com/widgets.js"></script>
<script>
window.onload = (function(){
var tweet = document.getElementById("tweet");
var id = tweet.getAttribute("tweetID");
twttr.widgets.createTweet(
id, tweet,
{
conversation : 'none', // or all
cards : 'hidden', // or visible
linkColor : '#cc0000', // default is blue
theme : 'light' // or dark
})
.then (function (el) {
el.contentDocument.querySelector(".footer").style.display = "none";
});
});
</script>
<!-- <li>{{tweet}} –> {{tweet_feel.0}} –> {{tweet_feel.1}}</li> -->
{% endfor %}
It is because you have used same id for multiple HTMLElements created while looping.
You must add loop counter to id attribute of div and also when
you are fetching it using getElementById inside script tag
{% for tweet, tweet_feel in dicPositive.items %}
<div id="tweet_{{forloop.counter}}" tweetID="{{tweet_feel.1}}"></div>
<script sync src="https://platform.twitter.com/widgets.js"></script>
<script>
window.onload = (function(){
var tweet = document.getElementById("tweet_{{forloop.counter}}");
# Rest of your code
...
</script>
{% endfor %}
I use the file upload plugin from Blueimp. In template download, I want to write value into
<div id="status"></div>
each time when template is render.
The div tag is put outside the form tag.
This is a script template download:
<script id="template-download" type="text/x-tmpl">
{%
var location = document.getElementById("hdnLocation").value;
var folder = document.getElementById("hdnFolder").value;
%}
{% for (var i=0, file; file=o.files[i]; i++) { %}
<div class="template-download fade clear-fix" data-value="{%=location%}\{%=folder%}\{%=file.name%}">
... do something ...
{%
document.getElementById("status").value = "TPL";
%}
</div>
{% } %}
</script>
location and folder, I can get value but trying to set value is failed.
Your problem is here:
document.getElementById("status").value = "TPL";
You need to use innerHTML not value
document.getElementById("status").innerHTML = "TPL";
.value is a property assigned to input elements like input, select, textarea
Using Django, I can successfully read and display values from my model in the content segment of my template, but I can't get the values from my model in the head segment of my template.
Here's the code -->
view.py:
from django.shortcuts import render_to_response
from django.template import RequestContext
from host.models import Event
def EventSingle(request, slug):
return render_to_response('event.html', {'eventobject': Event.objects.get(slug=slug)})
event.html:
{% extends "base.html" %}
{% block extrahead %}
<script type="text/javascript" src="https://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
var variable1;
variable1="click worked";
//variable1={{ eventobject.datetime }};
$(document).ready(function () {
$("#pic").click(function (b) {
alert(variable1);
});
});
</script>
{% endblock %}
{% block content %}
<div id="eventobject">
<p>{{ eventobject }}</p>
<p>{{ eventobject.location }}</p>
<p>{{ eventobject.datetime }}</p>
<img id="pic" src="{{ eventobject.image1.url }}" />
</div>
{% endblock %}
When clicking on the image, an alert box pops up with the text "click worked", but if I comment out variable1="click worked"; and un-comment variable1={{ eventobject.datetime }}; nothing happens when I click on the image. Can I not use model references in the head section of django template? All other references to the model in the content block display the values from the DB properly.
I guess eventobject.datetime must be a string or python datetime object.
If it is a string, change your code to :
variable1= "{{ eventobject.datetime }}" ;
If it is a datetime object, use django template filter :
variable1= "{{ eventobject.datetime|date:"D d M Y" }}"
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
If you do not put the quotes, the javascript statement looks like:
variable1 = 2013-05-30 ;
which is INCORRECT javascript syntax, the quotes are needed.
Per Django docs, you can use a date filter to format date:
variable1= '{{ eventobject.datetime|date:"d-m-Y" }}';
Additionally, you can also set DATE_FORMAT (or DATETIME_FORMAT) setting to set a project-wide default for displaying such values.