Insert JavaScript variable in Django tag - javascript

I'm working on an app that uses Django and jQuery for various things. I'm trying to assemble an AJAX request with jQuery that requires that I use Django's {% url %} template function. One of the arguments needed for the url call is stored in a JavaScript variable. Is it possible to insert the value of the JS var into the {% url %} tag? Something like
var jsvar = somestuff;
{% url some.view arg1=jsvar %}

No. Pass a sentinel (e.g. %s) to url which you replace in JavaScript with the actual value.

Related

How to use const values ​from JavaScript as an argument of Django Custom template tags and filters?

If I have custom filters and write {% load file_name %} into index.html, How to write:
<script>
const x = 10;
const y = "{{ obj|function:x }}";
</script>
This isn't possible, because the expression {{ obj|function:x }} is parsed by Django on the server before the javascript is run by the browser, so Django can't access the javascript variable x. You can verify this yourself by looking at the page's HTML response in your browser's network tab
-- you will see that any template expression enclosed in {{ }} is replaced by whatever value it resolves to.
If you need to use a javascript variable in Django, an alternative could be to send the variable's value to a Django view on your server and run the function there. Then you can do any computation involving that value on the server and return the appropriate response to the browser to be displayed.

How to inject JavaScript variable in a Django template filter

I have a Django template filter to retrieve dictionary items based on the key passed.
{% with data=dict_data|get_data:key %}
I have separately made a template_tag.py file which returns those items.
def get_domain_data(dictionary, key):
p = ast.literal_eval(dictionary)
return p[key]
# data being returned successfully
The issue is in passing the dynamic value of the key in the filter function.
<script>
var key_val = $('#input_id').val();
'{% with data=dict_data|get_domain_data:"'+key_val+'" %}'; //encountering error here
// rest of the code
'{% endwith %}';
</script>
If I hardcode a string value the entire operation works, but I am unable to use the JavaScript variable within the Django {% filter %} function.
As mentionned by Matt Ellen in a comment, the template code is executed on the server, then the generated result is sent to the browser which interprets the javascript parts - so this just can not work this way.
If your data dict is small enough and doesn't depend on javascipt user interactions (ie the javascript only reads it), then the solution is to serialize it to json (in the view itself or using a template filter - one might already exists FWIW), bind it to a javascript variable (in the template) and then let the javascript code use it as just any js object, ie (assuming a "jsonify" template filter):
<script>
var data_dict = {% data_dict|jsonify %};
function do_something() {
var key_val = $('#input_id').val();
var data = data_dict[key_val];
// rest of the code
}
// and you'll probably want to bind do_something to
// some js event handler
</script>
There is a similar issue at Get javascript variable's value in Django url template tag
Providing arg1 can be numeric and the reversed url doesn't contain other instances of the string /12345/ then you can use,
var url_mask = "{% url 'someview' arg1=12345 %}".replace(/12345/, tmp.toString());

Best way to share data between node.js and django?

I have a variable in django settings.(eg settings.ALLOW_REDIRECT). I am running some tests (django and node.js tests) and the value of settings.ALLOW_REDIRECT would be changed after some tests.
What is the best way to let the node.js tests to access the value of the variable. I thought of using a conf file in which the value of variable can be stored and altered by django. This can be read by the node.js script. Is there any simpler method than this?
You can pass the value of settings.ALLOW_REDIRECT into your template render call:
def myview(request):
...
return render(request, 'mytemplate.html', {'allow_redirect': settings.ALLOW_REDIRECT})
And then the template can check the value of allow_redirect and insert some small unique element into the page HTML to reflect its value:
{% if allow_redirect %}
<div id="allow_redirect_is_true"> </div>
{% else %}
<div id="allow_redirect_is_false"> </div>
{% endif %}
And then your js code can check for the presence of an element with an id of allow_redirect_is_true or allow_redirect_is_false.

how to pass javascript variable into liquid markup?

I have a value from JavaScript:
var customerID = document.getElementById("CustomerID").value;
Now I want query the firstName, lastName from module data, based on that customerID variable.
{module_data resource="customers" version="v3" fields="id,firstName,lastName,titleType,customerTypeId,ratingTypeId" skip="0" limit="10" order="lastName" collection="selected-data"}
{% for item in selected-data.items %}
{% if item.id == 10393092%}
document.getElementById("CAT_Custom_15").setAttribute("value","{{item.titleType.label}}") ;
document.getElementById("CAT_Custom_14").setAttribute("value","{{item.firstName}}");
document.getElementById("CAT_Custom_4").setAttribute("value","{{item.lastName}}");
{% endif %}
{% endfor %}
How should I write the where condition?
Whne I assign instant value that 10393092 in my code above. It is working fine. but I need assign the variable equal to item.id(like item.id == customerID). Anyone can help? Thank you so much
What you are asking for is not possible. Liquid generates a static page, which is then stored on your web server. When a user navigates to your site, the pre-generated page is sent to them. Then the JavaScript in it may execute. At this point, it is impossible to do anything in Liquid. You should be looking for a pure JavaScript solution.
Unfortunately you cannot do that. Reason is liquid is processed at server side and you will be fetching the content from the browser DOM using
var customerID = document.getElementById("CustomerID").value;
When the page loads, the content from server (for module_data) have already processed and after that the DOM elements will load resulting in no data passed to liquid if else condition.
At the moment there is no way to send javascript data to the server for module_data.

List.pop() in Django Template without for loop

I have a list of id all_entries_user. They basically serve as a part of url for rest service that I have developed using TastyPie. Inside my Django template i want to use them by iterating all_entries_user
function ajaxCall(){
$.getJSON("http://localhost:8000/api/Location/" + {{ all_entries_user.pop }} + "/?format=json",
function(json) {
convert(json,"googleMapUser");
}
);
}
Using this I am getting values from Service and this happens in a continous interval .
interval = startInterval(ajaxCall, 3000);
The value of url must change for each call and it must be taken from list
all_entries_user
gives me the same id every time.
I tried to pop values but each time gives me same value
I havent found an efficient way to iterate through this.
Suggestions and Help Please
Why don't you use the for construct?
{% for user in all_entries_user %}
Do your thing with {{ user }}
{% endfor %}
It's very confusing when you mix two languages. What's happening is your javascript is getting "Built" once when the template is rendered so you only have one URL regardless of how many times javascript hits that method. You can verify this by using view source and checking out what your javascript looks like to the client.
If you want the client to call a different URL each time, you will have to send all the IDs down to the client first. One way to do this is by using json serializer or just a simple home grown javascript array builder.
Something like this might work:
<script>
var allEntries = [{% for entry in all_entries_user %}{{ entry.id }},{% endfor %}];
for (entryId in allEntries) {
doSomethingWith(entryId);
}
</script>
This isn't the best way to populate an array of javascript from django, but it works in a hurry.

Categories