Django template integer value iteration - django

I have the following model
class Table(models.Model):
# Some not important attrs
rows = IntegerField(etc)
cols = IntegerField(etc)
Then I have my view where I'm rendering objects of this model. And I need to build some HTML tables based on the quantity of each objects' rows and cols.
View:
get_tables(request):
tables = Table.objects.all()
return render(request, 'tables.html', {'tables': tables})
I'm trying to do something like:
{% for table in tables %}
<table>
<thead>
<tr>
{% for col in table.cols %}
<th>column label here</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for row in table.rows %}
<tr>my row</tr>
{% endfor %}
</tbody>
</table>
{% endfor %}
I know it is possible to loop for key in dict. But the values cols and rows are integers. How can I achieve this on a Django template?

Try
{% for table in tables %}
<table>
<thead>
<tr>
{% with ''|center:table.cols as range %}
{% for _ in range %}
<th>column label here</th>
{% endfor %}
{% endwith %}
</tr>
</thead>
<tbody>
{% with ''|center:table.rows as range %}
{% for _ in range %}
<tr>my row</tr>
{% endfor %}
{% endwith %}
</tbody>
</table>
{% endfor %}

# You can take use of filter tags in django template
# For Example
Step 1:- Create 'templatetags' package in your app folder.
Step 2:- Create filter.py in 'templatetags' package
Step 3:-
from django import template
register = template.Library()
def table_rows(value):
value_list = [value]
html_row = ''
for val in value_list:
html_row += '<tr></tr>'
return html_row
def table_cols(value):
value_list = [value]
html_cols = ''
for val in value_list:
html_cols += '<td>Hello</td>'
return html_cols
register.filter('table_rows', table_rows)
register.filter('table_cols', table_cols)
Step 4:-
# Your template can be:-
{% load filter %}
{% for table in tables %}
<table border="1">
{% autoescape off %}
{{table.rows|table_rows}}
{{table.cols|table_cols}}
{% endautoescape %}
</table>
{% endfor %}
# You can make changes according to your requirement

Related

nested loop with differents data

I have two lists:
campaigns = [{"name":"test", "client": "test_client", "reporter": "myself", "price": 45}...]
filters = ["name", "client", "reporter"]
I want my table to just display the data contained in the filter.
<tbody>
{% for campaign in campaigns %}
<tr role="row" class="odd">
{% for filter in filters%}
<td>{{campaign.filter}}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
Those are 2 differents lists, but I want to use the filters list to get the keys in the campaigns list, I tried multiple writing but it didn't work:
{{campaign[filter]}}
{{campaign}}.{{filter}}
Do you have any idea ?
Thank you.
<tbody>
{% for campaign in campaigns %}
<tr role="row" class="odd">
{% for key, item in campaign.items%}
{% for filter in filters %}
{% if key == filter %}
<td>{{item}}</td>
{% endif %}
{% endfor %}
{% endfor %}
</tr>
{% endfor %}
</tbody>
With this code I was able to retrieve my data in a nested loop. In case this might help someone.

Flask - Query CSV and Pass Results to render_template()

I have created two web pages - index and reports.
The index page contains an input box where the user can enter a Zip Code. When the submit button is pressed, the code reads in and queries a CSV file based on the Zip Code. The results are then passed to render_template.
When I run my code, all that displays on the reports page is the header row of the CSV file.
I am not sure what I am doing incorrectly.
Below is a snippet of my app.py file
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/reports', methods=['POST'])
def reports():
zip_code = request.form.get('zip_code')
df = pd.read_csv('real-estate.csv')
myData = df[df['zip'] == zip_code]
return render_template('reports.html', zip_code=zip_code, myData=myData)
Below is the contents of my reports file.
{% extends 'base.html' %}
{% block content %}
<div class='container'>
<h2>Real Estate Transactions</h2>
<ul>
{% for rec in myData %}
<li>{{ rec }}</li>
{% endfor %}
</ul>
</div>
{% endblock %}
Try using iterrows() to iterate over the rows of the dataframe.
<ul>
{% for key,value in myData.iterrows() -%}
<li id="row-{{key}}">{{value}}</li>
{% endfor -%}
</ul>
An example of a table would then look something like this.
<table>
<thead>
<tr>
{% for column in myData.columns -%}
<th>{{column}}</th>
{% endfor -%}
</tr>
</thead>
<tbody>
{% for key,value in myData.iterrows() -%}
<tr id="row-{{key}}">
{% for v in value.values -%}
<td>{{v}}</td>
{% endfor -%}
</tr>
{% endfor -%}
</tbody>
</table>

Jinja2 setting and using variables

I have the following
<thead>
<tr>
<th>Name</th>
{% if datas|length > 0 %}
{% set longest = [] %}
{% for data in datas %}
{% if data['numbers']|length > longest|length %}
{% set longest = data['numbers'] %}
{% endif %}
{% endfor %}
{% for i in longest %}
<th></th>
{% endfor %}
{% endif %}
</tr>
</thead>
I am trying to make enough headers to accommodate the longest list of numbers in the datas dictionary.
Can anyone see what I am doing wrong?
Chris

I was going to render the saved data into html table but found this error

<tbody>
{% for publication in publication_list %}
<tr>
<td>{{%publication.addpublication%}}</td>
</tr>
{% endfor %}
</tbody>
views.py
def publicationlist(request):
context = {'publication_list' : AddPublication.objects.all()}
return render(request,"publication_list.html", context)
TemplateSyntaxError at /addpublication/publicationlist/
Could not parse the remainder: '%publication.addpublication%' from '%publication.addpublication%'
# You have to remove % in your td tag of html
<tbody>
{% for publication in publication_list %}
<tr>
<td>{{publication.addpublication}}</td>
</tr>
{% endfor %}
</tbody>
For tags like for, if...:
{% for %}{% endfor %}
For context variables:
{{ my_context_variable }}

Return an extra argument with the datachart

I'm trying to print a chart and to return an argument with the datachart to the template.
Views.py:
def errors(request):
totalErrors = total_errors()
table = table_errors()
return render_to_response('macaco_errores.djhtml', {'totalErrors': totalErrors, 'table': table})
There's no problem to print the chart without the 'table' argument, but with both I get 'False' in template when I load in "load_chart".
EDIT:
Template:
{% block head %}
{% load nvd3_tags %}
{% include_chart_jscss %}
{% load_chart charttype totalesData totalesContainer extra %}
{% endblock %}
{% block body %}
<div align="center">
<h1>Errors</h1>
{% include_container totalesContainer 600 1000 %}
</div>
<div align="center">
<table border="1">
<tr>
<th>Log</th>
<th>Type</th>
</tr>
{% for type,log,date in table.items %}
<tr>
<td>{{ type }}</td>
<td>{{ log }}</td>
</tr>
{% endfor %}
</table>
</div>
{% endblock %}
{% load_chart charttype totalesData totalesContainer extra %}
This tag is needing four variables in the context: charttype, totalesData, totalesContainer, extra
It appears you are not passing any of them from your view function (which provides only totalErrors and table)
So there is no way that this can work from the code you've posted.
See this example from the django-nvd3 docs for the type of context data you need to provide from your view function:
http://django-nvd3.readthedocs.org/en/latest/introduction.html#example-how-to-create-a-piechart
Please see also the Django docs for how to pass variables from the view function into the template for rendering.
For example in your view you are currently using the render_to_response helper which takes a dict of variable names and values to pass to the template... these are the only vars which are available in the template.
The solution was:
def counterroresmacaco(request):
errores = errores_macaco()
errores['tabla'] = tipoerror_ticker()
return render_to_response('macaco_errores.djhtml', errores)
'errores' is a dictionary, then in the template I use a for to iterate over 'tabla'.
The problem to pass two arguments (as I was doing) is that django-nvd3 doesn't recognize the arguments like in the examples.
{% load nvd3_tags %}
{% include_chart_jscss %}
{% load_chart charttype totalesData totalesContainer extra %}
{% include_container totalesContainer 600 1000 %}
<table border="1">
<tr>
<th>Tipo de log</th>
<th>Ticker</th>
</tr>
{% for reg in tabla %}
<tr>
<td>{{ reg.log }}</td>
<td>{{ reg.ticker }}</td>
</tr>
{% endfor %}
</table>