Displaying data on new page in Python - python

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

Related

Flask BuildError - Could not build URL for endpoint

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

Python - display query results in an HTML table

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

Data table python flask

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>

How to avoid the below error in Python Flask

I am using the below 3 html i.e. Index.html , Results.html and Edit.html
and python code file app.py code is also pasted below.
The save to the DB is working fine and when I retrieve the data for editing and click on Submit I am encountering the below error
"_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s' at line 1")"
Index.html
<h1>Welcome</h1>
<br>
<br>
<form method="POST" action="{{ url_for('index') }}">
Name <input type="text" name="name" />
<br>
Email <input type="email" name="email" />
<br>
CRType <select name = "CRType">
<option value = "New">New</option>
<option value = "Old">Old</option>
</select><br>
<input type="submit" value="Submit">
</form>
Results.html
Add CR
<table border = 1>
{% for user in userDetails %}
<tr>
<td> {{user[3]}} </td>
<td> {{user[0]}} </td>
<td> {{user[1]}} </td>
<td> {{user[2]}} </td>
<td> Edit Profile </td>
</tr>
{% endfor %}
</table>
Edit.html
h1>Welcome to Update Zone</h1>
<br>
<br>
<body>
<form method="POST" action="{{ url_for('Edit') }}">
CR_ID <input type="text" name="CR_ID" value = "{{user[0]}}"/>
<br>
Name <input type="text" name="name" value = "{{user[1]}}"/>
<br>
Email <input type="email" name="email" value = "{{user[2]}}"/>
<br>
<br>
<input type="submit" value="Submit">
</body>
</form>
App.PY
from flask import Flask, render_template, request, redirect
from flask_mysqldb import MySQL
# from flask_table import Table, Col, LinkCol
app = Flask(__name__)
# Configure db
#db = yaml.load(open('db.yaml'))
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
#app.config['MYSQL_PASSWORD'] = 'P#$$w0rd'
app.config['MYSQL_DB'] = 'flaskapp'
mysql = MySQL(app)
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
# Fetch form data
userDetails = request.form
name = userDetails['name']
email = userDetails['email']
CRType = userDetails['CRType']
# CR_ID = userDetails['CR_ID']
cur = mysql.connection.cursor()
# cur.execute("""INSERT INTO users(name, email, CRType) VALUES(%s, %s, % )""",(name, email, CRType)
cur.execute("""INSERT INTO users (name, email, CRType) VALUES (%s, %s, %s)""", (name, email, CRType))
mysql.connection.commit()
cur.close()
return redirect ('/results')
# return redirect('/results')
return render_template('index.html')
#app.route('/results')
def results():
cur = mysql.connection.cursor()
resultValue = cur.execute("SELECT * from users")
if resultValue > 0:
userDetails = cur.fetchall()
# edit = LinkCol('Edit', 'edit', url_kwargs=dict(id='CR_ID'))
return render_template('results.html',userDetails=userDetails)
#app.route('/Edit', methods=['GET', 'POST'])
def Edit():
# request.method == 'GET':
# Fetch form data
# user = request.form
# CR_ID = user['CR_ID']
CR_ID = request.args.get('CR_ID')
name = request.args.get('name')
email = request.args.get('email')
CRType = request.args.get('CRType')
cur = mysql.connection.cursor()
# result= cur.execute("SELECT CR_ID, name, email from users where CR_ID = 1")
result = cur.execute("""SELECT CR_ID, name, email from users where CR_ID = %s""",CR_ID)
# result = cur.execute("Update table users set name=?, email=?, CRType=? where CR_ID = %s", CR_ID)
RV = cur.fetchall()
user = RV[0]
cur.close()
return render_template('Edit.html',user=user)
if __name__ == '__main__':
app.run(debug= True)
Your SQL statements aren't properly formatted. It should be
result = cur.execute("SELECT CR_ID, name, email from users where CR_ID = %s", (CR_ID))

Creating an events manager using Flask and MySQL

I'm a novice Python and Javascript programmer and am currently working on creating an events manager app using Flask and MySQL.
The one page website should allow users to:
Add and view events.
Sort events by date or by category
I can't seem to insert data into my local MySQL database. Each time I open the MySQL workbench to check, the table remains empty.
My questions are:
How do I insert the data from the input tags into MySQL using Flask?
What is the best method to check MySQL if the insertion was successful?
How do I get data from MySQL into the HTML table using Flask on app startup?
The HTML:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<link rel = 'stylesheet' href = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>
<title>Events and Opportunities</title>
</head>
<body>
<div class = 'container'>
<h1>Events and Opportunities</h1>
<table class="table">
<thead>
<tr id = 'tableHeader'>
<th>Date</th>
<th>Category</th>
<th>Title</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<form action = '/' method = 'post'>
<tr id = 'tableInput'>
<td><input type = 'date' name = 'inputDate' id = 'inputDate'></td>
<td><input type = 'text' name = 'inputCategory' id = 'inputCategory' maxlength = '20'></td>
<td><input type = 'text' name = 'inputTitle' id = 'inputTitle' maxlength = '100'></td>
<td><input type = 'text' name = 'inputDescription' id = 'inputDescription' maxlength = '500'></td>
</tr>
</form>
</tbody>
</table>
<button type = 'button' id = 'addButton' class="btn btn-default">Add</button>
</div>
<script src = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script src = 'static/app.js'></script>
</body>
</html>
The Javascript:
$('#addButton').on('click', () => {
if ($('#inputDate').val() === '' || $('#inputCategory') === '' || $('#inputTitle') === '' || $('#inputDescription') === ''){
alert('Please fill in the form.');
}
else{
const valDate = $('<th></th>').text($('#inputDate').val());
const valCategory = $('<th></th>').text($('#inputCategory').val());
const valTitle = $('<th></th>').text($('#inputTitle').val());
const valDescription = $('<th></th>').text($('#inputDescription').val());
const newRow = $('<tr></tr>').append(valDate, valCategory, valTitle, valDescription);
$('#tableInput').before(newRow);
$('#inputDate').val('');
$('#inputCategory').val('');
$('#inputTitle').val('');
$('#inputDescription').val('');
}
})
The Flask code:
from flask import Flask, render_template, request
import mysql.connector
app = Flask(__name__)
cnx = mysql.connector.connect(user='root', password='yunani', host='127.0.0.1', database='test')
cursor = cnx.cursor()
#app.route('/', methods = ['GET', 'POST'])
def index():
return render_template('index.html')
if request.method == 'POST':
date = request.form['inputDate']
category = request.form['inputCategory']
title = request.form['inputTitle']
description = request.form['inputDescription']
cursor.execute('INSERT INTO data (Date, Category, Title, Description) VALUES ({}, {}, {}, {})'.format(date, category, title, description))
cnx.commit()
if __name__ == '__main__':
app.run(debug = True)
The MySQL schema:link to image
Try changing your handler to
def index():
if request.method == 'POST':
date = request.form['inputDate']
category = request.form['inputCategory']
title = request.form['inputTitle']
description = request.form['inputDescription']
cursor.execute('INSERT INTO data (Date, Category, Title, Description) VALUES ({}, {}, {}, {})'.format(date, category, title, description))
cnx.commit()
return render_template('index.html') # don't do this at the top
You are currently returning before checking the call type or talking to the database.

Categories

Resources