I have a question regarding mysql db python table in Bootstrap.
My question is my data is not shown in the table. I can see it gets data because of when I add row in mysql db with data the table increases.
app.py code:
#app.route('/dashboard')
#is_logged_in
def dashboard():
#create cursor
cur = mysql.get_db().cursor()
#Get data
result = cur.execute("SELECT * FROM test")
data=cur.fetchall()
if result > 0:
return render_template('dashboard.html', data=data)
else:
msg = 'No DOC Found'
return render_template('dashboard.html', msg=msg)
#close connection
cur.close()
return render_template('dashboard.html' )
.html
<table class="table table-striped">
<tr>
<th>data1</th>
<th>data2</th>
</tr>
{% for test in data%}
<tr>
<td>{{test.rdno}}</td>
<td>{{test.ipno}}</td>
{% endfor %}
</tr>
</table>
instead of
<td>{{test.rdno}}</td>
<td>{{test.ipno}}</td>
do this
<td>{{test[0]}}</td>
<td>{{test[1]}}</td>
Related
I have the following code in my Python project:
<table class="table table-striped">
<tr>
<th>Card Number</th>
<th>Card Name</th>
<th>Card Rarity</th>
<th>Card Quantity</th>
</tr>
{% for card in card_data %}
<tr>
<td>{{card.card_prefix}}</td>
<td>{{card.card_name}}</td>
<td>{{card.card_rarity}}</td>
<td>{{card.card_quantity}}</td>
</tr>
{% endfor %}
</table>
Is there a way to update the quantity to -1 or +1 on a button that only updates one row of the SQL database?
The current code in my main page is:
#app.route('/lob')
def lob():
session.clear()
cur = mysql.connection.cursor()
current_set = 'LOB'
session['set_selected'] = True
session['current_set'] = current_set
result = cur.execute("SELECT * FROM card_list WHERE card_set =%s", [current_set])
card_data = cur.fetchall()
if result > 0:
return render_template('/Booster Packs/lob.html', card_data=card_data)
else:
flash('Set Not Found!', 'danger')
return render_template('/Booster Packs/lob.html')
I can update the question with more information if needed, I'm just not sure how to go about how to select the value to update given the table.
Sorry for the bad English, it is not my first language.
It is necessary to obtain information from the selected cell from the html file and then work with it in views.py. Is it possible and how to do it? Thank you in advance!
<tbody>
{% for element in qz %}
<tr>
<td class="counterCell"></td>
<td style="display: none">{{ element.0 }}</td> <!-- information is needed for this cell when it is selected -->
<td>{{ element.1 }}</td>
<td>{{ element.2 }}</td>
<td><span class="glyphicon glyphicon-trash"></span></td>
</tr>
{% endfor %}
</tbody>
views.py:
cursor = connection.cursor()
cursor1 = connection.cursor()
cursor2 = connection.cursor()
cursor.execute(
"SELECT sites.site_title, sites.url FROM sites, my_sites, auth_user WHERE auth_user.id = my_sites.id_user AND sites.id = my_sites.id_site AND auth_user.id =" + str(
request.user.id))
cursor1.execute(
"SELECT sites.site_title, sites.url FROM sites, my_sites, auth_user WHERE auth_user.id = my_sites.id_user AND sites.id = my_sites.id_site AND auth_user.id =" + str(
request.user.id))
cursor2.execute(
"SELECT sites.id, sites.site_title, sites.url FROM sites, my_sites, auth_user WHERE auth_user.id = my_sites.id_user AND sites.id = my_sites.id_site AND auth_user.id =" + str(
request.user.id))
q = [str(row[0]) for row in cursor.fetchall()]
z = [str(row[1]) for row in cursor1.fetchall()]
x = [str(row[0]) for row in cursor2.fetchall()]
qz = [(x[i], q[i], z[i]) for i in range(len(q))]
return render(request, 'main/my_newsagent.html', {'qz': qz})
That what you showing is a template. Template receive a data from a view function.
So that function located in a views.py returning that template, with interpolated data (rendered final html). So in may be in context or in other variable.
I've got what should be a very simple python code to select some data from my database
#app.route('/studentsearch', methods = ['POST', 'GET'])
def searchstudent():
""" Displays the student search page for the site """
cursor = mydb.cursor()
cursor.execute ("SELECT * FROM student")
all_students = cursor.fetchall()
cursor.close()
return render_template('studentsearch.html', all_students = all_students)
But when I go to render the HTML page i get werkzeug.routing.BuildError: Could not build url for endpoint 'studentsearch'. Did you mean 'newstudent' instead?
My table is also pretty straight forward as well...
<table>
<thread>
<tr>
<th>Student ID:</th>
<th>First Name:</th>
<th>Last Name:</th>
<th>Click to View Student Details</th>
</tr>
</thread>
<tbody>
{% for each_result in all_students %}
<tr>
<td>{{ each_result[0] }}</td>
<td>{{ each_result[1] }}</td>
<td>{{ each_result[2] }}</td>
<td>CLICK HERE!!!</td>
</tr>
{% endfor %}
</tbody>
</table>
What's going on? 'newstudent' isn't even mentioned within the python or HTML??
As requested here's the code that the 'newstudent' appears to be coming from:
def newstudent():
"""Displays the new student page for the site"""
return render_template('newstudent.html')
#app.route('/process_newstudent', methods = ['POST', 'GET'])
def process_newstudent():
""" Processes the data from the new student course """
if request.method == 'POST':
first_name = request.form['firstname']
last_name = request.form['lastname']
year_began = request.form['yearbegan']
try:
cursor = mydb.cursor()
cursor.execute ("INSERT INTO student (first_name, last_name, year_began) VALUES ('{}','{}','{}');".format((first_name.title()), (last_name.title()), year_began))
mydb.commit()
cursor.close()
except mysql.connector.Error as err:
cursor.close()
return failure('newstudent', f"Error message: {err}. Student not added")
else:
cursor = mydb.cursor()
cursor.execute ("SELECT * FROM student")
student_success = cursor.fetchall()
cursor.close()
return render_template('newstudent_success.html', student_success = student_success)
else:
request.method == 'GET'
return render_template('newstudent.html')
Are you trying to build a dynamic URL somewhere in your application code or HTML code using the url_for function?
If you are, then I think what might be happening is that you're passing the parameter 'studentsearch' to that function instead of 'searchstudent' (url_for builds endpoints using the view function name, not the endpoint name). E.g. within an HTML template the URL in question would be built like this:
Search
Firstly, here is what I'm using : Python 3, Flask, PostgreSQL, a bootstrap theme.
What I want to do ?
I have a table with near 34000 values. The problem, the page is loading very slowly cause of the number of values. How can I improve performance using Server-Side processing (or other) with Python and Flask ?
Code :
Here is a part of my main.py :
#login_required
def home():
connect() # Connect to the PG database
connect.cur.execute("""SELECT * FROM test""")
test_execute = connect.cur.fetchall()
count_equipement()
return render_template('index.html',
value=test_execute,
value2=count_equipement.nb_equipement,
value3=check_ok.nb_ok,
value4=check_ko.nb_ko)
test_execute fetch all the values of my table. In my index.html here is how I show the data :
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>First</th>
<th>Second</th>
<th>Third</th>
<th>Fourth</th>
<th>Fifth</th>
</tr>
</thead>
<tfoot>
<tr>
<th>First</th>
<th>Second</th>
<th>Third</th>
<th>Fourth</th>
<th>Fifth</th>
</tr>
</tfoot>
<tbody>
{% for row in value %}
<tr>
<td>{{row[0]}}</td>
<td>{{row[1]}}</td>
<td>{{row[2]}}</td>
<td>{{row[3]}}</td>
<td>{{row[4]}}</td>
</tr>
{% endfor %}
</tbody>
</table>
In my bootstrap theme, there is a .js to paginate correctly the table. Here is the result with 8 values :
How can I do to do a server-side processing ? I've already check this link but I don't think I can apply this in my case...
Here is the answer of my question. (comments are in french)
#app.route('/stack', )
#app.route('/stack/<int:page>', defaults={'page': 1})
#login_required
def stack(page):
"""
retourne la page 1 par défaut, puis change selon le numéro /4 par ex
"""
connect()
connect.cur.execute("""SELECT COUNT(*) FROM mydatabase""")
count = connect.cur.fetchall()
count = count[0][0]
check.count()
PER_PAGE = 10
offset = ((int(page)-1) * PER_PAGE)
connect.cur.execute("""SELECT *
FROM mydatabase
ORDER BY table1 OFFSET %s LIMIT %s""" % (offset, PER_PAGE))
solutions = connect.cur.fetchall()
# Display a 409 not found page for an out of bounds request
if not solutions and page != 1:
return(render_template('404.html', errmsg="Requested page out of bounds"), 404)
pagination = Pagination(page, PER_PAGE, count)
return(render_template('index.html',
r=request,
value=solutions,
pagination=pagination))
def url_for_other_page(page):
"""
récupère l'url
"""
args = request.view_args.copy()
args['page'] = page
return url_for(request.endpoint, **args)
app.jinja_env.globals['url_for_other_page'] = url_for_other_page
I want to display each row from a database in a <td> in the following index.html page:
$def with(items)
<h1></h1>
<br/>
<br>
<table border="1">
<tr>
<th>Name</th>
<th>address</th>
<th>number</th>
</tr>
<tr>
<td>//want name here</td>
<td>//address here</td>
<td>//number here</td>
</tr>
</table>
app.py code:
import web
import MySQLdb
urls = (
'/', 'Index'
)
app = web.application(urls, globals())
render = web.template.render('templates/')
class Index(object):
def GET(self):
return render.hello_form()
def POST(self):
form = web.input(name="a", newname="s", number="d")
conn = MySQLdb.connect(host= "localhost", user="root", passwd="", db="testdb")
x = conn.cursor()
x.execute("SELECT * FROM details WHERE name = '%s'" % (form.name))
conn.commit()
items = x.fetchall()
for row in items:
conn.rollback()
conn.close()
return render.index(items)
if __name__ == "__main__":
app.run()
items (results fetched) will be an array of tuples. Return the array as it is as you want to display whole data on the html and HTML is only rendered once.
app.py code
import web
import MySQLdb
urls = (
'/', 'Index'
)
app = web.application(urls, globals())
render = web.template.render('templates/')
class Index(object):
def GET(self):
return render.hello_form()
def POST(self):
form = web.input(name="a", newname="s", number="d")
conn = MySQLdb.connect(host= "localhost", user="root", passwd="", db="testdb")
x = conn.cursor()
x.execute("SELECT * FROM details WHERE name = '%s'" % (form.name))
items = x.fetchall()
conn.close()
return render.index(items) // return the array of results as a whole
if __name__ == "__main__":
app.run()
On index.html
$def with(items)
<h1></h1>
<br/>
<br>
<table border="1">
<tr>
<th>Name</th>
<th>address</th>
<th>number</th>
</tr>
$for row in items:
<tr>
<td>$row[0]</td>
<td>$row[1]</td>
<td>$row[2]</td>
</tr>
</table>
Iterate over the items and display them