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

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.

Related

Can I call a JavaScript function from a tornado template if check?

I have a websocket based chatroom that performs translations based on the users desired language in the room. On the python side I populate both the spoken language and the translated language. I pass these values to a templated html page where I want to make a javascript call in the templated if check which will help me to decide which value to populate in the message window. Is this possible to do? I keep getting an error stating my return result is invalid. I have shared what I currently have in my template. The function getUser() is a javascript function and message is the param passed from python to the template.
<div class="message" id="m{{ message["id"] }}">
{% if message["user"] == getUser() %}
{% module linkify(message["translation"]) %}
{% else %}
{% module linkify(message["transcription"]) %}
{% end %}
</div>
{% if message["user"] == getUser() %}
You say that getUser() is a JS function. In that case, it won't work. This is because the templates are compiled at the server but the JS runs on the browser. Hence, getUser() function will not run.

How to access flask config in javascript?

I need the config variables in javascript in my flask application. Currently, I access the config variables via:
#app.route('/api/getconfigs/')
def get_config_variable():
return config['VARIABLENAME']
Is this the only way to get the flask config in javascript? What would be the best practice to do this?
If you need the value as part of an API call, then yes, sending the value from an endpoint is correct. If you're rendering templates, then you can render the values in the JavaScript sent to the client.
Flask injects its config into the template context. Within a template, config['key'] or config.key will access any value in the config. Since you're rendering it as JavaScript, use the tojson filter to render valid values.
var debug = {{ config['DEBUG']|tojson }};
You could load the specific variable into your jinja2 globals like so:
app.jinja_env.globals.update(VARIABLENAME=config['VARIABLENAME'])
Then in an always included base-template load the variable into your javascript like so.
<script>
var config = {};
config.VARIABLENAME = {{VARIABLENAME}};
</script>
Or just throw the whole config into your jinja2 env like so:
app.jinja_env.globals.update(config=app.config)
And then insert the specific Variable only if it is found in config.
{% if config['VARIABLENAME'] %}
<script>
var config = {};
config.VARIABLENAME = {{config['VARIABLENAME']}};
</script>
{% endif %}

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.

Insert JavaScript variable in Django tag

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.

Categories