Django reverse url in javascript - javascript

This javascript
window.location.href = "{% url 'namespace:name' object.slug " + currentRow + " %}"
results in a NoReverseMatch error because it takes "currentRow" as a parameter instead of the value behind currentRow.

You are mixing Javascript and the Django template engine.
The Django template engine sees no Javascript variables. No script tags. It only sees text.
Javascript is processed on the clientside, after your HTML and Javascript is generated on the server side by the Django template engine.
If you have a context variable (e.g. coming from your Django view or maybe created in a {% for %} loop) named currentRow, you can use it directly like so:
window.location.href = "{% url 'namespace:name' object.slug currentRow %}"

Related

Include django static files in javascript dinamically

I have this situation. I have some bookcovers on my static files on Django. The jpg files names are the isbn of each book.
I am building img tags on Javascript and would like to incluide these images to change dinamically. I got each book's isbn already in a variable called "isbn". I am assigning it in this way:
var src = "{% static 'img/" + isbn + ".jpg' %}";, and then adding it to the img element. However, the src is been taking as follows: <img id="book-card1img" src="/static/img/%22%20%2B%20isbn%20%2B%20%22.jpg" class="card-img-top">.
Is something I am doing wrong?
The {% static tag will get evaluated first by django server-side, before any javascript runs (because js is run in the browser after django has delivered the page). This means you can't construct tag variables via javascript. Also, if your isbn variable is in javascript, it isn't known when the static tag runs, so it would be taken as a literal string.
Instead you can try
var src = "{{static_prefix}}img/" + isbn + ".jpg"
This does basically the same thing, but allows you more control over the end result, letting js do most of the url construction. See the docs for more

Is there any way I can access Django template variables and URL tags in a JS file so that the user can not inspect the data and links?

I want to access Django template variables and URL tags from my javascript file. currently, I'm doing it like follows-
<script>
const addcommentlink = "{% url 'post:add_comment'%}";
const postid = '{{post.id}}';
const deletecommentlink = "{% url 'post:delete_comment' %}";
const editlikelink = "{% url 'post:edit_like' %}";
const profilelink = "{% url 'instagram:profile' 'name' %}";
</script>
<script src="{% static 'post/js/post_details.js' %}"></script>
but I want to access it directly from the post_details.js file. Is there any way to do that?
You can't use Django template language in javascript files.
You can use variables, tags, filters only in a django template.
A template is a text file. It can generate any text-based format (HTML, XML, CSV, etc.).
If you want to access the result of {% url 'name' %} in a javascript file, you must first render it in the template(maybe store it as a data attribute).
A rough example:
<div id="comment" data-add-link="{% url 'post:add_comment'%}" data-delete-link="{% url 'post:delete_comment' %}"></div>
in your post_details.js:
const addcommentlink = $('#comment').data('add-link');
const deletecommentlink = $('#comment').data('delete-link');
However the user will be able to inspect the data links. And if you need anything in the template, then you must assume that it will be visible to the other users.

How to call a django view function based on its namespace and fun name from js?

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.

How to set a jinja2 expression with a Javascript variable?

How can I use a Jinja2 expression within a js function? I'd tried something similar to the lines below and the expression isn't working. The attribute fileList used in response is a list coming from flask through Json.
var response = JSON.parse(req.responseText);
{% set myFiles = response.fileList %}
Jinja2 is a templating language. Meaning all template expressions will be evaluated and replaced by either text or HTML code before even served to the client.
Whereas Javascript is a scripting language used on the client side.
So there is actually no way to pass any values to a Jinja2 expression from Javascript as there simply don't exist any Jinja2 expressions on the client side because they have all been replaced already by text or html code.
However if you simply want to pass any data from client to server there are a lot of ways to do that. Probably the most fitting for you would be an Ajax call.
I think you looking for including expression or statement in js.
It's possible, use double quotes(" "). One thing you can't directly add in the js file. use your code at the end of the code
var response = JSON.parse(req.responseText);
"{% set myFiles = response.fileList %}"
For Clear Understanding,
app.py
#app.route('/')
def home():
return render_template('index.html',check=0,text='hai')
index.html
<div>
.
.
.
</div>
<script>
var text = {{ text }} //Throws error
var text = "{{ text }}" //console it
{% if(check == 0) %}
console.log('its true')
{% endif %} //Throw error
"{% if(check == 0) %}"
console.log('its true')
"{% endif %}"//Success
</script>
It's working for me. vote if works

Sending JSON data as context quotes becoming "?

I am trying to send some schedule data to a webpage using Django and JSON format. My view to send this data looks like this:
def sessionscheduler(request):
c = connection.cursor()
c.execute("SELECT * FROM meter_schedule WHERE id = 1")
scheduleArray = []
for row in c.fetchall():
data = dict([('lastUpdate',row[1]), ('weekdaysOn',row[2]), ('weekdayChargeRateOffPeriodKwh',row[3]), ('weekdayEveningChargeOn',row[4]), ('weekdayEveningStart',row[5]),
('weekdayEveningDuration',row[6]), ('weekdayDayChargeOn',row[7]), ('weekdayDayStart',row[8]), ('weekdayDayDuration',row[9]), ('weekendsOn',row[10]),
('weekendChargeRateOffPeriodKWh',row[11]), ('weekendEveningChargeOn',row[12]), ('weekendEveningStart',row[13]), ('weekendEveningDuration',row[14]),
('weekendDayChargeOn',row[15]), ('weekendDayStart',row[16]), ('weekendDayDuration',row[17])])
scheduleArray.append(data)
jscheduleArray = json.dumps(scheduleArray)
context = {'jscheduleArray' : jscheduleArray}
return render(request, 'sessionscheduler.html', context)
I have used a template to render what is in jscheduleArray and it is coming out exactly how I want on the HTML page. However I want to use this data in my JavaSript file. The problem is that the quotes are not "" in the page source they are " which the script does not like. How do I fix this. Also I have a separte js file, is there anyway to directly call the JSON object into the the .js file? I am using YUI and pure JS.
I think you can use autoescape tag in your template to not escape the quotes
# sessionscheduler.html
{% autoescape off %}
{{ your_string }}
{% endautoescape %}

Categories

Resources