Use Jinja Variable to generate n elements - python

I want to use Jinja variables to generate n options in a drop down. Here is an example:
Session Select: <br>
{{ sessions }}
<select style="color:black">
{% for session in sessions %}
<li>{{ session }}</li>
{% endfor %}
</select> <br><br>
The value of sessions is:
['Session 1', 'Session 2', 'Session 3']
Any thoughts?

Assuming no_sessions is your n value... I would try something like this:
Session Select: <br>
<select style="color:black">
{% range number from 1 to no_sessions %}
<option>Session {{ number }}</option>
{% endrange %}
</select> <br><br>
(related to this question)

To generate items within a select box you use the <option> tag, not <li>.

Session Select: <br>
<select style="color:black">
{% for session in sessions %}
<option value="{{ session }}">{{ session }}</option>
{% endfor %}
</select> <br><br>

Related

django if condition not working when using variable, but when using number it's working

why this code not working, i get variable "data" from views.py
when i change data.numrooms with number like '1', it's working well, but is use data.numrooms that's not working
<select class="form-control" name="numadults">
<option value=''>No. of Adult</option>
{% for i in range %}
{% if data.numadults == i %}
<option value="{{ i }}" selected>{{ i }}</option>
{% else %}
<option value="{{ i }}">{{ i }}</option>
{% endif %}
{% endfor %}
</select>
Why not put that logic in the view and pass it to template like this:
# view
adult_range = list(map(lambda x: (x, True) if x == data.numadults else (x, False), range(1,10))
# Template
<option value=''>No. of Adult</option>
{% for i, selected in adult_range %}
{% if selected %}
<option value="{{ i }}" selected>{{ i }}</option>
{% else %}
<option value="{{ i }}">{{ i }}</option>
{% endif %}
{% endfor %}
Similarly to ruddra's solution, the easiest way to achieve this is probably to do the bulk of the logic in the view:
adults = [(element, element.number == data.numadults) for element in adult_list]
This will give you a list of two-tuples of (<adult object>, <boolean>) where the boolean represents the conditional you're trying to use in the template to decide whether to use selected attribute.
In the template, you can then base your conditional solely on that boolean:
<option value=''>No. of Adult</option>
{% for i, selected in adult_range %}
{% if selected %}
<option value="{{ i }}" selected>{{ i }}</option>
{% else %}
<option value="{{ i }}">{{ i }}</option>
{% endif %}
{% endfor %}
Note though that you can also evaluate the condition inline, in the html tag, like so:
<option value="{{ i }}" {% if selected %} selected {% endif %}>
This might make for more readable code.

In Django, what's the right way to pre-select a form option tag?

I'm using Django and Python 3.7. I want to create a SELECT menu on my template so I tried this ...
<select id="website_id" name="website_id">
<option value="">Select a website</option>
{% for website in websites %}
<option value="{{ website.id }}" {{ 'selected' if website_id == website.id else '' }}>{{ website.path }}</option>
{% endfor %}
</select>
but I get this error
Could not parse the remainder: ' if website_id == website.id else ''' from ''selected' if website_id == website.id else '''
Its choking on my "if" expression. What's the preferred way to set the "selected" attribute of an option tag?
The real right way is to use a Django form. But if you insist on doing it manually, you need an if tag
{% if website_id == website.id %} selected {% endif %}
The correct syntax is like so:
{% if CONDITION %}A{% endif %}
So in your case, we would implement it like so:
<select id="website_id" name="website_id">
<option value="">Select a website</option>
{% for website in websites %}
<option value="{{ website.id }}" {% if website_id == website.id %}selected{% endif %}>{{ website.path }}</option>
{% endfor %}
</select>
<select name="qf">
<option value="10th" {% if '10th' %} selected {% endif %}>10th</option>
<option value="12th" {% if '12th' %} selected {% endif %}>12th</option>
</select>

select entries from database mysql in dropdown, python flask

I want to select data from database table in MySQL. It is procedure in Python
#app.route('/formworkers.html')
def formworkers():
cursor = mysql.connection.cursor()
cur = cursor.execute("SELECT ID_worker, surname FROM workers")
return render_template('formworkers.html', workers0=cursor.fetchall())
And template in Jinja2
{% extends "layout.html" %}
{% block body %}
{% if session.logged_in %}
<form action="" method=post class=add-worker >
<dl>
<dt>Surname:
<dd><select name="worker0">
{% for ID_pats, surname in workers0 %}
<option value="{{ ID_worker }}">{{ surname }}</option>
{% endfor %}
</select>
<br><br>
<dd><input type=submit value="Submit">
</dl>
</form>
{% endif %}
{% endblock %}
But the dropdown list does not contain data (for example [Ivanov, Petrov, Sidorov]) from the database, it contain values [surname, surname, surname]. Thank you.
The query outputs a result as a list of dictionaries, so when you unpack it in the for loop, you get only a list of keys "ID_worker" and "surname" .
You can change the template like below to access the values :
{% for worker in workers0 %}
<option value="{{ worker.ID_worker }}">{{ worker.surname }}</option>
{% endfor %}

getting data from dynamically generated html form

I am dynamically generating a html page from data in the database(mainly labels retrieved since I'm in the stage of CREATING data to store in the db). I retrieve labels and id's from the database, then store it in a class which I return to jinja2 so that I can then dynamically generate all the labels and input boxes. Here is a snippet:
<div class="dataDiv">
<label class="inputBoxLabels">Device<span style="padding-left: 85px;font-size: 12px;">New</label>
<select id="devices" class="inputBoxes" style="height: 25px;">
{% for key, value in devices.iteritems() %}
{% if deviceID == key %}
<option value="{{ key }}" selected="selected">{{ value }}</option>
{% else %}
<option value="{{ key }}">{{ value }}</option>
{% endif %}
{% endfor %}
</select>
</div>
another example, this time an input box:
{% if inspection.statusDict|length > 0 %}
<select class="inputBoxes" id="ins_' + {{ inspection.insID }} + '" style="height: 25px;">
{% for key, value in inspection.statusDict.iteritems() %}
<option value="{{key}}">{{value}}</option>
{% endfor %}
</select>
{% else %}
<input type="text" class="inputBoxes" id="ins_' + {{ inspection.insID }} + '">
{% endif %}
This is what the select list looks like after is has been populated for visual reference:
Now the problem. I have everything inside a form and I have no idea how to retrieve the data from each input and select when I receive the post since it's all dynamically generated.
I originally thought of using jquery instead and ajax but if possible I'd like to stick to forms
Off the top of my head I think if you're submitting to a Pyramid view via POST you should be able to iterate over request.POST to get whatever was submitted.
Something like and inspect each item
for item in request.POST.keys():
print item + ' - ' + request.POST[item]
I'd have to try it when I get home to a console to confirm.

django template syntax to iterate through two lists

I have the following django template, where as I'm iterating through a list (class_list_overall), I want to use forloop.counter0 as an index in another list (classTimeSlots). It just keeps giving me a TemplateSyntaxError. I have tried the following variations:
{{classTimeSlots.{{forloop.counter0}}}}
{{classTimeSlots.[forloop.counter0]}}
{{classTimeSlots.{forloop.counter0}}}
{{classTimeSlots.(forloop.counter0)}}
{{classTimeSlots.forloop.counter0}}
{% with forloop.counter0 as index%}
<legend>{{ classTimeSlots.index}}</legend>
{% endwith %}
None of which worked. Any suggestions? I'm just a newbie at DJango. I'm using Google App Engine.
Here's the code snippet (I know it's inefficient but I've been trying different things):
{% for class_list in class_list_overall %}
<fieldset> <legend>{{ classTimeSlots.forloop.counter0 }}</legend>
<ul>
<li> <label>First Choice </label>
<select class="dropdown" name="class{{forloop.counter}}1" size="1">
<option value="Click Here to Choose" selected="selected">Click Here to Choose</option>
{% for class in class_list %}
<option>{{class}}</option>
{% endfor %}
</select>
</li>
<li>
<label>Second Choice </label>
<select class="dropdown" name="class{{forloop.counter}}2" size="1">
<option value="Click Here to Choose" selected="selected">Click Here to Choose</option>
{% for class in class_list %}
<option>{{class}}</option>
{% endfor %}
</select>
</li>
</ul>
</fieldset>
{% endfor %}
Short answer: you can't do that.
The template language will not try to determine the value of a variable passed in dot syntax.
It will do a literal lookup of forloop.counter0
1: write a template tag that accepts a variable and a key, and have it return the variable[key]
2: this can most likely be done in the view. Can I see it?
Django doesn't support this - it's deliberately limited. Instead, you should modify your view function to zip the two lists together, and pass that in to the template.
Its possible but not recommendable:
{% for class_list in class_list_overall %}
<fieldset> <legend>
{% for cts in classTimeSlots %}
{% ifequal forloop.counter forloop.parentloop.counter %} {{cts}}
{% endifequal %}
{% endfor %} </legend>
<ul>
<li> <label>First Choice </label>
<select class="dropdown" name="class{{forloop.counter}}1" size="1">
<option value="Click Here to Choose" selected="selected">Click Here to Choose</option>
{% for class in class_list %}
<option>{{class}}</option>
{% endfor %}
</select>
</li>
<li>
<label>Second Choice </label>
<select class="dropdown" name="class{{forloop.counter}}2" size="1">
<option value="Click Here to Choose" selected="selected">Click Here to Choose</option>
{% for class in class_list %}
<option>{{class}}</option>
{% endfor %}
</select>
</li>
</ul>
</fieldset>{% endfor %}
But its better to take list into parent dict:
[class_list_overall[i].update({'label':classTimeSlots[i]}) for i in range(0,len(classTimeSlots))]
And then change above code to:
<legend>
{{ class_list.label }}
</legend>

Categories