Variable which is a database query doesnt render properly in template - django

My template doesnt render the key , values for the variable table which is a dictionary.
{% for key, value in table.items %}
<p> {{key}} : {{value}}</p>
{% endfor %}
The was how the variable 'table' was derived. Client is a model and Client_FirstName is the attribute of the model.
table = Client.objects.filter(Client_FirstName__startswith='p').values()
I am just trying to do a database query which i just learn from here

There may not be any data in the database. Try this.
{% if table|length %}
{% for key, value in table.items %}
<p> {{ key }} : {{ value }}</p>
{% endfor %}
{% else %}
<div>There are no data in the database</div>
{% endif %}

I was rendering the database values wrongly on the template , this is how it should be done for a list of dictionary
{% for x in table %}
{% for key,values in x.items %}
<p> {{key}} : {{values}} </p>
{% endfor %}
{% endfor %}

Related

How to display N number of Backward relationship in Django templates?

{% for category in categories %}
{% for product in categories.product_set.all %}
<h1> {{ product.name }} </h1>
{% endfor %}
{% endfor %}
I want to show 10 products instead of all in template
There is a slice filter that you can use in templates:
{% for category in categories %}
{% for product in categories.product_set.all|slice:":10" %}
<h1> {{ product.name }} </h1>
{% endfor %}
{% endfor %}

Django showing values of an annotated queryset without knowing the filed name

I´m building a dashboard where you can cross data from a sales database.
For example, sales by seller, products by client, etc. I let the user choose both option 1 and option 2.
I get the form back to the view and annotate the model with those options:
if filter_opts.is_valid():
option_1 = filter_opts.cleaned_data["option_1"]
option_2 = filter_opts.cleaned_data["option_2"]
results = ventas.values(option_2).annotate(Count(option_1, distinct=True))
The annotation works fine and if I just print the queryset in the template
{% for case in results %}
{{ case }}
{% endfor %}
I can see it like:
{'cliente': '502 EMSUR', 'prod_nombre__count': 9}
Then in the template I want to show only the values. But I can´t tell forehand which would be the value name to do something like this:
{% for case in results %}
{{ case.option_1 }}
{{ case.option_2 }}
{% endfor %}
If I iterate over the result I can see the field name:
{% for case in results %}
{% for item in case %}
{{ item }}
{% endfor %}
{% endfor %}
How can I show the values of that fields?
Thanks!
Since each case in results is a dictionary, you can use the property .items inside the template to iterate through its keys and values:
{% for case in results %}
{% for item, value in case.items %}
{{ item }} - {{ value }}
{% endfor %}
{% endfor %}

Django template: check for empty query set

Is there a way to check for an empty query set in the Django template? In the example below, I only want the NOTES header to be displayed if there are notes.
If I put an {% empty %} inside the "for" then it does display whatever is inside the empty tag, so it knows it's empty.
I'm hoping for something that does not involve running the query twice.
{% if notes - want something here that works %}
NOTES:
{% for note in notes %}
{{note.text}}
{% endfor %}
{% endif %}
Clarification: the above example "if notes" does not work - it still displays the header even with an empty query set.
Here's a simplified version of the view
sql = "select * from app_notes, app_trips where"
notes = trip_notes.objects.raw(sql,(user_id,))
return render_to_response(template, {"notes":notes},context_instance=RequestContext(request))
Edit: the view select selects from multiple tables.
Have a look at the {% empty %} tag.
Example from the documentation
<ul>
{% for athlete in athlete_list %}
<li>{{ athlete.name }}</li>
{% empty %}
<li>Sorry, no athletes in this list.</li>
{% endfor %}
</ul>
Link: https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#for-empty
If you are interested in a table, or some kind of heading if there are results, add the forloop.first:
{% for athlete in athlete_list %}
{% if forloop.first %}
Athlete Name:
{% endif %}
{{ athlete.name }}
{% empty %}
Sorry, no athletes in this list.
{% endfor %}
Try {% if notes.all %}. It works for me.
In your view check whether notes is empty or not. If it is then you pass None instead:
{"notes": None}
In your template you use {% if notes %} as normal.
It's unfortunate that you're stuck using a raw query set - they're missing a lot of useful behavior.
You could convert the raw query set into a list in the view:
notes_as_list = list(notes)
return render_to_response(template, {"notes":notes_as_list},context_instance=RequestContext(request))
Then check it as a boolean in the template:
{% if notes %}
Header
{% for note in notes %}
{{ note.text }}
{% endfor %}
{% endif %}
You could also make it happen without conversions using forloop.first:
{% for note in notes %}
{% if forloop.first %}
Header
{% endif %}
{{ note.text }}
{% endfor %}
What about:
{% if notes != None %}
{% if notes %}
NOTES:
{% for note in notes %}
{{ note.text }}
{% endfor %}
{% endif %}
{% else %}
NO NOTES AT ALL
{% endif %}
Your original solution
{% if notes %}
Header
{% for note in notes %}
{{ note.text }}
{% endfor %}
{% endif %}
Works now with Django 1.7 and thanks to QuerySet caching, it does not cost and extra query.
Often the right way to do this is to use the {% with ... %} tag. This caches the query so it runs only once and also gives you more flexibility with your markup than using {% empty %}.
{% with notes as my_notes %}
{% if my_notes %}
<ul>
{% for note in my_notes %}
<li>{{ note }}</li>
{% endfor %}
</ul>
{% else %}
<p>Sorry, no notes available</p>
{% endif %}
{% endwith %}
With this particular example I'm not sure how useful it is but if you're querying Many-to-Many field, for instance, it's likely what you want to do.
Use {% empty %} in django templates
{% if list_data %}
{% for data in list_data %}
{{ data.field_1 }}
{% endfor %}
{% else %}
<p>No data found!</p>
{% endif %}
We can write above code with {% empty %}.
{% for data in list_data %}
{{ data.field_1 }}
{% empty %}
<p>No data found!</p>
{% endfor %}

How do I get the first list objects value using a second list objects result in a django template

I have two object lists: firstobjectlist and secondobjectlist. With these two lists I want to get the values of the first object using the second object list result values.
For example:
{% for i in firstobjectlist %}
{% for value in secondobjectlist %}
<td align="left">{{i{{value.id}}}}</td>
{% endfor %}
{% endfor %}
When I excute the above code I get the error:
"Could not parse the remainder: '{{value.id' from 'i.{{value.id'"
Can anyone help show me how it should be done?
Firstly, django template variables have to have a space between the {{ and the contents.
You could use the with tag (presuming that the value of value.id is a key or index in firstobjectlist):
{% for i in firstobjectlist %}
{% for value in secondobjectlist %}
{% with value.id as j %}
<td align="left">{{ i.j }}</td>
{% endwith %}
{% endfor %}
{% endfor %}

Django fieldset.html customization. How to customize a single field?

In my app, I need to add javascript to the admin template "fieldset.html" in order to create a widget for a single field.
But, in the fields iteration (for), when I try to catch the specific field, I fail.
I'm doing by the ifequal tag (fieldset.html):
{% for line in fieldset %}
<div class="form-row{% if line.errors %} errors{% endif %}{% for field in line %} {{ field.field.name }}{% endfor %}">
{% for field in line %}
(...)
{% ifequal field.label_tag "name" %}
#do something
{% endifequal%}
(...)
{% endfor %}
</div>
{% endfor %}
Any sugestions? The field stores the recurrence of a schedule. So I need to do something dinamic, that's why I'm thinking about using javascript.
"Form Media"