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

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")

Related

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/

Save data from a template into a file in django and send an email

I have a template in django that shows some information in a table that has the format of a bill with different fields for the unity price, the description, the total price, etc... and i want to, for example, show a button that saves that table into a file and then send an email with that file attached. I wrote Django in the title because thats what im using. Is that the correct way to do it? to save that "table" into a file and then send an email? or maybe someone has another idea to acomplish the same?
EDIT: This the table that i have in the template, it makes sum multiplications and addings and completes some boxes with those results.:
<div class="row">
<div class="col-xs-12">
<div class="box">
<div id="">
<p id="address">
{{fact.nombre_cliente}}
</p>
<p id= "numero">
{{fact.numero_De_Factura}}
</p>
<div id="logo">
<img id="image" src="{% static 'img/Home/Logo-Exisoft.png' %}" alt="logo" />
</div>
</div>
<div style="clear:both"></div>
<div id="customer">
<div id="datos">
<p id = "direccion">
{{cliente.Direccion}}
</p>
<br>
<p id = "direccion">
{{fact.RI}}
</p>
</div>
<table id="meta">
<tr>
<td class="meta-head">Fecha</td>
<td><textarea id="date">{{fact.fecha_factura}}</textarea></td>
</tr>
<tr>
<td class="meta-head">CUIT</td>
<td><div class="due">{{cliente.CUIT}}</div></td>
</tr>
</table>
</div>
<table id="items">
<tr>
<th class="tipo">Tipo de Factura</th>
<th class="descripcion">Descripcion</th>
<th>Precio</th>
</tr>
<tr class="item-row">
<td><div><textarea>{{fact.tipo_Factura}}</textarea></div></td>
<td class="description"><textarea>{{fact.descripcion}}</textarea></td>
<td><span class="price">$ {{fact.importe_sin_iva}}</span></td>
</tr>
</table>
<table id="totales">
<tr>
<td class="total-line">Subtotal</td>
<td class="total-value"><div id="subtotal">$ {{fact.importe_sin_iva}}</div></td>
</tr>
<tr>
<td class="total-line">Iva</td>
<td class="total-value"><div id="total">$ {{iva}}</div></td>
</tr>
<tr>
<td class="total-line">Precio Pagado</td>
<td class="total-value"><textarea id="paid">$ {{total}}</textarea></td>
</tr>
<tr>
<td class="total-line balance">Balance Due</td>
<td class="total-value balance"><div class="due">$875.00</div></td>
</tr>
</table>
<div id="terms"></div>
</div><!-- /.box-body -->
</div><!-- /.box -->
</div>
This is what i need to send in an email. I didn't try anything yet because i donĀ“t know what the best approach is. Should i save this table in a file and then print send that file? Is there a way to capture the hole thing and past it in an email and sent it without saving it?
Thank you very much.
There should be no reason to store the the file to be attached as an actual file on the server. Have a look at https://docs.djangoproject.com/en/dev/topics/email/
It seems EmailMessage.attachments define the files to be attached in terms of (filename, content, mimetype) triples. Use EmailMessage.attach() to attach your template rendered as a string (along with a proper file name and mime type), see render_to_string(). Then use EmailMessage.send() to send the email.
You should do this in your view. If using model based views, say FormView, you should do it in your form_valid() method. See also http://ccbv.co.uk/projects/Django/1.6/django.views.generic.edit/FormView/

Linking python variables to a HTML script

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)

Google App Engine Python HTML Table

I am trying to create a table within a Google App Engine Application where the background color in a table changes periodically based on input. Does anyone know how to accomplish this?
Here is my code:
self.response.out.write("""
<img src="/images/resistor.png" width = "150">
<table border = "1">
<tr height="150" >
<td bgcolor="%s" width="35"> </td> <td bgcolor="%s" width="35"> </td> <td bgcolor="%s" width="35"> </td> <td bgcolor="%s" width="35"> </td> %(Red,Blue,Black,Green)
</tr>
</table>
<form action="/sign" method="post">
<div><textarea name="content" rows="3" cols="60"></textarea></div>
<div><input type="submit" value="Sign Guestbook"></div>
</form> """)
self.response.out.write('</pre></body></html>')
For example the Red,Green... Colors in %( ) will be variables that will change so at one point they all may be Red or Blue and Yellow.
That type of string-formatting is deprecated. Please use the .format() method in new code. Example:
self.response.out.write("""
<img src="/images/resistor.png" width = "150">
<table border = "1">
<tr height="150" >
<td bgcolor="{}" width="35"> </td>
<td bgcolor="{}" width="35"> </td>
<td bgcolor="{}" width="35"> </td>
<td bgcolor="{}" width="35"> </td>
</tr>
</table>
<form action="/sign" method="post">
<div><textarea name="content" rows="3" cols="60"></textarea></div>
<div><input type="submit" value="Sign Guestbook"></div>
</form> """.format( ('Red','Blue','Black','Green') ))
self.response.out.write('</pre></body></html>')
And for anything beyond the basic have a look at using templates. Examples of templating systems are Jinja2 and Django Templates.

Categories