Non defined array? - javascript

The code I'm writing is supossed to fetch a set of airports urls, and assign them to an array by code-url.
This is what I have so far:
<script>
var airport = new Array();
function CheckAirportCode(){
{% for x in linklists['airports'].links %}
var y = {{x.url}};
y = y.match(/\/([A-Za-z0-9]{3})\-/);
airport[y] = {{x.url}};
{% endfor %}
}
$(document).ready(CheckAirportCode());
</script>
but when I load the page and access the variable from the console browser, it says it is undefined. Any pointers ?

Related

Python folium fetching csv data to the jinja macro template

I have the jinja macro template provided to my code, which executes the Leaflet circle creation.
I would like to include the .csv data in this template when possible
df = pd.read_csv("survey.csv")
class Circle(folium.ClickForMarker):
_template = Template(u"""
{% macro script(this, kwargs) %}
var circle_job = L.circle();
function newMarker(e){
circle_job.setLatLng(e.latlng).addTo({{this._parent.get_name()}});
circle_job.setRadius({{rad}});
circle_job.getPopup({{role}})
if {{role}} = "Contractor" {
color="red"
}else{
color="black"
}
circle_job.bringToFront()
parent.document.getElementById("latitude").value = lat;
parent.document.getElementById("longitude").value =lng;
};
{{this._parent.get_name()}}.on('click', newMarker);
{% endmacro %}
""") # noqa
def __init__(self, popup=None):
super(Circle, self).__init__(popup)
self._name = 'Circle'
job_range = Circle()
for i,row in df.iterrows():
lat =df.at[i, 'lat']
lng = df.at[i, 'lng']
sp = df.at[i, 'sp']
phone = df.at[i, 'phone']
role = df.at[i, 'role']
rad = int(df.at[i, 'radius'])
is it possible something like this?
A similar approach was here:
How add circle markers to a rendered folium map embedded in a QWebEngineView?
UPDATE I:
I tried recently something like this:
class Circle(MacroElement):
_template = Template(u"""
{% macro script(this, kwargs) %}
var {{this.get_name()}} = L.circle();
function newCircle(e){
{{this.get_name()}}.setLatLng(e.latlng)
.addTo({{this._parent.get_name()}});
{{this.get_name()}}.setRadius({{rad}});
{{this.get_name()}}.setStyle({
color: 'black',
fillcolor: 'black'
});
};
{{this._parent.get_name()}}.on('click', newCircle);
{% endmacro %}
""") # noqa
def __init__(self,
popup=None
):
super(Circle, self).__init__()
self._name = 'Circle'
for i,row in df.iterrows():
lat =df.at[i, 'lat']
lng = df.at[i, 'lng']
sp = df.at[i, 'sp']
phone = df.at[i, 'phone']
role = df.at[i, 'role']
rad = int(df.at[i, 'radius'])
popup = '<b>Phone: </b>' + str(df.at[i,'phone'])
work_range = os.path.join('survey_range.geojson')
job_range = Circle()
Now I lost some features, whereas the Js console says nothing. Is it possible to fetch data from df.iterrows directly to the Macroelement?
UPDATE II
I tried to fiddle with def__init__ section and now my code looks as follows:
class Circle(MacroElement):
def __init__(self,
popup=None,
draggable=False,
edit_options=None,
radius=rad
#lat,
#lng
):
super(Circle, self).__init__()
self._name = 'Circle',
self.radius = radius,
self._template = Template(u"""
{% macro script(this, kwargs) %}
var circle_job = L.circle();
function newCircle(e){
circle_job.setLatLng(e.latlng).addTo({{this._parent.get_name()}});
circle_job.setRadius(50000);
circle_job.setStyle({
color: 'black',
fillcolor: 'black'
});
};
{{this._parent.get_name()}}.on('click', newCircle);
{% endmacro %}
""") # noqa
for i,row in df.iterrows():
lat =df.at[i, 'lat']
lng = df.at[i, 'lng']
sp = df.at[i, 'sp']
phone = df.at[i, 'phone']
role = df.at[i, 'role']
rad = int(df.at[i, 'radius'])
and the error thrown is: The rad is not defined
Is there any way of including the stuff from inside of df.iterrows() in the jinja2 template via defining the def___init?

Django-Javascript - materialcss breaks javascript code when adding new elements to the body of html template

Well this is making my head spin... When I run the following code in a test environment without material css loaded, I get the expected output, a dropdown menu with animals to select from. However, if I run this exact same code with material css loaded, it just displays the title and no dropdown is visible. Why does this happen?
html
{% extends 'base.html' %}
{% load materializecss %}
{% block content %}
<button id = 'id_graph_type'>Add Stuff</button>
{% endblock %}
javascript
graphInput.addEventListener('click', e=>{
var values = ["dog", "cat", "parrot", "rabbit"];
var select = document.createElement("select");
select.name = "pets";
select.id = "pets"
for (const val of values) {
var option = document.createElement("option");
option.value = val;
option.text = val.charAt(0).toUpperCase() + val.slice(1);
select.appendChild(option);
}
var label = document.createElement("label");
label.innerHTML = "Choose your pets: "
label.htmlFor = "pets";
document.body.appendChild(label).appendChild(select);
})

How to use javascript variables with django or vice versa?

I am trying to generate random numbers between 1 to 132 (inclusive) using JavaScript, when a user clicks on a button.
So far so good, it generates the value and I am able to get the desired output.
The problem:
I was to use the generated value in a custom Django filter (or whatever it is called). Let me explain it better with my code:
<script type="text/javascript">
function random_generator()
{
var rand = [];
var i;
var j;
var text = "";
for(i = 0; i < 5; ++i)
{
rand[i] = Math.floor((Math.random() * 132) + 1);
text += rand[i];
}
document.getElementById('rand1').innerHTML = text; //Just trying to see if the numbers are generated properly
var text2 = "{%for i in allb %}{%if i.id == " + text + "|add:0 %}<p>{{ i.name }}</p>{% endif %}{%endfor%}";
document.getElementById('rand2').innerHTML = text2;
document.writeln(rand[0]);
}
</script>
Here's what else I tried doing:
<div id="b005" class="modal">
<div id="rand1"></div>
<div id="rand2"></div>
{%for i in allb %}
{%if i.id == **WANT TO USE THE JS VARIABLE HERE**|add:0 %}
<p>{{ i.name }}</p>
{% endif %}
{%endfor%}
</div>
Note:allb is an object that I have passed from my views.py
Is there any other way of doing the same?
Thank you in advance :)
As Daniel already mentioned, you have to first understand what is going on behind the scenes. Your django templates only exist on your server, and all template code gets executed on that server. This template code can be used for non-html rendering as well, as you are doing in your random_generator() script.
But the browser receives only an evaluated version of the templates. So it is impossible to compare your django template code (server-side) to your client-side js.

Using Django rendered lists in Javascript on the rendered html page

I am working on a django app where I made a custom view that passes a queryset of elements to the rendered html page.
In the html page I want to have an option to select a word from a select list and If the selected word matches any element from the list I got from view, I should need to display it.
I tried using Java script to read these elements into array and then use that array on chnage in select box. but it didnt work as I required.
Here is what I have done so far.
View:
from .models import words as m
def test(request):
words = m.objects.all()
context = Context({
'words': words,
})
return render(request, 'newpage.html',context)
newpage.html:
<select id="sel" onChange="func();">
<option value="" selected="selected">--none--</option>
<option value="word1">word1</option>
....
<option value="wordn">wordn</option>
</select>
<script>
function func()
{
var e = document.getElementById("sel");
var str = e.options[e.selectedIndex].value;
'{% for each in words %}'
var a="{{ each.word }}";
if(str===a)
{
console.log('{{each.word }}')//or passing it to a div in html
}
{% endfor %}
}
</script>
what I require is If the selected element is "word1" and if the queryset "words" has "word1" in it, it should display the word in the page in any div
can any one help me understand the right way to use this queryset object in the html/js.
Fix your script like the following, this should work for you:
<script>
function func() {
var e = document.getElementById("sel");
var str = e.options[e.selectedIndex].value;
"{% for each in words %}"
var a = "{{ each.word }}";
if(str === a) {
console.log("{{ each.word }}")
}
"{% endfor %}"
}
</script>
Try something like this:
<script>
var words = [
{% for word in words %}
"{{ word }}",
{% endfor %}
];
function func() {
var e = document.getElementById("sel");
var str = e.options[e.selectedIndex].value;
for (var word = 0; word < words.length; word++) {
if (words[word] === str) {
console.log(words[word]);
}
}
}
</script>

How to work with django template variable and javascript?

I have a django template variable {% clients_list %}
I want to load this in multiple select boxes with same prefixes.
I am writing this code:
$(document).ready(function(){
for (i=1; i<=30; i++){
for(j=0; j<=clients_list.length - 1; j++){
$('#client'+i).append($('<option>')
.text(clients_list[j])
.attr('value', clients_list[j]));
}
}
});
But I am facing this error:
ReferenceError: clients_list is not defined
Help me please!
As always, encode as JSON.
{% load jsonify %}
var clients_list = {{ clients_list|jsonify }};

Categories