Get dict's value by key name in Django Tempaltes - python

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 %}

Related

If statement in table in django-templates

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 %}

how to prevent data from being repeated in the template even though the context is being nested

I am trying to implement an upvote and downvote functionality in my website. I am getting the data in two's and i think this reason is because the suppliers_votes_count is being nested in the suppliers data cominf from the view. How can I avoid this please.
This is an image that shows the template
And a proof for this is that if i print the result outside of the loop, it works normally.
To understand the question better, check the view-supplier.html, you will t=see this {% for vote in suppliers_votes_count %} being nested in this {% for supplier in suppliers %}. I think this is what causes that.
views.py
def Viewsupplier(request):
title = "All Suppliers"
suppliers = User.objects.filter(user_type__is_supplier=True)
# Get the updated count:
suppliers_votes_count = {}
for supplier in suppliers:
upvote_count = supplier.upvotes
downvote_count = supplier.downvotes
supplier_count = {supplier: {'upvote': upvote_count, 'downvote': downvote_count } }
suppliers_votes_count.update(supplier_count)
context = {"suppliers":suppliers, "title":title, "suppliers_votes_count": suppliers_votes_count}
return render(request, 'core/view-suppliers.html', context)
view-suppliers.html
<table class="table table-borderless table-data3">
<thead>
<tr>
<th>No</th>
<th>Email</th>
<th>Votes</th>
</tr>
</thead>
<tbody>
{% for supplier in suppliers %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{supplier.email}}</td>
<td>
<div class="table-data-feature">
<a href="{% url 'upvote' supplier.id %}" class="m-r-10">
<button class="item" data-toggle="tooltip" data-placement="top" title="Like">
<i class="zmdi zmdi-thumb-up">
{% for vote in suppliers_votes_count %}
{{vote.upvotes}}
{% endfor %}
</i></button>
</a>
<a href="{% url 'downvote' supplier.id %}">
<button class="item" data-toggle="tooltip" data-placement="top" title="Dislike">
<i class="zmdi zmdi-thumb-down">
{% for vote in suppliers_votes_count %}
{{vote.downvotes}}
{% endfor %}
</i></button>
</a>
</div>
</td>
</tr>
{% empty %}
<tr><td class="text-center p-5" colspan="7"><h4>No supplier available</h4></td></tr>
{% endfor %}
</tbody>
</table>
I was going to offer to combine supplier data and vote counts onto one object and avoid nested loops in the template but then realized that since you can do this in the view
upvote_count = supplier.upvotes
downvote_count = supplier.downvotes
there is no reason to build, pass and process separately suppliers_votes_count
so in the template instead of this
{% for vote in suppliers_votes_count %}
{{vote.upvotes}}
{% endfor %}
use this
supplier.upvotes
similar to downvotes

How to output in HTML all objects from Django database?

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.

Flask-SQLalchemy pagination error, Could not build url for endpoint

I am trying to implement pagination with Flask-SQLAlchemy
Here is what I have done for my route
#app.route('/client/<int:page_num>',methods=['POST','GET'])
def client(page_num=None):
form = ClientForm(request.form)
if current_user.is_active ==True:
if current_user.user_role == "super_admin":
if form.validate_on_submit():
message=addOrUpdateClient(form, current_user)
return jsonify(json.dumps(message))
if (page_num):
clients = Client.query.paginate(per_page=5, page=page_num, error_out=True)
else:
clients = Client.query.paginate(per_page=5, page=1, error_out=True)
return render_template('client.html/', user=current_user,form = form,clients= clients)
else:
next_page = url_for('login')
return redirect(next_page)
And my template file is
{% if clients %}
<h4>All client</h4>
<div class="table-responsive">
<table class="table table-striped" id="client_table">
<thead>
<tr>
<th>Client Name</th>
<th>Client Short Name</th>
</tr>
</thead>
<tbody>
{% for client in clients.items %}
<tr>
<td>{{client.client_name}}</td>
<td>{{client.client_code}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% for client in clients.iter_pages(left_edge=3, right_edge=3, left_current=3, right_current=3) %}
{% if page %}
{{page}}
{% else %}
{% endif %}
{% endfor %}
{% endif %}
But when I tried to load I get the following error
Could not build url for endpoint 'client'. Did you forget to specify values ['page_num']?
Before adding this pagination , my code were working fine . One more thing to be noted here , is that I didn't even hit '/client' route . I got this error in index page http://localhost:5000/
Edit:
It seems , there is a problem in my html template , although I am still not sure
I was building url for navigation in my html template like following
<li class="nav-item">
<a class="nav-link" href="{{ url_for('client') }}">
<i class="ti-shield menu-icon"></i>
<span class="menu-title">Client</span>
</a>
</li>
And the IDE is pointing error at this line.

Django 'getattr(row,', expected 'empty' or 'endfor''

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 %}

Categories