Django: Printing a queryset dynamically in the template - django

How can I print the columns specified in "fields_i_want" instead of hardcoding the column names in the template code?
# Let's say I have this in my view:
foo = Foo.objects.filter(some_field='bar').select('field1', 'field2', 'field3')
fields_i_want = ['field1', 'field2']
# Then in the template I want to do something like this:
<TABLE id="some_id">
<TBODY>
{% for row in some_var.foo %}
<tr>
{% for value in another_var.fields_i_want %}
<td>{{ row[value] }}</td>
{% endfor %}
</tr>
{% endfor %}
</TBODY>
</TABLE>
# Instead of doing this:
<TABLE id="some_id">
<TBODY>
{% for row in some_var.foo %}
<tr>
<td>{{ row.field1 }}</td>
<td>{{ row.field2 }}</td>
</tr>
{% endfor %}
</TBODY>
</TABLE>

See this SO question.

Related

how to get random 1/2 data from database in jinj2 template in Django?

<table>
{% for field in fields %}
<tr>
<td>{{ field.name }}</td>
<td>{{ field.value }}</td>
</tr>
{% endfor %}
</table>
here we will get all the data from fields . but i want to only get randomly 1/2 (i can specified how many) data in jinja2 template from backend ?
How to do this ?
<table>
{% for field in fields %}
{% if forloop.counter < x %}
<tr>
<td>{{ field.name }}</td>
<td>{{ field.value }}</td>
</tr>
{% endif %}
{% endfor %}
</table>
just put your desired number in x,you are good to go.
Try this. You can add this logic to the frontend. This way it will display records with even ID. and those will 1/2 as well.
<table>
{% for field in fields %}
<tr>
{% if field.id%2 == 0 %}
<td>{{ field.name }}</td>
<td>{{ field.value }}</td>
{% endif %}
</tr>
{% endfor %}
</table>

How to print only certain cells of my table in Django templates?

I am developing an app in Django.
I have on my template (code 0):
{% for row in query_result %}
<tr>
{% for cell in row %}
<td>{{ cell }}</td>
{% endfor %}
</tr>
{% endfor %}
Let's suppose I want my template to print only the first and the third column of my matrix, how can I indicate to my template a specific cell?
I tryed with
{% for row in query_result %}
<tr>
<td >{{ cell[0] }}</td>
<td >{{ cell[2] }}</td>
</tr>
{% endfor %}
but it does not work.
EDIT:
As suggested, I tryed with (code 2):
{% for row in query_result %}
<tr>
<td >{{ cell.0 }}</td>
<td >{{ cell.2 }}</td>
</tr>
{% endfor %}
But this somehow erases the content of my cells, see here below.
results of Code 0:
results of code 2:
You can obtain an item at an index in Django's template engine by fetching it as you would fetch an attribute, so:
{% for row in query_result %}
<tr>
<td >{{ row.0 }}</td>
<td >{{ row.2 }}</td>
</tr>
{% endfor %}
That being said, I strongly advise to try to fix the problem upstream: instead of rendering a subset, take a look what you can do to limit the "columns" in query_result.
or you can unpack the elements and put the second item in a "throwaway" variable:
{% for cell0, __, cell2 in query_result %}
<tr>
<td >{{ cell0 }}</td>
<td >{{ cell2 }}</td>
</tr>
{% endfor %}
Use looks like {{ cell.0 }} this. The Django docs explain in the section variables and lookups.
So you would do something like:
{% for row in query_result %}
<tr>
<td >{{ cell.0 }}</td>
<td >{{ cell.2 }}</td>
</tr>
{% endfor %}

how to display retrieved data from database using django

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.

Iterating over user in django template

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").

Counting objects and showing the results in Django

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>