I have been searching for a way to make a django template which can show more than 2 values per row in a table,
Let's say I have an class with 5 attributes, and I want these attribute values presented in a table on my HTML page. at first I tried with a dictionary but just 2 of the 5 attributes is not enough.
Lets say my object is like:
class ModelA(models.Model):
ID = models.IntegerField(primary_key=True, db_column='ID')
name = models.CharField(max_length=60, db_column='name')
yesorno = models.CharField(max_length=9, db_column='yes/no')
text = models.TextField(db_column='text')
description = models.TextField(db_column='description')
Now in a view I call for all these model attributes, in what datastructure should I save everything and how can I put all these 5 attributes in one row per object in a table.
(sometimes hundreds of objects may need to be shown in table (so, 100 rows))
Grab all the objects (filter accordingly).
As #init3 points out the ID is not required as Django adds that automatically, and yesorno should be a Bool.
# view.py
model_as = []
for id in ids:
try:
model_a = ModelA.objects.get(ID=id)
except ModelD.DoesNotExist:
# No model found
pass
else:
model_as.append(model_a)
return render_to_response('template.html',
{'model_as': model_as},
context_instance=RequestContext(request))
Loop over the objects in the template and print each variable in whichever column you want.
# template.html
<table>
{% for model_a in model_as %}
<tr>
<td>
{{ model_a.ID }}
{{ model_a.name }}
{{ model_a.yesorno }}
{{ model_a.text }}
{{ model_a.description }}
</td>
<tr>
{% empty %}
<tr>
<td>No ModelAs to see here</td>
<tr>
{% endfor %}
</table>
Related
I created a table in my html file for my Django project, and the raw data is based on the following list (It's a very long list, so I only list a few lines):
mylist=
[{'StartDate': '2021-10-02', 'ID': 11773, 'Receiver': Mike, 'Days':66 },
{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Jane, 'Days':65},
...
{'StartDate': '2021-10-5', 'ID': 34653, 'Receiver': Jack, 'Days':63}]
My Html file:
<table class="table table-striped" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>StartDate</th>
<th>ID</th>
<th>Name</th>
<th>Days</th>
</thead>
<body>
{% for element in mylist %}
<tr>
<td>{{ element.StartDate}}</td>
<td>{{ element.ID }}</td>
<td>{{ element.Receiver }}</td>
<td>{{ element.Days }}</td>
</tr>
{% endfor %}
</tbody>
</table>
I want to make all the rows with the same ID value the same color. Please advise what I should add into the <td>{{ element.ID }}</td>. Thank you!
parts of my views.py:
client = gspread.service_account_from_dict(creds)
def CreateSheet(Return_record):
sheet = client.open(Return_record).sheet1
return sheet
from sheet2api import Sheet2APIClient
sheet = client.open('Return Record 2022')
sheet_instance = sheet.get_worksheet(0)
mylist = sheet_instance.get_all_records()
mylist
def table2022(request):
return render(request,'table2022.html',{'mylist':mylist})
Everything we want to pass as context, we should keep inside view we want to use it in. It's more readable when we have more and more code.
What we are going to do, it's define a color for numbers 0-9. I'll pick some light colors for now, you can change them as you prefer.
views.py:
def table2022(request):
mylist = sheet_instance.get_all_records()
colors = {'0': 'aqua', '1': 'beige', '2': 'burlywood', '3': 'lightgrey', '4': 'silver', '5': 'skyblue', '6': 'lightblue', '7': 'lightpink', '8': 'lightgreen', '9': 'lawngreen'}
context = {'mylist': mylist, 'colors': colors}
return render(request, 'table2022.html', context)
Now, because in templates it's not that simple to use Python, we need to create custom Template Tag. Let's start with creating folder in your app, let's name it custom_tags.py. It should be created in YourProject/your_app/templatetags/ folder, so we have to also create templatetags folder in there.
custom_tags.py:
from django import template
register = template.Library()
#register.filter(name='get_color')
def get_color(colors, number):
return colors[str(number)[-1]]
your_template.html:
{% load custom_tags %}
...
{% for element in mylist %}
<tr>
<td>{{ element.StartDate }}</td>
<td style="background-color: {{ colors|get_color:element.ID }}">
{{ element.ID }}
</td>
<td>{{ element.Receiver }}</td>
<td>{{ element.Days }}</td>
</tr>
{% endfor %}
get_color tag is basically taking whole ID, then extract only last number and make it a string. After that it uses the single number as a key in colors dictionary and passes corresponding value to template, where it is going to be a valid html color.
Custom tags are used to 'implement' some Pythonic code directly into template. Don't use it too much, because most of coding should be in standard files like views.py and models.py. But sometimes there is no better way. :)
For more details about Tags, check that Django's DOCS
I have a class HardBook that inherits from Book:
class Book(models.Model):
title = models.CharField('Book Title', max_length=200)
image = models.ImageField('Book Cover', upload_to='covers')
description = models.CharField('Description', max_length= 350)
class HardBook(Book):
quantity = models.IntegerField('Quantity')
views.py
class BookCreateView(CreateView):
def get_context_data(self,**kwargs):
context = super(BookCreateView, self).get_context_data(**kwargs)
context['softbooks'] = SoftBook.objects.all()
context['hardbooks'] = SoftBook.objects.all()
return context
I want to display the field data in a table, I want to show title, image and quantity. Everthing is displayed except quantity.
{% for hardbook in hardbooks %}
<tr>
<td>
<div class="cover-image" style="background-image:url({{hardbook.image.url}});"></div>
</td>
<td>{{hardbook.title}}</td>
<td>{{hardbook.quantity}}</td>
</tr>
{% endfor %}
I have a simple Flask application with just one table.
So python code is irrelavantly simple:
#app.route('/')
def home():
items = long_db_request()
return render_template("index.html", items=items)
#app.route('/extended')
def extended():
return render_template("animals.html")
And items is a huge JSON object.
I created a table which reflects that data:
<table>
<tr>
<th style="text-align:center">id</th>
<th style="text-align:center">creation time</th>
<th style="text-align:center">name</th>
<th style="text-align:center">animals</th>
<th style="text-align:center">number</th>
</tr>
{% for item in items %}
<tr>
<td> {{ item.id }} </td>
<td> {{ item.time }} </td>
<td>
{{ item.name }}
</td>
<td> {{item.group}} </td>
<td>{{ item.group|length }}</td>
</tr>
{% endfor %}
</table>
The table looks like:
As you can see, column animal contains a lof of object which makes it all difficult to percieve.
I want it to be like this
which is a lot easier to get. And show animals is a link to another page, where a pure json exists.
How can I achieve this?
I followed the doc of jinja2 and Flask and found method url_for() but in that case I have to pass all my json in query which is unacceptable..
How can I jump from first image to exellent nice view of the second one?
working code with the first picture is place here
Thank you very much in advance!
P.S. I only saw one question here with rellevant topic, but it does not help me
Instead of passing all the animals (e.g. cats) from one view to another, just pass the category cats to the next page.
The view function for the next page then selects all cats from the json, and passes the cats then to the detailed view.
So, on you overview page, you render links like species.html?cats (and so on), and when somebody clicks on these links the view function selects all cats, and then passes them into a render_template("species.html", species=cats) view.
I'm using jinja2 and python.
Everything works but a table printed based on a string of arrays, this is the template
<table>
<tr>
<th> {{table.title}}</th>
</tr>
<tr>
{% for value in table.values %}
<td> {{ value }} </td>
{% endfor %}
</tr>
</table>
Table is defined in data in the pyton:
data['table'] = {
'title': 'Title',
'values': ['test','test2']
}
templateVars = data.copy()
templateEnv = jinja2.Environment(
loader=jinja2.FileSystemLoader(f'{package_directory}/assets/templates/'))
outputText = template.render(templateVars)
When executing I get an error:
{% for value in table.values %}
TypeError: 'builtin_function_or_method' object is not iterable
I can't find the error, because I created a list, and it should be iterable. I copied the same code to python and it works.
I solved my problem, it was I was using "values" as key and it's a reserved word, changing it for table_rows it works
My data are like this :
13.2610136284,20.8676059554,11.6376896892,0.51203356592,167,20154.4815106,
395,766,56,55047.3477967,-26818.1766435,3072.97868784,12.5402166873,-1443.
74556748,-4.0
I need to display it as a table in html
This is the function used in python to transform the data suitable for a table
import string
from datetime import datetime, date
def ratio_fil():
ratioFil = open('sergRatiosOut20170426','r')
rat = ratioFil.read().split(',')
ratioFil.close()
return rat
Rat is similar to this :
['13.2610136284', '20.8676059554', '11.6376896892', '0.51203356592',
'167', '20154.4815106', '395', '766', '56', '55047.3477967',
'-26818.1766435', '3072.97868784', '12.5402166873', '-1443.74556748',
'-4.0\r\n']
I need to put it in a table, So i create a data_table tags :
<tr><td>X</td>
<td>{{data_table.0|floatformat:1}} %</td></tr>
<tr><td>y</td>
<td>{{data_table.1|floatformat:1}} %</td></tr>
<tr><td>y1 </td>
<td>{{data_table.2|floatformat:1}} </td></tr>
<tr><td>y2</td>
<td>{{data_table.3|floatformat:1}} </td></tr>
In Html :
<div> {% with rat as data_table %}
{% include 'tags/data_table.html' %}
{% endwith %}
</div>
The table appears empty, i think it should be a method to import rat ? Please i need your help
You can use builtin for loop template tag to loop through and render the data in HTML table
<table>
<tr>
<th>Column Name</th>
</tr>
{% for data in data_table %}
<td>
<td>{{ data }} </td>
</td>
{% endfor %}
</table>
Remember to return the data from your view
def ratio_fil():
ratioFil = open('sergRatiosOut20170426','r')
rat = ratioFil.read().split(',')
ratioFil.close()
return render(request, 'template_name.html', {'data_table': rat})