I'm trying to figure out the simplest way to access my file in my HTML template in Django and store this file as a string in Javascript. I've tried directly storing it via:
var global_data = '{{ accessed_file }}';
But for me that did not work. I was able to access it by loading my static files directly in the HTML document and then retrieving it with $.get.
$(document).ready(function() {
{% with '/path/to/file.txt' as accessed_file %}
$.get("{% static accessed_pdb %}", function(data){
// function using data
});
});
{% endwith %}
However, I want to be able to have access to data outside of the $.get. I've tried assigning it to a global variable, but with no luck.
$(document).ready(function() {
var global_data = '';
{% with '/path/to/file.txt' as accessed_file %}
$.get("{% static accessed_pdb %}", function(data){
global_data = data;
});
//access global_data outside of $.get
});
{% endwith %}
I'm using the file for a visual on my site and currently I am unable to manipulate it using HTML buttons when it is within the $.get without reloading the file again. I'm not quite sure how else to approach the problem, so any feeback would be appreciated.
Set the value to a hidden element
<input type="hidden" value="{{ accessed_file }}" id="file">
And access it via:
$('#file').val()
You cannot access the global data outside of the $.get because the result is returned to the callback function asynchronously, it will run after your code outside of $.get runs. You can use promises (https://api.jquery.com/category/deferred-object/) to wait for the data.
Related
I've a function in views.py which returns latitude and longitude:
return render(request, 'map.html', {'lat_lng':lat_lng})
and I am able to access it in html file as {{ lat_lng }} but when I try to use lat_lng in separate js file then I'm not able to access it.
I tried all below stack answers but none worked for me:
Django Template Variables and Javascript
Passing django variables to javascript
How to use Django variable in JavaScript file?
Passing Python Data to JavaScript via Django
You can take advantage of json_script template tag. In your template do this
{{ lat_lng|json_script:"lat_lng" }}
Then in your javascript file you can access this variable like
const lat_lng = JSON.parse(document.getElementById("lat_lng").textContent);
One simple way to do it is to append the following snippet at the top of your template html file(the one that imports your javascript file):
<script type="text/javascript">
const LAT_LNG = "{{ lat_lng }}"; // Or pass it through a function
</script>
when I try to use lat_lng in separate js file then I'm not able to access it.
You can't use a django template variable in a static file. The static files will be returned in a way that bypasses Django's typical request processing.
Instead, set the variables on data-* attributes on an known HTML element, then get the element, access the attribute and use the value that way.
Be sure when that getting the variable in a script tag is before including the separate js file
Exmple :
<script type="text/javascript">
var variable = "{{myV}}";
</script>
<script type="text/javascript" src="myJsFile.js"></script>
I have an app which creates file location from submit button
json_path = os.path.join('json', request.POST['submit'], '.json' )
This gives the file location under \static\json\ folder.
I am sending this using dictionary to template
render_dict = {
'json_path':json_path,
}
Inside javascript, I have the following
<script>
map.addSource('locationData', {
type: 'geojson',
data: "location of the json file needs to be provided here"
});
</script>
can anybody suggest if this can be done through template tagging?
I somehow managed this by following work around. But would appreciate if anything better is suggested.
In render_dict i send a list instead of string -
render_dict = {
'json_path':[json_path],
}
Inside javascript I used the following -
map.addSource('locationData', {
type: 'geojson',
{% autoescape on %}
data: "{{json_path|safe|escape|cut:"'"|cut:"["|cut:"]"}}"
{% endautoescape %}
});
I have sent a variable in context from my django python code as so:
context = {
"data": data,
}
return render(request, "template.html", context)
but do not know how to access it in my javascript file. I have tried accessing it like this:
data_from_django = {{ data }}
However this simply gives me a syntax error. Please can someone tell me the correct way to access this variable.
IN Javascript you have to use the variables within the quotes.
data_from_django = '{{ data }}'
if "data" is a JSON value, be sure to use {{ data | safe }}
In the case where variable and javascript code is not in the same html file,the above method will fail.
In the case of separate js file, wrap the variable with a id and later refer to it in the js file:
//template.html
<div id="data_from_django">{{ data }}</div>
//sample.js
var data_from_django =
document.getElementById("data_from_django").innerHTML;
Below is my code. 'n' logs correctly in the console, and everything works perfectly if I manually enter the value for 'n' into url: '{% url "delete_photo" iddy=2%}'. Alas, when I try to use 'n' as a variable (seen below) it gives me a reverse match not found error. Can anyone help with this?
javascript
function test(n){
console.log(n);
$.ajax({
type: 'get',
url: '{% url "delete_photo" iddy=n%}',
datatype:'json',
success: function(data){
alert(n)
console.log(data)
console.log(n)
},
error: console.log("SSS"),
});}
html
{% for t in photos %}
<div id="photobox" ><img id="img_pb3"src="{{t.photo.url}}">
<div><a><span onclick="test({{t.id}})" class="closeBtn">×</span></div></a>
</div>
{% endfor %}
urls
urlpatterns = [
path('', views.explore, name='explore'),
path('home/', views.home, name='home'),
path('home/comment', views.comment, name='comment'),
path('home/photo_del/<iddy>', views.delete_photo, name='delete_photo')
]
views
def delete_photo(request, iddy):
data = {'a':iddy, 'b': iddy}
return JsonResponse(data, safe=False)
You can't possibly do this. You have fundamentally misunderstood the relationship between backend Django code and front-end Javascript code. Django templates are fully evaluated on the server, at which point the template tags are converted into plain HTML text. There is therefore no way that a Javascript function - which runs much, much later, on the browser itself - can pass a parameter to be used in a template tag.
The only way to do this would be to render the URL with a dummy value - one you know can't occur in the URL itself - and then replace that value in the JS with the one from the parameter, using normal JS string replace functions.
To be honest, it would be better to remove the ID from the URL altogether. Apart from anything else, a delete action should be a POST, not a GET - you don't want the Googlebot accidentally crawling your URLs and deleting all your items - and with a POST you can send the ID in the posted data.
Maybe something like this:
<a class="closeBtn" href="{% url 'delete_photo' iddy=t.id %}" id="{{t.id}}"></a>
And then you can retrieve the reference using attr:
$.ajax({
url: $('.closeBtn').attr("href"),
data: { "iddy": $('.closeBtn').attr("id")},
.....
})
To call a Django view from HTML we use the following:
"{% url 'namespace: view_fun' %}"
But how to do this from Javascript?
Thank you!
One hacky way to do it would be to include following script in your template that references the javascript file.
<script>
var fun_url = "{% url 'namespace: view_fun' %}";
</script>
And then expecting this fun_url variable in your referenced javascript file.