I just started learning Python and Django.
Trying to output on HTML data from the database, I can do it if I set a id, but I wanna have a page where I list all the data from the database in a table.
This is my views:
from django.shortcuts import render
from django.http import HttpResponse
from .models import clientes, viagem
# Create your views here.
def index(request):
ls= clientes.objects.all()
context= {'ls': ls}
return render(request, "booking/home.html", context)
And this is my page:
{% extends 'bulma/base.html' %}
{% block title %}Travel{% endblock %}
{% for clientes in clientes %}
{% block content %}
<table class="table is-fullwidth is-hoverable">
<thead>
<tr>
<th><abbr title="ID">ID</abbr></th>
<th>Nome</th>
<th>Apelido</th>
<th>Morada</th>
<th>Telemóvel</th>
<th>NIF</th>
</tr>
</thead>
<tbody>
<tr>
<th>{{ls.id}}</th>
<td>{{ls.nome}}</td>
<td>{{ls.apelido}}</td>
<td>{{ls.morada}}</td>
<td>{{ls.tel}}</td>
<td>{{ls.nif}}</td>
</tr>
</tbody>
</table>
{% endblock content %}
{% endfor %}
Can someone point me in the right direction?
First thing: your {% for %} loop is not at the right place. When extending another template, only the code in {% block %} statements are executed. So you want to move your loop inside the {% block content %}.
Second point: in the context you pass to the template, your queryset is named ls, not clientes, so you want to change this name either in the view or the template - the point is that they have to match xD.
A possible correction:
def index(request):
queryset = clientes.objects.all()
context= {'clientes': queryset}
return render(request, "booking/home.html", context)
and
{% extends 'bulma/base.html' %}
{% block title %}Travel{% endblock %}
{% block content %}
{% for client in clientes %}
<table class="table is-fullwidth is-hoverable">
<thead>
<tr>
<th><abbr title="ID">ID</abbr></th>
<th>Nome</th>
<th>Apelido</th>
<th>Morada</th>
<th>Telemóvel</th>
<th>NIF</th>
</tr>
</thead>
<tbody>
<tr>
<th>{{client.id}}</th>
<td>{{client.nome}}</td>
<td>{{client.apelido}}</td>
<td>{{client.morada}}</td>
<td>{{client.tel}}</td>
<td>{{client.nif}}</td>
</tr>
</tbody>
</table>
{% endfor %}
{% endblock content %}
you can try this:
{% extends 'bulma/base.html' %}
{% block title %}Travel{% endblock %}
{% block content %}
<table class="table is-fullwidth is-hoverable">
<thead>
<tr>
<th><abbr title="ID">ID</abbr></th>
<th>Nome</th>
<th>Apelido</th>
<th>Morada</th>
<th>Telemóvel</th>
<th>NIF</th>
</tr>
</thead>
<tbody>
{% for client in ls %} # ls as you passed variable named ls
<tr>
<th>{{client.id}}</th>
<td>{{client.nome}}</td>
<td>{{client.apelido}}</td>
<td>{{client.morada}}</td>
<td>{{client.tel}}</td>
<td>{{client.nif}}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock content %}
you must write this code in view.py
def product_detail_view(request):
obj = product.objects.all()
context = { 'allobject' : obj }
return render(request, "product/details.html", context)
you have to write this code in your html file
{% extends 'base.html' %}
{% block content %}
<h1> New about </h1>
<p>
{% for item in allobject %}
{{ item.title }}
{% endfor %}
</p>
{% endblock %}
{% block content %}
{% for x in y %}
{% autoescape off %}
{{x}}
{% endautoescape %}
{% endfor%}
This is quite simple to execute. Use the tools that django provides :)
Try it:
{% extends 'bulma/base.html' %}
{% block title %}Travel{% endblock %}
{% for clientes in ls%}
{% block content %}
<table class="table is-fullwidth is-hoverable">
<thead>
<tr>
<th><abbr title="ID">ID</abbr></th>
<th>Nome</th>
<th>Apelido</th>
<th>Morada</th>
<th>Telemóvel</th>
<th>NIF</th>
</tr>
</thead>
<tbody>
<tr>
<th>{{ls.id}}</th>
<td>{{ls.nome}}</td>
<td>{{ls.apelido}}</td>
<td>{{ls.morada}}</td>
<td>{{ls.tel}}</td>
<td>{{ls.nif}}</td>
</tr>
</tbody>
</table>
{% endblock content %}
{% endfor %}
You need to use the same name of the dict in your forloop.
Related
in my view.py I have a function with field: context ={'user':user, 'user_gpds':user_gpds, 'team':team, 'team_gpds':team_gpds}
which I return:
return render(request, 'app/team_gpd_page/team_gpds.html', context)
in my templates I have next code:
{% for gpd in {{context|key:team_gpds}} %}
<tr>
<td><a class="nav-link" href="/gpd/{{gpd.employee.end_user_id}}">GPD</a></td>
<td>{{gpd.employee}}</td>
<td>{{gpd.gpd_year}}</td>
<td>{{gpd.gpd_start}}</td>
<td>{{gpd.gpd_end}}</td>
<td>{{gpd.gpd_status}}</td>
</tr>
{% endfor %}
But in result I have had an empty fields. I am also trying context.team_gpds and context.get('team_gpds'). What I am doing wrong?
If team_gpds is querysets then you can loop through querysets as
{% for gpd in team_gpds %}
<tr>
<td><a class="nav-link" href="/gpd/{{gpd.employee.end_user_id}}">GPD</a></td>
<td>{{gpd.employee}}</td>
<td>{{gpd.gpd_year}}</td>
<td>{{gpd.gpd_start}}</td>
<td>{{gpd.gpd_end}}</td>
<td>{{gpd.gpd_status}}</td>
</tr>
{% endfor %}
say we have table in template
<table class="table">
<thead>
<tr>
<th>Status</th>
</tr>
</thead>
<tbody>
{% for student in students %}
<tr>
{% if {{student.academic_status}}=="promoted" %}
<td class=text-success>promoted</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
So is it possible using if statement in table in django-templates
Since you are already in a template tag, you should not use curly brackets ({{ … }}) for the variable, so:
{% if student.academic_status == "promoted" %}
…
{% endif %}
The correct way to add if statement in Django Templates
follow me !
if statement
{% if condition %}
{{here you add the key that you using in the views page exactly context}}
{% endif %}
Trying to use nested block and for loop in a Jinja template block setup.
{% block main %}
<table>
<tr>
<td>user id</td>
<td>user sec level</td>
</tr>
{% block main_nested_b scoped %}
{%
for user in list_users:
t_id_user = str(user[0][0])
t_sec_level = str(user[2][0])
%}
<tr>
<td>
<a href='/usersEdit?id_user={{ t_id_user }}' class='onwhite'>edit</a>
</td>
</tr>
{% endfor %}
{% endblock main_nested_b %}
{% endblock main %}
</table>
Error message:
jinja2.exceptions.TemplateSyntaxError: expected token 'end of statement block', got 't_id_user'
Help?
You can't treat Jinja syntax as Python syntax. It's not the same thing. Keep your for tag separate from assignment (set) tags:
{% for user in list_users %}
{% set t_id_user = user[0][0] %}
{% set t_sec_level = user[2][0] %}
Note that there isn't even a : at the end of the for ... in ... syntax! Also you don't need to call str() here, leave that to Jinja to convert to strings for you; anywhere you use {{ t_id_user }} or {{ t_sec_level }} the value will be converted to a string anyway.
Here is the complete template:
<table>
{% block main %}
{% block main_nested_b scoped %}
{% for user in list_users %}
{% set t_id_user = user[0][0] %}
{% set t_sec_level = user[2][0] %}
<tr>
<td>
<a href='/usersEdit?id_user={{ t_id_user }}' class='onwhite'>edit</a>
</td>
</tr>
{% endfor %}
{% endblock main_nested_b %}
{% endblock main %}
</table>
Code I'm working with:
{% for row in all_rows %}
<tr>
{% for names in all_fields_names %}
<td> {% getattr(row, names) %} </td>
{% endfor %}
</tr>
{% endfor %}
I get error:
'getattr(row,', expected 'empty' or 'endfor'
I've tried:
{% for row, names in (all_rows, all_fields_names) %}
<tr>
<td> {% getattr(row, names) %} </td>
</tr>
{% endfor %}
With no success. Any ideas?
You can't call functions like that inside the template. You'd want to create a custom template tag.
Custom Template Tag:
#register.simple_tag
def getattr(row, field_name, default=None):
return getattr(row, field_name, default)
Call it inside your template like so:
{% for row, names in (all_rows, all_fields_names) %}
<tr>
<td> {% getattr row names %} </td>
</tr>
{% endfor %}
I have a Django project, in which one of my views is displaying a number of tables based on information stored in the database. The view is defined as follows:
def pipeline(request):
...
tables = []
def make_table(detailed_status, projects, status_view=False, first_table=False):
...
table_context_map = {
Project.ds2: {'fields': [['date added',1], ['site visit date',1], ['initial exc VAT',1]]},
...
# Similar lines to populate the tables with data from the database
...
}
table_context = table_context_map[detailed_status]
...
table_context['fields'] = [['project name',1], ['town',1], ['postcode',1], ['contact name',1]] + table_context['fields']
table = render_to_string('.../....html', table_context)
...
return render(request, 'abc.html', context)
What I'd like to do, is at a column to each table created by this view, and insert an 'autonumber' in that column for every row in the table. The tables will be populated dynamically, based on a database query whenever the view is run and the webpage loaded, I just want to number the list of items in each table as it's created.
How would I do this? I am knew to Python Django, so any help or guidance would be much appreciated.
Edit
The part of the HTML that is currently displaying these tables in the webpage looks like this:
<div class="content">
{% block tables %}
{% for table in tables %}
{# Only shows table headers on first table (css first of type on multisection thead) #}
{{table}}
{% endfor %}
{% endblock tables %}
</div>
Edit
The HTML for the file passed into the render_to_string(...) view has the following structure:
{% load getters money_handling staticfiles utilities %}
{% if projects %}
<div class="table-container m-t-lg">
<table class="multisection pipeline left">
<tr class="sub-summary">
<th colspan="4"><h3 class="p-l-sm">{{detailed_status_str}}</h3></th>
{% if total_i %}<th>Initial exc VAT: {{total_i|money:"£"}}</th>{% endif %}
{% if total_u %}<th>Latest exc VAT: {{total_u|money:"£"}}</th>{% else %}
<th></th>
{% endif %}
</tr>
</table>
<table class="multisection pipeline left m-b-xl">
<tr class="summary">
<th style="width: 3em;"></th>
{% for field in fields %}
<th class="text-sm p-l-sm p-t-sm p-b-sm" style="width:{{widths|getval:forloop.counter0}}">
{% if field.1 %}
{% if sort == field.0 and not reverse %}
{{field.0}}
{% else %}
{{field.0}}
{% endif %}
{% else %}
{{field.0}}
{% endif %}
</th>
{# Make all have the same number of columns (8) #}
{% if forloop.last %}
{% for i in ',,,,,,,,' %}
{% if forloop.counter|add:forloop.parentloop.counter0 < 11 %}
<th> </th>
{% endif %}
{% endfor %}
{% if detailed_status == "ds4"|ds %}
<th></th>
{% endif %}
{% endif %}
{% endfor %}
</tr>
{% with user.employee.full_name|is:'Nick Ross' as summary_link %}
{% for project in projects %}
<tr data-project-id="{{project.id}}" class="even {% if project.office == 2 %} col{% endif %}">
{% with initial_details=project.initial_details survey=project.survey %}
{# Open lightbox #}
<td>
{# ERF(22/11/2016 # 1450) Add a counter to display table row numbers #}
{% if user.is_superuser %}
<a class="gallery-loader" data-project-id="{{project.id}}"><i class="icon info"></i></a>
{% if forloop.first and first_table %}
<div id="iframe_gallery_wrap">
<a href="#p1" class="gallery">
<div id="p1">
<iframe class="lightbox-content" src="{% url 'projects:description' project.id %}report/" width="1200" height="800" id="p1" style="border:none;" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe>
</div>
</a>
Probaly forloop.counter is what you are looking for.
Just use it in your template like this:
<ul>
{% for data in data_list %}
<li>{{ forloop.counter }}</li>
{% endfor %}
</ul>
As for your file hope my modifications will work (marked it with your username):
{% load getters money_handling staticfiles utilities %}
{% if projects %}
<div class="table-container m-t-lg">
<table class="multisection pipeline left">
<tr class="sub-summary">
<th colspan="4"><h3 class="p-l-sm">{{detailed_status_str}}</h3></th>
{% if total_i %}<th>Initial exc VAT: {{total_i|money:"£"}}</th>{% endif %}
{% if total_u %}<th>Latest exc VAT: {{total_u|money:"£"}}</th>{% else %}
<th></th>
{% endif %}
</tr>
</table>
<table class="multisection pipeline left m-b-xl">
<tr class="summary">
<th style="width: 3em;"></th>
<th>Number</th> #someone2088
{% for field in fields %}
<th class="text-sm p-l-sm p-t-sm p-b-sm" style="width:{{widths|getval:forloop.counter0}}">
{% if field.1 %}
{% if sort == field.0 and not reverse %}
{{field.0}}
{% else %}
{{field.0}}
{% endif %}
{% else %}
{{field.0}}
{% endif %}
</th>
{# Make all have the same number of columns (8) #}
{% if forloop.last %}
{% for i in ',,,,,,,,' %}
{% if forloop.counter|add:forloop.parentloop.counter0 < 11 %}
<th> </th>
{% endif %}
{% endfor %}
{% if detailed_status == "ds4"|ds %}
<th></th>
{% endif %}
{% endif %}
{% endfor %}
</tr>
{% with user.employee.full_name|is:'Nick Ross' as summary_link %}
{% for project in projects %}
<tr data-project-id="{{project.id}}" class="even {% if project.office == 2 %} col{% endif %}">
{% with initial_details=project.initial_details survey=project.survey %}
{# Open lightbox #}
<td>{{ forloop.counter }}</td> #someone2088
<td>
{# ERF(22/11/2016 # 1450) Add a counter to display table row numbers #}
{% if user.is_superuser %}
<a class="gallery-loader" data-project-id="{{project.id}}"><i class="icon info"></i></a>
{% if forloop.first and first_table %}
<div id="iframe_gallery_wrap">
<a href="#p1" class="gallery">
<div id="p1">
<iframe class="lightbox-content" src="{% url 'projects:description' project.id %}report/" width="1200" height="800" id="p1" style="border:none;" webkitallowfullscreen="" mozallowfullscreen="" allowfullscreen=""></iframe>
</div>
</a>