I want to display the content of the database from .db file on web framework using flask module. However, only the row title is able to be displayed on the web framework. The content of the database from the .db file couldn't load out on the web framework. Anyone can help me with this? Thanks.
This is my code:
from flask import Flask, render_template
import sqlite3
app = Flask(__name__)
def connect_db(db):
con = sqlite3.connect(db)
return con.cursor()
#app.route('/')
def index():
db ='mcu_aurix_git.db'
cur = connect_db(db)
cur.execute("SELECT * FROM mcu_aurix")
data = cur.fetchall()
return render_template('flask.html', rows=data)
if __name__ == "__main__":
app.run(debug=True)
flask.html:
<table class="table table-hover">
<thead>
<tr>
<th>project</th>
<th>branch</th>
<th>id</th>
<th>number</th>
<th>subject</th>
<th>owner_name</th>
<th>owner_email</th>
<th>owner_username</th>
<th>url</th>
<th>commitMessage</th>
<th>createdOn</th>
<th>lastUpdated</th>
<th>open</th>
<th>status</th>
<th>current_date</th>
</tr>
</thead>
<tbody>
{% for row in rows %}
<tr>
<td>{{row.project_name}}</td>
<td>{{row.branch_id}}</td>
<td>{{row.id_id}}</td>
<td>{{row.num_number}}</td>
<td>{{row.subject_name}}</td>
<td>{{row.owner_name}}</td>
<td>{{row.owner_email}}</td>
<td>{{row.owner_username}}</td>
<td>{{row.url_name}}</td>
<td>{{row.commitMessage_name}}</td>
<td>{{row.num_createdOn}}</td>
<td>{{row.num_lastUpdated}}</td>
<td>{{row.num_open}}</td>
<td>{{row.status_name}}</td>
<td>{{row.current_date}}</td>
</tr>
{% endfor %}
</tbody>
</table>
Is there anything missing in my code? Hopefully anyone can help me on this. Thanks in advance!
You are not passing rows variable to the html page.
return render_template('flask.html', data=data)
You are only passing data variable.
If you want to use rows inside your html page, you need to use
return render_template('flask.html', rows=data)
Also one more thing,
{{row.project_name}}
You cannot get the value of project_name like this, you need to use index value (col. no. starting from 0). Like,
{{row[0]}}
Instead of manually creating <td> for each col value, you can just use the below tbody code.
<tbody>
{% for row in rows %}
<tr>
{% for col in row %}
<td> {{ col }} </td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
Hope it helps!
Related
Hello all I am new to flask I am just creating a basic table with DB data as S.no & Name & filling this with some random data of 10 users , Now I am query Db & displaying this list on HTML page in a table , on the HTML page I have added an extra column which takes input from WTF form Select field with option as YES & NO & Pending now the issues I am getting is on the HTML page select column If I select Yes as option & submit all other below row are getting this value , similarly If I select Pending On first & submit all row get pending How can I fix this kindly pardon my english
# for wtf-forms
class inputform(FlaskForm):
userinput = SelectField(choices=[('Yes'), ('No'),('Pending')])
Submit = SubmitField(label="Click to Submit")
#route
#app.route('/', methods=['GET', 'POST'])
def index():
form = inputform()
dbdata = mydb.query.all()
if form.validate_on_submit():
usernameinput = form.userinput.data
print(f"usernameinput {usernameinput}")
return render_template('index.html', userdata=dbdata, form=form)
On HTML
<form action="" method="post">
{{ form.hidden_tag() }}
<table class="table table-bordered ">
<thead>
<tr>
<th class="">S.No</th>
<th class="">name</th>
<th class="">Select</th>
</tr>
</thead>
<tbody>
{% for x in userdata %}
<tr>
<td>{{loop.index}}</td>
<td>{{x.user_name}}</td>
<td>{{form.userinput}}</td>
</tr>
{% endfor %}
</tbody>
</table>
{{form.Submit()}}
</form>
In my basic web application, when click to "calculate" button there can be two options.
First, there is only one result so I directly show them to the users.
Secondly, there can be more than one result so I need to use table to show my results.
For the first option, I can show my result like below:
<p>Result {{result}}</p>
But I cannot figure out if my "result" parameter is array and how can I show all values of array in the table in my html file.
Any help is appreciated.
You can iterate over your iterable in your template:
Python script:
users = [{"name": "123", "hash": "qwe"},]
#app.route('/index/')
def index_page():
return render_template('index.html', users=users)
Template:
<table>
<thead>
<tr>
<th><span>Hash - Name</span></th>
</tr>
</thead>
<tbody>
{% for user in users %}
<tr>
<td>
<span>{{user['hash']}} - {{user['name']}}</span>
</td>
</tr>
{% endfor %}
</tbody>
</table>
See here for more details about iterating over a loop in jinja2 templater.
You can send your result to render in python script:
#app.route('/')
def index():
return render_template('index.html', result='yes')
And in tempalte:
<p>Result {{ result }}</p>
In browser:
<p>Result yes</p>
My Template is outputting the below. It doesnt pull in any of the queried values, but the page loads fine and doesnt fail, but it doesnt show any of the values.
I double checked the query in a mysqlmonitor, and it pulls 3 records as it should.
<li></li>
In the templates/index.html I have:
{% for blogpost in blogposts %}
<li>{{blogpost[0]}}</li>
{% else %}
<li>no blog posts right now...</li>
{% endfor %}
app.py has this:
import pymysql.cursors
app = Flask(__name__)
connection = pymysql.connect(host='localhost', user='myuser', port=3306, password='mypass', db='mydb', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
#app.route('/', methods=('GET', 'POST'))
def email():
form = EmailForm()
curs = connection.cursor()
curs.execute("SELECT post_title, post_name, YEAR(post_date) as YEAR, MONTH(post_date) as MONTH FROM mydb.wp_posts WHERE post_status='publish' ORDER BY RAND() LIMIT 3")
blogposts = curs.fetchall()
if request.method == 'POST':
return render_template('index.html', form=form, blogposts=blogposts)
if __name__ == '__main__':
app.run()
UPDATE I think my for() is not working correctly, because when i update in the template i get all the data like:
[{u'MONTH': 12, u'YEAR': 2016, u'post_name': u'data is here', u'post_title': u'data is here'},
{u'MONTH': 12, u'YEAR': 2016, u'post_name': u'data is here', u'post_title': u"data is here"}]
How can i access this data in my flask template ?
Thank you so much!
Try finding out what is being sent to the template. Add print(blogposts) to the email function - just below the if request.method == 'POST': line and see what information it gives you.
If blogposts is a list of dictionaries, then you cannot access them by number. You need to use the name of the key. For example, you will need to change blogpost[0] to blogpost['name']. With Flask's templates you can also use the dot notation, so the blogpost name would become blogpost.name.
#app.route('/get', methods=['POST','GET'])
def requestCustomerDataFromTestForm():
data={'id':1, 'name':'Josh'}
return render_template("index.html", data = data)
In index.html
{% if data %}
<h1>{{data['id']}}</h1>
<h1>{{data['name']}}</h1>
{% endif%}
Or.. you can also iterate
<table class="table table-striped" >
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">name</th>
</tr>
</thead>
<tbody>
{% for key, value in data.items() %}
<tr>
<th scope="row">{{ key }}</th>
<td>{{ value }}</td>
</tr>
{% endfor %}
</tbody>
</table>
Or, to display all data with their index
{% if data %}
<p>{{data}}</p>
{% endif %}
I just want to write a table in HTML in Django, where the data is not from Database. It seems django-tables2 is a good package that I can use in Django. However, my data is not from Database, so maybe it's not necessary to use Django model. Here comes my code of view.py and HTML page:
def device_manager_submit(request):
'''Switch manager page'''
ret = rest.send_device_tor(device_name) #data from rest API exist in the form of array of dictronary: [{}, {}, {}]
return HttpResponse(ret) #return data to HTML
I can use for loop in HTML to display this data but I'm not clearly about how to show them:
<tbody>
{% for item in xx %} //I'm not sure
<tr>
<td>111</td> //how to display?
</tr>
{% endfor %}
Does anyone has any example that I can follow to display the data from view.py in HTML page
You don't need to return Django objects to create templates, you can use any data. The render() function allows you to combine context with the regular HttpResponse. You pass it the request which was given to the view calling it, the name of the template you want to render, and then a dictionary of data to provide to the template.
def device_manager_submit(request):
'''Switch manager page'''
ret = rest.send_device_tor(device_name) #data from rest API exist in the form of array of dictronary: [{}, {}, {}]
return render(request, 'some_template.html', {'devices': ret}) #return data to HTML
Assuming that ret contains some objects with a name and description, we can loop through devices like so:
<tbody>
{% for device in devices %}
<tr>
<td>{{ device.name }}</td>
<td>{{ device.description }}</td>
</tr>
{% endfor %}
One way would be to use pandas to load the data, and then use the DataFrame.to_html() to output the data into an html table. See the example below:
import pandas as pd
data = [{'column1': 1, 'column2': 2}]
df = pd.DataFrame(data)
html = df.to_html()
Html will result in:
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>column1</th>
<th>column2</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>1</td>
<td>2</td>
</tr>
</tbody>
</table>
In a Django view this would be:
#api_view(['GET'])
def showData(request):
data = [{'column1': 1, 'column2': 2}]
df = pd.DataFrame(data)
html = df.to_html()
return HttpResponse(html)
Goal: {% for loop %} over a list (using Jinja2) and then print out results {{print}} in a HTML table using Bootstrap.
Problem: List is not printing in the template.
In the view_config, I used query .all() to return a list of all the assessment_results objects. They are returning... I confirmed this via terminal/print debugging. However, the for loop is not returning the values needed to populate a table; as read in Jinja2 tutorial. I don't think I need to use a for loop in the view_config as I have seen others do (see here), but I am new to this and am trying to figure out how these two programs (SQLALCHEMY and Jinja2) interact.
An example from the printout after using .all() mentioned above:
[<Assessment_Result(owner='<User(username ='baseball', firstname ='Jen', lastname ='See', email='girl#aol.com')>', assessment='<Assessment(name='Becoming a Leader', text='better decisions')>')>]
view_config code:
views.py
#view_config(route_name='assessment_results', request_method='GET', renderer='templates/assessment_results.jinja2')
def all_assessment_results(request):
with transaction.manager: # < --- THIS WAS THE ISSUE !
assessment_results = api.retrieve_assessment_results()
if not assessment_results:
raise HTTPNotFound()
return {'assessment_results': assessment_results}
Corresponding Jinja2 template using Bootstrap:
assessment_results.jinja2
<div class="container">
<table class="table table-hover">
<thead>
<tr>
<td> Assessment ID </td>
<td> Assessment </td>
<td> Owner </td>
</tr>
</thead>
<tbody>
<tr>
{% for x in assessment_results %}
<td>{{ x.assessments|e }}</td>
<td>{{ x.owners|e}}</td>
{% else %}
<td><em>no users found</em></td>
{% endfor %}
</tr>
</tbody>
</table>
</div>
You should look at the documentation
http://jinja.pocoo.org/docs/dev/templates/#for
You want to iterate over a dict, so consider using iteritems, itervalues or what ever you want.
Also note that your query will not return a dict, it will return a list or rows that matched.
I am also not sure if the for-else works in jinja. But you should avoid using that anyways.