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
Related
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 am trying to generate a dynamic list of student from database, using FieldList and FormField. The fields are being generated using the data from database, but if I try to change something from the front-end, the back-end receives only the starting data (e.g., for checkbox it only gets False)
form:
class Beneficiary_Migration_Entry_Form(FlaskForm):
name = StringField('')
id = StringField('')
school = SelectField('', validate_choice=False)
student_class = SelectField('', validate_choice=False)
migrate = BooleanField('')
class Beneficiary_Migration_Form(FlaskForm):
entry_form_list = FieldList(FormField(Beneficiary_Migration_Entry_Form))
submit = SubmitField('Submit')
route
#app.route('/migration/student/<school_year_id>', methods=['GET', 'POST'])
#login_required
def student_migration_page(school_year_id):
school_year_id = int(school_year_id)
school_year = School_Year.query.filter(School_Year.id==school_year_id).first()
entry_form_list = []
school_list = Database_Manager.get_school_list(current_user)
school_choices = get_school_list()
entries = Student.query.filter(Student.user_id==current_user.id).all()
for entry in entries:
form = Beneficiary_Migration_Entry_Form(
name=entry.name,
id=entry.id,
)
id_str = str(entry.id)
form.name.name = 'name-' + id_str
form.school.name = 'school-' + id_str
form.migrate.name = 'migrate-' + id_str
form.student_class.name = 'student_class-' + id_str
form.id.name = 'id-' + id_str
form.school.choices = school_choices
form.student_class.choices = [('','')]
entry_form_list.append(form)
migration_form = Beneficiary_Migration_Form()
migration_form.entry_form_list = entry_form_list
school_map = Database_Manager.get_schools_map(current_user)
if migration_form.submit.data:
for form in migration_form.entry_form_list:
print(form.migrate.data)
return redirect(url_for('migration_page', school_year_id=school_year_id))
return render_template('migration-elev.html', school_map=school_map,school_year=school_year, migration_form=migration_form)
Front-end:
<form action="" method="post">
{{ migration_form.hidden_tag() }}
<table class="table table-striped table-dark" style="text-align: center;">
<thead class="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Nume</th>
<th scope="col">Scoala</th>
<th scope="col">Clasa/ Grupa</th>
<th scope="col">Transfer</th>
</tr>
</thead>
<tbody>
{% for form in migration_form.entry_form_list %}
{{ form.hidden_tag() }}
<tr>
<td>{{form.id.value}}</td>
<td>{{form.name}}</td>
<td>{{form.school}}</td>
<td>{{form.student_class}}</td>
<td>{{form.migrate}}</td>
</tr>
{% endfor %}
</tbody>
</table>
<p>{{ migration_form.submit(class_="btn btn-primary") }}</p>
</form>
At first it only got the data from the first entry from the FieldList, but I've found that I need to put unique names to work.
I've tried to use validate_on_submit but I get AttributeError: 'Beneficiary_Migration_Form' object has no attribute 'copy'.
I've also tried to use dictionaries and named tuples to load data, but I get the same result.
I've modified name to entry_name, since name is a reserved word.
To load data I've used append_data, where I've made a dictionary with data from db.
I am new to Django and I am working on a project. In my project an admin will have the power to assign the project to a manager. So I want to render the name of all the managers from the database so that it will be displayed to the admin.
here is my .html file where I want to render the name of the manager in:
<div class="body table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>S No.</th>
<th>COMPANY NAME</th>
<th>TEAM MEMBER</th>
<th>EMAIL</th>
<th>ASSIGN TEAM</th>
</tr>
</thead>
<tbody>
{%for team in object%}
<tr>
<form id="form_id" method="POST" action = "{% url 'accept' %}">
{% csrf_token %}
<th scope="row"> {{ forloop.counter }}</th>
<td>{{team.company_name}}</td>
<td>{{team.team_member}}</td>
<td>{{team.email}}</td>
<td>
<select name="manager">
{% for manager in managers %}
<option value ="{{manager.id}}">{{manager.name}}</option>
{% endfor %}
</select>
<!-- </div> -->
</td>
</tr>
{% endfor %}
</tbody>
</table>
Here is my model for manager:
class manager(models.Model):
name = models.CharField(max_length= 500)
designation = models.CharField(max_length= 500)
class Meta:
permissions = [
("edit_task", "can edit the task"),
]
def __str__(self):
return self.name
Here is my views.py;
def accept(request):
obj= Create_Team.objects.filter(status='Accept')
if request.method == 'POST':
acc = manager()
manager_id = int(request.POST.get('manager', 1))
acc.manager = manager.objects.get(pk=manager_id)
return render(request, "admin/accept.html", {"object": obj})
In the admins page, I want to display all the names of the managers. I have added the image of the admin page.
I think you forgot to include the managers queryset in the context variable
def accept(request):
obj= Create_Team.objects.filter(status='Accept')
managers = manager.objects.all()
if request.method == 'POST':
acc = manager()
manager_id = int(request.POST.get('manager', 1))
acc.manager = manager.objects.get(pk=manager_id)
return render(request, "admin/accept.html", {"object": obj, "managers": managers})
I m trying to request table_id from table_base.html and is not returning anything.
This my table_base.html
<div class="container">
<div class="jumbotron">
<h1> {{ table_name }} List</h1>
{% if list_tables %}
<table class="table table-bordered sortable">
<thead>
<th>Id</th>
<th>Name</a></th>
<th>Date</a></th>
<th>Search Button</th>
</thead>
{% for list in list_tables %}
<tr>
<td><a href="#" >{{ list.id }}</a></td>
<td>
{{ list.name }}
</td>
<td>{{ list.date }}</td>
<td>Search</td>
</tr>
{% endfor %}
</table>
{% else %}
<p> No Records Found</p>
{% endif %}
</div>
</div>
This is my tables/urls.py
urlpatterns = [
url(r'^$', views.table_base, name='tables'),
url(r'^(?P<table_id>\d+)$', views.AboutDetail.as_view(), name='details'),
url(r'^(?P<table_id>\d+)/details$', views.addview, name='addview')
]
This is my tables/views.py
def table_base(request):
table_name = Crawledtables._meta.db_table
list_tables = Crawledtables.objects.order_by('id')
return render(request, 'tables/table_base.html', {'table_name': table_name,
'list_tables': list_tables})
class AboutDetail(DetailView):
model = Crawledtables
pk_url_kwarg = 'table_id'
template_name = 'tables/table_list.html'
def __init__(self, **kwargs):
super(AboutDetail, self).__init__(**kwargs)
def get_object(self, **kwargs):
if 'table_id' not in self.kwargs:
return Crawledtables.objects.get(id=1)
else:
return Crawledtables.objects.get(id=self.kwargs['table_id'])
def addview(request, table_id):
q = request.GET.get('table_id')
print q
table_name = Crawledtables.objects.get(id=q)
print table_name
AllTables._meta.db_table = table_name.name
tbl_detail = AllTables.objects.order_by('id')
return render(request, 'tables/table_list.html', {'details': tbl_detail})
It works 1 time. When I select the first table (table with id 1) it gives me all the info. When I try to select another table it gives me this error:
InternalError: (1054, u"Unknown column 'table_name.id' in 'field list'")
I use print to print me everything. And it shows good response. But in the end it just hits me with error 1054. I can only see 1 table details at a time. If I want to see another table. I have to restart the server.
It seems that you don't run this command
python manage.py makemigrations <app_name>
python manage.py migrate
your table is not created yet
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