Linking python variables to a HTML script - python

I've written a Python 3.2 script to select 10 random questions out of a list of 18, having extracted them from a SQLite 3 database. The script works fine, but I now want to render this using HTML - I know how to make question boxes in HTML, but not how to get the asked question to print, in the place of a "question 1" placeholder.
HTML code below:
def PrintGame():
print( """
<html>
<div id = "textbody">
<h2>Quiz</h2>
<form method="post" action="quiz.cgi">
<table border="0">
<tr>
<td>Question 1:</td>
<td><input type="text" name="A1"/></td>
</tr>
<tr>
<td>Question 2:</td>
<td><input type="text" name="A2"/></td>
</tr>
<tr>
<td>Question 3:</td>
<td><input type="text" name="A3"/></td>
</tr>
<tr>
<td>Question 4:</td>
<td><input type="text" name="A4"/></td>
</tr>
<tr>
<td>Question 5:</td>
<td><input type="text" name="A5"/></td>
</tr>
<tr>
<td>Question 6:</td>
<td><input type="text" name="A6"/></td>
</tr>
<tr>
<td>Question 7:</td>
<td><input type="text" name="A7"/></td>
</tr>
<tr>
<td>Question 8:</td>
<td><input type="text" name="A8"/></td>
</tr>
<tr>
<td>Question 9:</td>
<td><input type="text" name="A9"/></td>
</tr>
<tr>
<td>Question 10:</td>
<td><input type="text" name="A10"/></td>
</tr>
<tr>
<td><input type="submit" value="Submit Answers"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
""")
Just to clarify, I want to replace the "Question n"-type things with the questions pulled from the SQLite 3 database. The questions are loaded into QASKEDN variables (where N is replaced by the question number).

Sounds like you just want string formatting, but with a flexible format string/variable.
I haven't checked, but something like this perhaps?
def PrintGame():
htmlquestions = []
for question in QASKEDN:
htmlquestions.append("""
<tr>
<td>{} :</td>
<td><input type="text" name="A1"/></td>
</tr>""".format(question))
html = ("""
<html>
<div id = "textbody">
<h2>Quiz</h2>
<form method="post" action="quiz.cgi">
<table border="0">"""
+ "".join(htmlquestions) +
""" </table>
</form>
</div>
</body>
</html>
""")
Update: now with opening triple double quote for the last lines.

You might want to check out Jinja - a templating language for python.
In your case your Jinja template should look something like
template_string = """
<html>
...
{% for question, name in questions %}
<tr>
<td>{{question}}</td>
<td><input type="text" name="{{name}}"/></td>
</tr>
{% endfor %}
...
</html>
"""
Then you load the template string from your code and call the rendering function passing it your data (in this case a list of tuples containing the question and name)
question_list = [("Q1", "name1"), ("Q2", "name2"), ...]
template = Template(template_string)
template.render(questions=questions_list)

Related

I am unable to get round toggle in my django template

I have a table which contains for loop and if tag using jinja this table shows some data but in last column I want round toggle button but I only get a checkbox, I am unable to find the error please help me.
<tbody>
{%for student in students%}
{%if user.staff.class_coordinator_of == student.division and user.staff.teacher_of_year == student.year%}
<tr>
<td style="color:white;">{{student.user.first_name}}</td>
<td style="color:white;">{{student.user.last_name}}</td>
<td style="color:white;">{{student.year}}</td>
<td style="color:white;">{{student.division}}</td>
<td style="color:white;">{{student.batch}}</td>
<td>
<label class="switch ">
<input type="checkbox" id="" value="" checked>
<span class="slider round"></span>
</label>
</td>
</tr>
{% endif %}
{%endfor%}
</tbody>
OUTPUT
Output Image
You should use radio button instead of checkbox so, it should be type="radio".
<input type="radio" id="" value="" checked>

How to count rows from a html table web2py

actually i have a table in the html and i want to know how i can get like tabe.rows.count on python in web2py
here is my code:
<table id="TablaMateriales" name="TablaMateriales" class=" table table-responsive order-list">
<thead>
<tr class="table-light">
<td>Item</td>
<td>Descripcion</td>
<td>Unidad</td>
<td>Cantidad</td>
<td>Proveedor</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="number" name="Item0" class="form-control" style="width:45px" value="1" disabled />
</td>
<td>
<input type="text" name="Unidad0" style="width:100px" class="form-control"/>
</td>
<td>
<input type="number" min="0" id="Cantidad0" name="Cantidad0" style="width:75px" value="0" class="form-control" onFocus="this.select()" onsubmit="if(this == ''){$this.val('0');}"/>
</td>
<td>
<input type="text" name="Proveedor0" style="width:250px" class="form-control"/>
</td>
</tr>
</tbody>
</table>
and code behind:
def crearCotizacion():
materialesT = request.vars.get('TablaMateriales')
rowsCount = materialesT.rows.count
return dict(rowsCount = rowsCount)
Thank you!
It seems like you are trying to access a client side element ('TablaMateriales') on the server side. You can only do that if you explicitly pass the element back to the server.
And then you would need to manipulate it using something like http://web2py.com/books/default/chapter/29/05/the-views#Server-side-DOM-and-parsing
You could just count the number of rows using JavaScript from inside the view: JavaScript to get rows count of a HTML table

Change the value of selection box Selenium

Option 1 is selected automatically from HTML which is equal to 10.
This is the HTML:
<form>
<table>
<tr>
<th>Name:</th>
<td><input id="search_term" /></td>
</tr>
<tr>
<th>Page size:</th>
<td>
<select id="page_size">
<option>4</option>
<option selected>10</option>
<option>20</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" id="search" value="Search" />
</td>
</tr>
</table>
</form>
I tried running:
js = "document.getElementById('page_size').options[1].text ='1000';"
# js = "document.getElementById('page_size').options[1].text ='1000'"
driver.execute(js)
I get KeyError when i execute js. So I tried doing it the Python way, however, nothing happens:
x = driver.find_element_by_xpath('//*[#id="page_size"]/option[2]')
x.clear()
x.send_keys(1000)
this is link i am testing on link
1:'http://example.webscraping.com/places/default/search'
As you want to change the option elements text, I just tested this piece of javascript using jsfiddle and it works, try using "innerText" instead of "text":
document.getElementById('page_size').options[1].innerText = "1000";
Link to jsfiddle: https://jsfiddle.net/z1omaue3/

Python Flask collapsible/expandable dynamic table

I am building a table in flask with rows that are collapsible. A row may have several elements underneath it that will all collapse on clicking. It works fine if I just hardcode values but when I am populating the table using a loop with data from a python dictionary, it does not work. The first row's first child collapses instead of all the correct row's children collapsing. Below should be sufficient code to reproduce the issue.
elements is a dictionary where key is a string and value is a list of tuples.
<table>
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>E</th>
</tr>
</thead>
{%for k, v in elements.items()%}
<tbody>
<tbody class="labels">
<tr>
<td colspan="5">
<label for="i">{{k}}</label>
<input type="checkbox" name="i" id="i" data-toggle="toggle">
</td>
</tr>
</tbody>
{%for desc in v%}
<tbody class="hide">
<tr>
<td>{{desc[0]}}</td>
<td>{{desc[1]}}</td>
<td>{{desc[2]}}</td>
<td>
<button>trigger</button>
</td>
<td>{{desc[3]}}</td>
</tr>
</tbody>
{% endfor %}
</tbody>
{% endfor %}
<script>
$(document).ready(function() {
$('[data-toggle="toggle"]').change(function(){
$(this).parents().next('.hide').toggle();
});
});
</script>
<label for="i">{{k}}</label>
<input type="checkbox" name="i" id="i" data-toggle="toggle">
Accidentally wasn't changing the for, name, id fields.
Needed to update those as variables as well so looks like
<label for={{k}}>{{k}}</label>
<input type="checkbox" name={{k}} id={{k}} data-toggle="toggle">

Python: How to insert a line in a multi-line string?

I'm trying to make a simple website demo and I have some trouble editing the html using python. The following is the string I defined to store the html (not complete because it's too long). I want to write a function that will throw a error under a certain condition, but I don't know how to insert a line in the string "page".
page="""
<html>
<head>
<title>Sign up</title>
<style type="text/css">
.label {text-align: right}
.error {color: red}
</style>
</head>
<body>
<h2>Sign up</h2>
<form method="post">
<table>
<tr>
<td class="label">
Username
</td>
<td>
<input type="text" name="username" value="">
</td>
<td class="error">
</td>
</tr>
<tr>
<td class="label">
Password
</td>
<td>
<input type="password" name="password" value="">
</td>
<td class="error">
</td>
</tr>
I want to insert the line "There is an error" in the blank between these two lines:
<td class="error">
</td>
Note there are two of this group in the string. How can I insert "There is an error" in the first group using Python? Thanks.
python uses C style format strings.
page="""<html>
......
<td class="error">
%s
</td>
</tr>""" % "There was an error"
alternatively, you can use python string.format as
"fooo {x}".format(x="bar").
see (https://docs.python.org/2/library/string.html);
jinja is an excellent template engine if you've got the time. Genshi (https://genshi.edgewall.org/wiki/GenshiTutorial) is worth looking into as well.
for Jinja2:
pip install Jinja2
in python
from jinja2 import Template
page = Template("""<html> ....
<td class="error">{{x}}</td>
""")
page.render(x="There was an error")

Categories