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
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.
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
So, I have the below web app in Python which should return the info about students (ID, Name, Last name) from a custom table in MSSQL:
from flask import Flask, render_template, redirect, url_for, request
from student import Student, students
app = Flask(__name__)
#app.route("/", methods=["GET", "POST"])
def students_page():
if request.method == "POST":
new_student_id = request.form.get("student-id", "")
new_student_name = request.form.get("name", "")
new_student_last_name = request.form.get("last-name", "")
new_student = Student(name=new_student_name, last_name=new_student_last_name, student_id=new_student_id)
students.append(new_student)
return redirect(url_for("students_page"))
return render_template("index.html", students=students)
#app.route("/about")
def about():
return render_template("about.html")
if __name__ == "__main__":
app.run(debug=True)
Here is my Student class:
import pyodbc
students = []
conn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
"Server=localhost;"
"Database=ERPBasic;"
"Trusted_Connection=yes;")
sql = '''SELECT Student_id, Name, Last_name FROM MyT'''
cursor = conn.cursor().execute(sql)
for row in cursor.fetchall():
students.append(row)
class Student:
school_name = "Springfield Elementary"
def __init__(self, name, last_name, student_id):
self.name = name
self.last_name = last_name
self.student_id = student_id
students.append(self)
def __str__(self):
return "Student " + self.name
def get_name_capitalize(self):
return self.name.capitalize()
def get_school_name(self):
return self.school_name
Somehow, when I run the web app on my localhost, the table does not display the query results within the table, but only 4 (four) empty rows and I would like to display the results from the query which is the following:
[(1, 'Clarissa', 'Simpson'), (2, 'Gil', 'Kennedy'), (3, 'Owen', 'Willson'), (4, 'Sylvia', 'Burge')]
Here is my HTML table:
<div class="page-header">
<h1>All Students</h1>
</div>
<div class="row">
<div class="col-md-12">
<table class="table table-striped">
<thead>
<tr>
<th>Student ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for student in students %}
<tr>
<td>{{ student.student_id }}</td>
<td>{{ student.name }}</td>
<td>{{ student.last_name }}</td>
<td>
<button class="btn btn-primary btn-sm">Edit</button>
<button class="btn btn-danger btn-sm">Delete</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
What am I missing here? Thanks
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>