use dropbox value in jinja if statement - javascript

I have a dynamic dropbox using jinja loop. As part of the condition, I want to use a value from another dropbox. For this, I am setting up a global variable using scenario_id = $('#scenario').val(); in an onchange function for the other combo. It works ok. I also show it on the page.
However, when I use scenario_id as part of the if statement, it does not work. It does not use the correct value. It is potentially null ( I am not sure).
So, the below code does not create a correct select field. If I replace the scenario_id with a static known id, it works okay for that selected scenario.
Can you please help me to be able to use dynamic value here?
Kind Regards,
Sofia
<SELECT name="source1" id="source1">
{% for node in allowed_values_nodes %}
{% if node[0]==edge.source_id and node[2]== scenario_id%}
<OPTION value = {{node[0]}} selected>{{node[1]}}</option>
{% endif %}
{% if node[0]!=edge.source_id and node[2]== scenario_id%}
<OPTION value = {{node[0]}}>{{node[1]}}</option>
{% endif %}
{% endfor %}
</SELECT>
I added the code already.

Related

flask javascript can't print/log jinja2 request.form variable

Hi all I'm trying to get the value from flask and print it in javascript.
When I do print with a javascript string variable in my form it prints none.
var javascript_variable = "key_name";
// output is: request
console.log('request'+"{{request.form['"+javascript_variable+"']}}");
Also tried
// output is: request
console.log('request'+"{{request.form["+javascript_variable+"]}}");
however when I manually type the key name it works.
// output is: request key_information
console.log('request'+"{{request.form['key_name']}}");
Can someone please tell me what I'm doing wrong.
EDIT: I do not want to hardcode the keyname because the key_name is a changing dynamically
I'm trying to access that variable, so I can populate my select option/checkbox/radiobox option something like <option {% if request.form['key_name'] == "value" %} selected {% endif %} same for checkbox and radio box
In order to do that, you can use the flash statements inside the views in flask as follows,
#blueprint.route('/something.html', methods=['GET', 'POST'])
#login_required
def function():
try:
flash("Submission successful!")
except Exception as e:
traceback.print_exc()
return render_template('something.html')
In jinja, you can access the flash variable in the following way,
{% if get_flashed_messages() %}
{% for message in get_flashed_messages() %}
<script>window.alert("{{ message }}")</script>
{% endfor %}
{% endif %}

Avoid pagination limits for simple output - Shopify / Liquid

I want to create a simple list of every article URL in my blog (I have >150).
My current code:
{% for article in blogs['myblog'].articles %}
{{article.url}}
{% endfor %}
The problem is that it only outputs 50 URLs, as per the standard Shopify pagination limit. How could I overcome this? Any solutions using Ajax or otherwise would be highly appreciated.
You can overwrite the pagination limit simply by wrapping the call with the pagination tag and passing the number you want to paginate.
{% paginate blogs['myblog'].articles by 999 %}
{% for article in blogs['myblog'].articles %}
{{article.url}}
{% endfor %}
{% endpaginate %}
PS: Please note that the more articles you have the longer it will take for the DOM to load.

How to associate dynamic value with HTML elements?

I want to create a list which is clickable and which would allow me to take a survey when I click it.
{% extends "layout.html" %}
{% block title %}
Take Survey
{% endblock %}
{% block main %}
<div class="list-group">
{ for search in searches }
{{search.topic}}
{ endfor }
</div>
{% endblock %}
When I click it I want it to go to a page which shows the questions of the survey whose topic was being shown.
I have created SQL tables for users,surveys,questions and options. Surveys are linked to users, questions are linked to surveys and options are linked to questions.
I just need a way to access the survey id({{search.id}}) in my take route where I could run a SQL query using the survey id to link everything.
Just a disclaimer, I am a beginner in HTML so please try to explain elaborately.
There are multiple ways that you can do this with html, here are a few of them
create a hidden input with the value that u need, and later when u need it retrieve it from that input
<input type="hidden" id="searchId" name="searchId" value="3487">
add a custom attribute to an element, and later when needed retrieve it from that element
<div class="list-group">
{ for search in searches }
{{search.topic}} data-search-id="{{search.id}}"
{ endfor }
</div>
There are also multiple ways you can do this without html
insert a script that has the search id, and later retrieve that id from javascript
{% block main %}
<div class="list-group">
{ for search in searches }
{{search.topic}}
{ endfor }
<script>
// just make sure that this variable is unique, so u dont cause errors or overwrite another variable by mistake
const MY_APP_SEARCH_ID ={{search.id}}
</script>
</div>
{% endblock %}
You could also generate a unique url for each survey
{{search.topic}}
and then handle that search id from the \take endpoint

Django template ifequal statement always true

Hi I am building a simple blog using Python/Django. In my index.html file, I am trying to show archived posts when a button containing a month is clicked. At the moment, I am just trying to get the id of every post made in that month into a javascript array. For some reason though,it always returns true!
<script type="text/javascript">
function showPosts(month)
{
var posts_in_month=[];
{% for post in all_posts %}
var match = {{ post.pub_date.month }}
{% ifequal match month %}
posts_in_month.push({{ post.id }})
{% endifequal %}
{% endfor %}
}
</script>
I then go on to have a switch statement where I show the contents of the array depending on the month clicked. The code definitely works, when I call an alert(month) it shows up correctly, and when I call alert({{ post.pub_date.month }}) it shows up fine as well. These are usually not the same though, why is it always evaluating the ifequal to true?
You cannot create Javascript variable in python and use it as python's variable.
Replace the match with actual value:
{% ifequal post.pub_date.month month %}
posts_in_month.push({{ post.id }})
{% endifequal %}

How to send values via ajax from django template to views?

I have a select box that calls a function on changes. The function finds the selected value from "Products" selectbox.
I want to throw that selected value to my views.py which after some operations return the list of data and Populates the Destination's selectbox.
I want to use ajax for this purpose. Please help.
My code looks like this:
<script type="text/javascript">
function select_value()
{
var e = document.getElementById("Product");
var prod = e.options[e.selectedIndex].text
console.log(prod)
}
</script>
This is what my selectbox look like:
<table>
<tr>
<td>
<select id="Product" onChange="select_value();">
{% for products in product_name_list %}
<option>{{products|safe}}</option>
{% endfor %}
</select>
</td>
<td>
<select id="dest">
{% for des in destinations_name_list %}
<option>{{des|safe}}</option>
{% endfor %}
</select>
</td>
</tr>
</table>
This is my views.py:
def selection_filter(request,prod):
destination_objs = Destination.objects.filter(product=prod)
destination_name = destination_objs.values_list('name')
destination_name_list = []
for iter_name in destination_name:
destination_name_list.append(iter_name[0].encode('utf-8'))
return render_to_response('temp/test.html',
{"destination_name_list" : destination_name_list},
)
I think the point you might be misunderstanding is that your Django template for your whole page will not be re-rendered "magically". In Django's standard model-view-template paradigm, the template is rendered just once, upon the initial request. The way you've written it, unless there's a default product selection, you're going to have an awkward empty <select> in the first render. But ignoring that...
For a problem like this, you need two views: one for rendering the whole page, and one for providing the Ajax response. There are two main options for the second view: 1) return JSON for interpretation/rendering by your script post-response or 2) return a fully rendered HTML fragment for direct insertion into your DOM. In this case, I'd just go for option 2.
I recommend looking into Jquery, as it makes Ajax and DOM manipulation super simple.
If you've got Jquery, it's as simple as adding to your script:
$.get('/destinations/' + prod)
.done(function (html) {
$(#dest).html(html);
});
(You can do the same thing without Jquery too, but it requires a bit more wrangling)
Your test.html file should contain:
{% for des in destinations_name_list %}
<option>{{des|safe}}</option>
{% endfor %}

Categories