Basically in application i am connecting to my sql database and trying to retrieve results for the inputs given by user which are AGE,SEX and ADMITTING DIAGNOSIS CODE.
I am able to give user input for both AGE and SEX and get the required results but when i give user input for AGE, SEX and ADMITTING_DIAGNOSIS_CODE my webpage returns NONE values.
Python code:
import MySQLdb
from flask import Flask, render_template, request
from flask.ext.mysqldb import MySQL
app = Flask(__name__)
db = MySQLdb.connect("127.0.0.1","root","","health" )
#app.route("/", methods = ['GET','POST'])
def home():
return render_template('home.html')
#app.route("/value", methods = ['GET','POST'])
def Authenticate():
cursor = db.cursor()
AGE = request.form['AGE']
SEX = request.form['SEX']
ADMITTING_DIAGNOSIS_CODE = request.form['ADMITTING_DIAGNOSIS_CODE']
#DIAGNOSIS_CODE_1= request.args['DIAGNOSIS_CODE_1']
sql = 'select avg(LENGTH_OF_STAY),avg(TOTAL_CHARGES),(select count(*) from health where AGE = %s and SEX = %s and ADMITTING_DIAGNOSIS_CODE = %s and DISCHARGE_STATUS = "A")/(count(*))*100 as alive,(select count(*) from health where AGE = %s and SEX = %s and ADMITTING_DIAGNOSIS_CODE = %s and DISCHARGE_STATUS = "B")/(count(*))*100 as dead from health where AGE = %s and SEX = %s and ADMITTING_DIAGNOSIS_CODE = %s'
entries = []
cursor.execute(sql,(AGE,SEX,ADMITTING_DIAGNOSIS_CODE,AGE,SEX,ADMITTING_DIAGNOSIS_CODE,AGE,SEX,ADMITTING_DIAGNOSIS_CODE,))
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
entries.append(dict([('avg(LENGTH_OF_STAY)',row[0]),
('avg(TOTAL_CHARGES)',row[1]),
('dead',row[3]),
('alive',row[2])
]))
return render_template('show_entries.html', entries=entries)
if __name__ == "__main__":
app.debug = True
app.run()
HTML CODE:
<html>
<head>
<title> Welcome</title>
</head>
<body>
<h1> Hello World!!!!</h1>
<form action="/value" method="post" enctype ="multipart/form-data">
<div>Enter the Age <input type="text" name="AGE" style="border: 1px solid black"></div>
<div>Enter the Sex <input type="text" name="SEX" style="border: 1px solid black"></div>
<div>Enter the code <input type="text" name="ADMITTING_DIAGNOSIS_CODE" style="border: 1px solid black"></div>
<div><input type="submit" value=" GO"></div>
</form>
</body>
</html>
<html>
<head>
<title> Welcome</title>
</head>
<body>
<form action="/value" method="get" enctype ="multipart/form-data">
<table style="border: 1px solid black">
<tbody>
<tr>
<th width="35%" style="background-color: #CCFFCC; margin: 5px">Length of stay</th>
<th style="background-color: #CCFFCC; margin: 5px">Total charge</th>
<th style="background-color: #CCFFCC; margin: 5px">Alive</th>
<th style="background-color: #CCFFCC; margin: 5px">Dead</th>
</tr>
{% for entry in entries %}
<tr>
<td>{{ entry['avg(LENGTH_OF_STAY)'] }}</td>
<td>{{ entry['avg(TOTAL_CHARGES)'] }}</td>
<td>{{ entry['alive'] }}</td>
<td>{{ entry['dead'] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</form>
</body>
</html>
OUTPUT:
Length of stay Total charge Alive Dead
None None None None
Related
Been struggling for weeks now with this issue, starting to feel like I will never solve it.
I have these methods under my model.
def sfget_totals(self):
return self.agent_sale.filter(Date_created__range=["2022-03-01","2022-04-02"]).count()
def sfget_confirmed(self):
return self.agent_sale.filter(State="Confirmed",Date_created__range=["2022-03-01","2022-04-02"]).count()
def sfget_debi(self):
return self.agent_sale.filter(AcknowledgeQA=True,State="Confirmed",Debi_status="Accepted",Date_created__range=["2022-03-01","2022-04-02"]).count()
def sfget_requested(self):
return self.agent_sale.filter(Debi_status="Requested",Date_created__range=["2022-03-01","2022-04-02"]).count()
def sfget_cancelled(self):
return self.agent_sale.filter(State="Cancelled",Date_created__range=["2022-03-01","2022-04-02"]).count()
def sfget_pending(self):
return self.agent_sale.filter(State="Pending",Date_created__range=["2022-03-01","2022-04-02"]).count()
in the above example i am putting the dates in manually(it works and returns the correct query)
problem is I still don't know how to make the user plug these dates in through the site.
This is my view.
def Team_stats(request,pk):
sd = request.GET.get("from")
ed = request.GET.get("to")
start_date = datetime.datetime.strptime(sd, "%Y-%m-%d").date()
end_date = datetime.datetime.strptime(ed, "%Y-%m-%d").date()
if start_date == None or end_date == None:
sales_agent = SalesAgent.objects.filter(Team_leader=pk)
return render(request,"Sales/Team_detail_page.html",{"sales_agent":sales_agent})
else:
sales_agent = SalesAgent.objects.filter(Team_leader=pk,agent_sale__Date_created__range=[start_date,end_date]).distinct()
print(type(start_date))
return render(request,"Sales/Team_detail_page.html",{"sales_agent":sales_agent})
This is my template.
I need to render all the agents under the team leader and the particular field of another model. For example State,Date_Created,Debi_status.
<form method="GET" action=".">
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Start date</label>
<input type="date" format='%Y-%m-%d' name="from" class="form-control" id="inputEmail4" placeholder="Start Date">
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">End date</label>
<input type="date" format='%Y-%m-%d' name="to" class="form-control" id="inputEmail4" placeholder="End date">
</div>
</div>
<button type="submit" class="btn btn-primary">Search</button>
</form>
<!-- <p>THERE SHOULD BE A GRAPH IN HERE FOR THE AGENTS STATS</p> -->
<br>
<br>
<div class="container">
<table class="table table-dark table-striped table-bordered">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Agent Name</th>
<th scope="col">Total sales</th>
<th scope="col">Total debis</th>
<th scope="col">Total confirmed</th>
<th scope="col">Total requested</th>
<th scope="col">Total pending</th>
<th scope="col">Total cancelled</th>
</tr>
</thead>
{% for entry in sales_agent %}
<tbody>
<td>{{forloop.counter}}</td>
<td>{{entry.SA_name}}</td>
<td>{{entry.sfget_totals}}</td>
<td>{{ entry.sfget_debi}}</td>
<td>{{ entry.sfget_confirmed}}</td>
<td>{{ entry.sfget_requested}}</td>
<td>{{ entry.sfget_cancelled}}</td>
<td>{{ entry.sfget_pending}}</td>
{%endfor%}
</table>
<div>
<a type="button" class="btn btn-dark btn-m" href="{%url 'Sales:salesdash'%}">Go back</a>
{%endblock%}
I don't know how to do it better. It's not the best answer because you have to iterate through the entire queryset. But I think it works:
1- Change your models methods adding the variables "from" and "to":
#example
def sfget_totals(self, from, to): #
return self.agent_sale.filter(Date_created__range=[from,to]).count()
2- In your views.py, iterate and add the new properties to each item of the queryset:
def Team_stats(request,pk):
sd = request.GET.get("from")
ed = request.GET.get("to")
start_date = datetime.datetime.strptime(sd, "%Y-%m-%d").date()
end_date = datetime.datetime.strptime(ed, "%Y-%m-%d").date()
if start_date == None or end_date == None:
sales_agent = SalesAgent.objects.filter(Team_leader=pk)
return render(request,"Sales/Team_detail_page.html",{"sales_agent":sales_agent})
else:
sales_agent = SalesAgent.objects.filter(Team_leader=pk,agent_sale__Date_created__range=[start_date,end_date])
for s in sales_agent:
s.sfget_totals_prop = s.sfget_totals(start_date,end_date)
s.sfget_confirmed_prop = s.sfget_confirmed(start_date,end_date)
s.sfget_debi_prop = s.sfget_debi(start_date,end_date)
....
....
return render(request,"Sales/Team_detail_page.html",{"sales_agent":sales_agent})
3- In your templates, change the methods name by the new properties:
<td>{{entry.sfget_totals_prop}}</td>
<td>{{ entry.sfget_debi_prop}}</td>
<td>{{ entry.sfget_confirmed_prop}}</td>
<td>{{ entry.sfget_requested_prop}}</td>
<td>{{ entry.sfget_cancelled_prop}}</td>
<td>{{ entry.sfget_pending_prop}}</td>
Probably, you can solve the problem using Django Managers https://docs.djangoproject.com/en/4.0/topics/db/managers/ and you will find a better way.
Hello I want to display data of the user that is logged in form models into a table written in html
My views.py { I am displaying data from two different models in one table }
def managestugriev(request):
from_stugrievance = studentgriev.objects.all()
from_facgriev = facgrieve.objects.all()
return render(request,'manageGriev.html',
{"data_form_stu":from_stugrievance,"data_from_fac":from_facgriev})
template.html
<div>
<div>
<h2><center>Manage Your Grievances Here </h2>
<h3>Your Total Grievances: {{data|length}}</h3>
<h3></h3>
<table class="center">
<thead>
<tr text-align="justify">
<th>ID</th>
<th>Grievance</th>
<th>Date & Time</th>
<th>Status</th>
<th>Solution</th>
</tr>
</thead>
<tbody>
{% for i in data_form_stu %}
<tr text-align="justify">
<td padding:10px>{{forloop.counter}}</td>
<td>{{i.grievance}}</td>
<td>{{i.date_time}}</td>
<td>{{i.status}}</td>
{% for i in data_from_fac%}
<td>{{i.solution}}</td>
{% endfor %}
</div>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
models.py {Two models from which I am displaying the data}
class studentgriev(models.Model):
ch = (
("Solved","Solved"),("Pending","Pending"),("Not Solved","Not Solved")
)
name = models.CharField(max_length=30,default='',null=False)
contactnum = models.IntegerField(default='',null=False)
email = models.EmailField(max_length=50,default='',null=False)
grievance = models.TextField(default='',null=False)
date_time = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=100,choices=ch,default='')
def __str__(self):
return self.name + " "
class facgrieve(models.Model):
solution = models.TextField(default='',null=False)
def __str__(self):
return self.solution + " "
Please can anyone help !
I have created a table in DB Browser SQLite with real data input. How do I link the SQLite with flask so that the table will be displayed in the html. I want the html part to be displayed exactly the same as DB Browser Sqlite.
This is my app.py
#app.route('/viewrec', methods=['POST', 'GET'])
def viewrec():
try:
if request.method == 'POST':
use = session['user'].get("name")
ema = session['user'].get("preferred_username")
depart = request.form['depart']
type = request.form['type']
uploadre = request.form['uploadre']
amt = request.form['amt']
description = request.form['description']
if request.form.get("price"):
price_checked = "Yes"
else:
price_checked = "No"
conn = sql.connect(db_path)
c = conn.cursor()
c.execute('SELECT * FROM SubmitClaim')
rows = c.fetchall()
return render_template("viewpastclaim.html", rows=rows)
except:
# for row in rows:
# print(row)
#
# conn.close()
return render_template('viewpastclaim.html')
This is my viewpastclaim.html
I tried to call the various variables from App.py and use them with rows['Name']
<form action="/viewrec" METHOD="POST" >
<!-- Generate all the claim content -->
<table style=" font-family: arial, sans-serif;
width: 60%;
border: 1px solid black;
margin-left:500px;
margin-top: 100px;
text-align: center;
padding:20px;">
<tr>
<th class="type">Name</th>
<th>Email</th>
<th>Department</th>
<th>ClaimType</th>
<th>UploadReceipt</th>
<th>ClaimAmount</th>
<th>checkbox</th>
<th>ClaimDescription</th>
</tr>
{% for rows in SubmitClaim %}
<tr>
<td>rows['Name']</td>
<td>rows['Email']</td>
<td>rows['Deparment']</td>
<td>rows['ClaimType']</td>
<td>rows['UploadReceipt']</td>
<td>rows['ClaimAmount']</td>
<td>rows['checkbox']</td>
<td>rows['ClaimDescription']</td>
</tr>
{% endfor %}
</table>
<!-- View all the claims -->
<button type="submit", class="viewall-button" name="save", value="save">View All</button>
</form>
If you are able to solve them, please drop a msg below. Thank you for your time.
You have to wrap your Python variables in {{ }} to show them in HTML format. You also have some errors in your code. You have to replace 'SubmitClaim' with rows since you passed that in your python function. So the correct code would be:
{% for row in rows %}
<tr>
{% for data in row %}
<td>{{ data }}</td>
{% endfor %}
</tr>
{% endfor %}
I think something like that should work. You are giving the info to the template inside of "rows" not inside of "SubmitClaim"
<tr>
<th class="type">Name</th>
<th>Email</th>
<th>Department</th>
<th>ClaimType</th>
<th>UploadReceipt</th>
<th>ClaimAmount</th>
<th>checkbox</th>
<th>ClaimDescription</th>
</tr>
{% for row in rows %}
<tr>
<td>row['Name']</td>
<td>row['Email']</td>
<td>row['Deparment']</td>
<td>row['ClaimType']</td>
<td>row['UploadReceipt']</td>
<td>row['ClaimAmount']</td>
<td>row['checkbox']</td>
<td>row['ClaimDescription']</td>
</tr>
{% endfor %}
If you still can't get it to work I suggest you use SQL-Alchemy to manage the database. That should make everything easier.
Given the elements of the following lists, which express the columns of a table:
table1 = [('January', '$5'),('February', '$9000'), ('October', '$90'), ('NaN', '$300')]
table2 = [('July', '$890'),('December', 'NaN')]
And this html base template:
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<h1>Table element 1</h1>
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>month</td>
<td>amount</td>
</tr>
</table>
<h2>This is the status X</h2>
<input type="checkbox" id="valn" name="valn" value="val_n"> Validate
</body>
</html>
What is the best way to fill with the template's table with the list's values? and extend the table structure for more pairs of lists (columns). For example, for the above lists of tubles, this should be the filled version of the html template:
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<h1>Table element 1</h1>
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$5</td>
</tr>
<tr>
<td>February</td>
<td>$9000</td>
</tr>
<tr>
<td>October</td>
<td>$90</td>
</tr>
<tr>
<td>NaN</td>
<td>$9000</td>
</tr>
</table>
<h2>This is the status A</h2>
<form action="/action_page.php">
<input type="checkbox" id="val1" name="val1" value="val_1"> Validate
</form>
<h1>Table element 2</h1>
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>July</td>
<td>$100</td>
</tr>
<tr>
<td>December</td>
<td>NaN</td>
</tr>
</table>
<h2>This is the status B</h2>
<input type="checkbox" id="val2" name="val2" value="val_2"> Validate
</body>
</html>
Although I could handle this with some string manipulation I think that theres a cleaner way of doing this with jinja. However, I do not know how to control different elements from the template such as the tables and checkboxes. Any idea of how to get the above output, for two and n lists of tuples?
As you requested in comments (basically the same as #nenadp's answer since it was corrected):
from jinja2 import Template
table1 = [('January', '$5'), ('February', '$9000'), ('October', '$90'), ('NaN', '$300')]
table2 = [('July', '$890'), ('December', 'NaN')]
table = table1 + table2 # Concatenate the two lists
template = Template("""
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
{% for row in table %}
<tr>
<td>{{ row[0] }}</td>
<td>{{ row[1] }}</td>
</tr>
{% endfor %}
</table>
""")
print(template.render(table=table))
Change your template file:
{% for row in table1 %}
<tr>
<td>{{ row[0] }}</td>
<td>{{ row[1] }}</td>
</tr>
{% endfor %}
You can format it using this piece of code:
from jinja2 import Template
table1 = [('January', '$5'),('February', '$9000'), ('October', '$90'), ('NaN', '$300')]
t = open('template_file.html', 'r').read()
template = Template(t)
formatted_template = template.render(table1=table1)
print(formatted_template)
You can learn more from Jinja documentation
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