I have a page that displays Employees Masterlist and I wanted to do is when I clicked the Employee No. it will view the timesheet of that employee.
I tried using this as the result of my research.
In my routes.py
#app.route("/employee/<int:employee_id>")
def employee(employee_id):
employee = Employee.query.get_or_404(employee_id)
return render_template('emp_timesheet.html', employee=employee)
Here is my masterlist.html
{% extends 'header.html' %}
{% block content %}
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>Employee Number</th>
<th>Name</th>
<th>Contract</th>
<th>Position</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
{% for employee in list_employee %}
<tr class="odd gradeX">
<td>{{ employee.employee_number }}</td>
<td>{{ employee.last_name }}, {{ employee.first_name }}</td>
<td>{{ employee.contract }}</td>
<td class="center">{{ employee.title }}</td>
<td class="center">{{ employee.salary }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
But I'm getting this error:
File "/home/jxmtsi/Desktop/flask_training/rep/templates/header.html", line 293, in top-level template code
{% block content %}{% endblock %}
File "/home/jxmtsi/Desktop/flask_training/rep/templates/masterlist.html", line 27, in block "content"
<td>{{ employee.employee_number }}</td>
File "/home/jxmtsi/.local/lib/python3.6/site-packages/jinja2/environment.py", line 430, in getattr
return getattr(obj, attribute)
jinja2.exceptions.UndefinedError: 'employee' is undefined
I think, that a problem is in your Python code, more precisely in a communication between your application and SQL base. Or, maybe, you do not have in SQL database a data about requested employee_id.
Check, does variable employee in method employee (employee_id) is receiving data from your database. For example, try print(employee.last_name):
#app.route("/employee/<int:employee_id>")
def employee(employee_id):
employee = Employee.query.get_or_404(employee_id)
print(employee.last_name) # or print other value from table (Model) Employee
# print(employee.id)
return render_template('emp_timesheet.html', employee=employee)
Related
I started working with Django earlier this week and watched a few tutorials and thought I would try out switching over a site I made in PHP to something a little more current. I ran into some issues over the weekend and managed to get help with some of them, but one issue remains.
I already have an existing database with some information it that I want to retrieve to display on a website. The information is modified through the database so Django doesn't have to deal with any of that - just displaying results to a bootstrapped template file.
So, in essence Django would have 2 models - one for each relevant database table.
The first model relates to products
class Bikes(models.Model):
bikempn = models.CharField(primary_key=True, max_length=50)
bikecategory = models.CharField(max_length=50)
bikeyear = models.CharField(max_length=4)
bikebrand = models.CharField(max_length=50)
bikedesc = models.CharField(max_length=255)
bikesize = models.CharField(max_length=50)
bikecolour = models.CharField(max_length=255)
bikeurl = models.CharField(max_length=255)
class Meta:
managed = False
db_table = 'bikes'
The second model relates to their expected arrival dates. This model would represent a database view which performs some logic comparing product that is on its way to the number of matching items that are on reserve.
The model is:
class Eta(models.Model):
bikempn = models.ForeignKey(Bikes, on_delete=models.CASCADE, primary_key = True, db_column='bikempn', related_name='etas')
eta = models.DateField()
class Meta:
managed = False
db_table = 'bike_eta'
The idea of this website is essentially to let people know if a product they are interested in will be arriving any time soon.
I have been trying to come up with a query that will display all of the linked information, but everything I find online hasn't quite worked. I have received some help along the way but have hit the wall again and frankly feel foolish having not figured this out yet.
So, currently I have a query that is:
kidsquery = Bikes.objects.filter(bikecategory='kids').select_related('etas')
This filters out only bikes categorized as kids bikes and should join the two models together.
My relevant template to display this information is:
{% extends 'base.html' %}
{% block content %}
{% if kidsquery %}
<div class="table-responsive">
<table class="table table-striped table-hover table-bordered table-sm">
<thead class="table-dark">
<tr>
<th scope="col">Year</th>
<th scope="col">Brand</th>
<th scope="col">Model</th>
<th scope="col">Colour</th>
<th scope="col">Size</th>
<th scope="col">Part#</th>
<th scope="col">ETA</th>
</tr>
</thead>
{% for info in kidsquery %}
<tr>
<td>{{ info.bikeyear }}</td>
<td>{{ info.bikebrand }}</td>
{% if info.bikeurl %}
<td>{{ info.bikedesc }}</td>
{% else %}
<td>{{ info.bikedesc }}</td>
{% endif %}
<td>{{ info.bikecolour }}</td>
<td>{{ info.bikesize }}</td>
<td>{{ info.bikempn }}</td>
{% for arrival in info.etas.all %}
{% if arrival is null %}
<td>Contact Us</td>
{% else %}
<td>{{ arrival|date:"F Y" }}</td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
</table>
</div>
{% endif %}
{% endblock %}
Does anyone know why I cannot get anything to display in the final column (where it should display the eta date values (or failing that, the "Contact Us" result)?
The proper solution to pulling the information out in the template:
{% extends 'base.html' %}
{% block content %}
{% if kidsquery %}
<div class="table-responsive">
<table class="table table-striped table-hover table-bordered table-sm">
<thead class="table-dark">
<tr>
<th scope="col">Year</th>
<th scope="col">Brand</th>
<th scope="col">Model</th>
<th scope="col">Colour</th>
<th scope="col">Size</th>
<th scope="col">Part#</th>
<th scope="col">ETA</th>
</tr>
</thead>
{% for info in kidsquery %}
<tr>
<td>{{ info.bikeyear }}</td>
<td>{{ info.bikebrand }}</td>
{% if info.bikeurl %}
<td>{{ info.bikedesc }}</td>
{% else %}
<td>{{ info.bikedesc }}</td>
{% endif %}
<td>{{ info.bikecolour }}</td>
<td>{{ info.bikesize }}</td>
<td>{{ info.bikempn }}</td>
{% for arrival in info.etas.all %}
{% if arrival.eta %}
<td>{{ arrival.eta|date:"F Y" }} </td>
{% else %}
<td>Contact Us</td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
</table>
</div>
{% endif %}
{% endblock %}
Swapped around the checks, and compensated for the lack of a date.
i have a django project that is connected to SQL Server i tried to retrieve data from the database.
if i try to display all the data it run correct and display all the values.
but if i try to display the data in an html table it doesn't display anything.
views.py
def connect(request):
conn = pyodbc.connect(
'Driver={ODBC Driver 17 for SQL Server};'
'Server=DESKTOP-LPD1575\\SQLEXPRESS;'
'Database=testDB;'
'UID=test;'
'PWD=test;'
)
cursor = conn.cursor()
c = cursor.execute('SELECT * FROM Artist')
return render (request,'connect.html',{"c":c})
connect.html
{% for row in c %}
{{ row }}
{% endfor %}
this code in the html template work and display the data.
but if i try to do as below it will not work
<table align = "center">
<tr align="center">
<th>ID</th>
<th>FolderNumber</th>
<th>Title</th>
</tr>
{% for row in c %}
<tr align="center">
<td>{{ row.id }}</td>
<td>{{ row.artistName }}</td>
<td>{{ row.activeFrom }}</td>
</tr>
{% endfor %}
</table>
anyone can help me?
Each row in your result is a list, not a dict. You would need to use indexes not keys:
{% for row in c %}
<tr align="center">
<td>{{ row.0 }}</td>
<td>{{ row.1 }}</td>
<td>{{ row.2 }}</td>
</tr>
{% endfor %}
or better
{% for row in c %}
<tr align="center">
{% for item in row %}
<td>{{ item }}</td>
{% endfor %}
</tr>
{% endfor %}
However, really you should not be running SQL queries directly, but define a model for your table and access it that way.
django table information displayed twice
Why is the Due date and time remaining appear twice? I am trying figure out what is that coming from. I am still learning django, slowly. Sometimes, I'm just having trouble.
Picture:
http://gyazo.com/cae11df54df3f558865a772529f97139.png
.html code
{% if toolsBorrowed %}
<table id="dataTable" width="100%" cellspacing="0" cellpadding="5" class="table table-hover">
<thead>
<tr>
<th>Tool Name</th>
<th>Owner</th>
<th>Due Date</th>
<th>Time Remaining</th>
</tr>
</thead>
<tbody id="myTable">
{% for tool in toolsBorrowed %}
{% query Request borrowerId=user.id as req %}
{% query userAcc pk=tool.owner as owner %}
<tr style="cursor: pointer;" onclick="document.location = '/view_tool/{{ tool.id }}/';">
<td>{{ tool.name }}</td>
<td>{% for o in owner %}{{ o.username }}{% endfor %}</td>
{% for r in req %}
<td>{{ r.dueDate }}</td>
<td>{{ r.dueDate | timeuntil }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<strong>You are not borrowing any tools.</strong>
{% endif %}
views.py
def borrowed(request):
context = {'toolsBorrowed': Tool.objects.filter(borrower = request.user.id),
'toolsLoan':Tool.objects.filter(owner = request.user.id).exclude(borrower = None),
'userAcc' : userAcc.objects,
'Request' : Request.objects,
}
return render(request, 'borrowed.html', context)
Any help would be great.
I would like to print all user values in my profile template.
Printing it manually it works:
`
<table class="table table-striped table-bordered">
<tr><th>{{ user.username }}</th></tr>
<tr><th>{{ user.first_name }}</th></tr>
<tr><th>{{ user.last_name }}</th></tr>
<tr><th>{{ user.email }}</th></tr>
</table>`
but such approach does not work:
`
<table class="table table-striped table-bordered">
{% for field in user.fields %}
<tr>
<td>{{ field.name }}</td>
<td>{{ field.value }}</td>
</tr>
{% endfor %}
</table>
I was tryintg to use this approach Iterate over model instance field names and values in template
Any hints?
There is no attribute called fields available on model instances.
If you really want something like this:
views.py:
d = {}
for each in u._meta.fields:
d[each.name] = getattr(u, each.name)
template:
{% for k,v in d.items %}
{{k}}
{{v}}
{% endfor %}
You have to make sure you're sending in the "user" object itself through your views.py file (not user.username, or user.first_name, etc.). That way you can write in your template:
<table class="table table-striped table-bordered">
{% for field in user %}
<tr>
<td>{{ field.name }}</td>
<td>{{ field.value }}</td>
</tr>
{% empty %}
<tr>
<td>No "user" field</td>
</tr>
{% endfor %}
</table>
Notice the change in the second line ("for field in user").
I have a question regarding counting objects, filtering the results and finally putting them into my template.
in Models.py:
class Fms(models.Model):
department = models.CharField(max_length=255, verbose_name='Department')
date = models.DateField()
in Views.py:
def raport(request):
raport = Fms.objects.filter(date__year='2013').extra(select={'month': "EXTRACT(month FROM date)"}).values('month', 'department').annotate(Count('department'))
return render_to_response ('Fms/raport.html',
{'raport': raport},
context_instance=RequestContext(request))
Question is, how to show a result in a table like:
Or at least make it show each month and how many times department was mentioned in that month.
you need something like:
{% for each_model in raport %}
{{each_model.department}}
{{each_model.date}}
{% endfor %}
If you do not pass a keyword to annotate, it uses the name of the field with __count appended to it. https://docs.djangoproject.com/en/dev/topics/db/aggregation/#generating-aggregates-for-each-item-in-a-queryset To access that in your template you would simply do:
<table>
<thead>
<tr>
<th>Month</th>
<th>Count</th>
</tr>
</thead>
<tbody>
{% for item in raport %}
<tr>
<td>{{ item.month }}</td>
<td>{{ item.department__count }}</td>
</tr>
{% endfor %}
</tbody>
</table>
To display it horizontally...
<table>
<thead>
<tr>
{% for item in raport %}
<th>{{ item.month }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
<tr>
{% for item in raport %}
<td>{{ item.department__count }}</td>
{% endfor %}
</tr>
</tbody>
</table>