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>
Related
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!
I am creating a shopping cart as a part of the application I'm building.
I am trying to figure out how to add a form submission to a dictionary (I think this is what I need to do).
So for example this is what the page would look like(This is just test data).
Upon Clicking the add button I want the item name and price to populate in the Orders table to the right of the Pricing table(To start off). Once all orders have been added I'd click the Order button and that will order the added items in some type of list to the database using sqlalchemy. Now I feel strongly and I may be wrong that upon submitting form using add button that the form needs to be added to a dictionary. I just don't know how to save that dictionary and where that dictionary should be stored? Here is my code as of now.
routes.py
I tried putting the dictionary with in the route function but a single instance is created on each submission. So nothing is really being saved to dictionary.
#app.route('/equipment', methods=['POST', 'GET'])
def equipment():
form = OrderEquipmentForm()
eq = equipment_prices
# Tried to store forms in this dictionary but it look like a new instance
# is created on every form submission
ordersss = {}
if form.validate_on_submit():
ordersss[form.Type.data] = form.Price.data
print(form.Type.data, form.Price.data)
print(ordersss)
return redirect(url_for('equipment'))
return render_template('equipment.html', name='equipment', eq=eq, form=form)
#app.route('/equipment/cart', methods=['GET, POST'])
def cart():
return render_template('cart.html', name='cart')
Forms.py
Not sure if there needs to be function with in the actual form that adds the values to a dictionary
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
class AddEquipmentForm(FlaskForm):
Type = StringField('Type of Equipment',DataRequired())
Price = StringField('Price',DataRequired())
submit = SubmitField('Add equipment')
class OrderEquipmentForm(FlaskForm):
Type = StringField()
Price = StringField()
Order = SubmitField('Order')
# Should Dictionary go here?
# Not sure
def dict():
dict = {}
dict[Type] = Price
equipment.html
I would like to loop the element of the dictionary with in the Orders Table, if a dictionary is needed.
{% extends 'base.html' %}
{% block content %}
<div class="row">
<div class="col-6-sm">
<h1>Pricing</h1>
<table class='border'>
<thead class='border'>
<th style="width:200px;">Equipment</th>
<th style="width:200px; text-align:center;">Price</th>
<th></th>
</thead>
{% for quip in eq %}
<form method="post">
{{ form.hidden_tag() }}
<tr class ='border'>
<td>{{ quip }}</td>
<td style="text-align:center;"> <strong>${{ eq[quip] }}</strong></td>
<!-- Here I'm adding StringFields from the form but hiding them so they aren't displayed so I can submit the data somehow, hopefully to a dictionary. -->
<td style="display:none;">{{ form.Type(value=quip)}}</td>
<td style="display:none;">{{ form.Price(value=eq[quip]) }}</td>
<td><button class='btn btn-primary' type="submit">Add</button></td>
</tr>
</form>
{% endfor %}
</table>
</div>
<div class="col-6-sm">
<h1>Orders</h1>
<table>
<!-- This is where a loop of the dictionary elements of the items added would go -->
<tr>
<td></td>
<td></td>
</tr>
<button style='float:right' type="button" name="button" class='btn btn-info'>Order</button>
</table>
</div>
</div>
{% endblock %}
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 am trying to paginate data coming from backend using flask_paginate. I followed, https://pythonhosted.org/Flask-paginate/ to get it implemented.
My view -
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="utf-8" />
<title>AT - Monitoring System</title>
</head>
<body>
{{ pagination.info }}
{{ pagination.links }}
<table id="myTable">
<thead>
<tr>
<th>Sector ID</th>
<th>Username</th>
<th>Password</th>
<th>Camera Name</th>
<th>Camera ID</th>
<th>Recording status</th>
</tr>
</thead>
<tbody>
{% for each in response %}
<tr>
<td>{{ loop.index + pagination.skip }}</td>
<td>{{each[0]}} </td>
<td>{{each[1]}} </td>
<td>{{each[2]}}</td>
<td>{{each[3]}}</td>
<td> {{each[4]}}</td>
<td>{{each[5]}}</td>
</tr>
{% endfor %}
</tbody>
</table>
{{ pagination.links }}
</body>
</html>
Python Code -
APP = flask.Flask(__name__)
#APP.route('/', methods=['GET', 'POST'])
def index():
""" Displays the index page accessible at '/'
"""
search = False
q = request.args.get('q')
if q:
search = True
page = request.args.get('page', type = int, default = 1)
pagination = Pagination(page=page, total=len(Backend()), search=search, record_name='response')
if request.method == 'GET':
return flask.render_template('index.html',
response = data,
pagination = pagination
)
if __name__ == '__main__':
data = Backend()
Thread(target=main_loop).start()
APP.debug=True
APP.run(port=63000)
I tried to find documentation which shows me the usage of pagination.skip(), but can't find anything. On removing this function, I see the no. of pages on my browser, but on content is not displayed as per the page nos. There is definitely something, I am missing big time. The other examples online are very different to the example mentioned in https://pythonhosted.org/Flask-paginate/