django template show only distinct value - python

Suppose I have a query:
cities = City.objects.all()
In my template I have done:
{% for city in cities %}
{{city.friend_name}}
View Detail
{% endfor %}
It gives me name of 4 friends with id say alex 1, matt 2, mack 3, mack 3. But here mack is repeated. I only want mack once. If the values are repeated I want it to be printed only once.
How can I do this in template. I mean is there something like {{city.friend_name|distinct}} or something else
I dont want unique city. I want friends name on city to be unique.
Thank you

Don't use extra input parameters, just use the "ifchanged" django builtin filter: https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#ifchanged
{% for city in cities|dictsort:'friend_name' %}
{% ifchanged %}{{city.friend_name}}{% endifchanged %}
View Detail
{% endfor %}
p.s. i know it's 3 years old but it's an helpful answer for someone else.

It is usually best to change your Query first to ensure you get the least amount of data.
In this case, you could edit your query as follows:
cities_with_uniq_friend_names = City.objects.all().distinct('friend_name')
Now when you iterate over cities_with_uniq_friend_names it will give you unique friend names

Why do you want to do it in the template? Try to modify cities itself so that it has unique entries.
You could convert your list to a set and then re-convert it back:
cities_unique = list(set(cities))
If you have to show unique attributes, use the regroup feature

Related

dictionary values can't be iterated through using their corresponding keys in django template [duplicate]

This question already has answers here:
Django template how to look up a dictionary value with a variable
(8 answers)
Closed 4 years ago.
So I have a nested dictionary in the form of the following:
data = { server:{'rating':{'class':'good, 'desc':'whatever'}, 'vulnerabilities':{'heartbleed':{'severity':'critical', 'desc':'terrible config'}}
I want to iterate through the values using keys, I've read the documentations and this is what I do in template:
{% for key, value in data.items %}
<p> 'This is the key {{ key }} and this is the value {{value}}'<p>
{% endfor %}
so far so good, the bizarre thing is that I can`t get the values using the key retrieved by the for loop, namely, when I have such a template:
{% for key in data.keys %}]
<p> 'This is the key: {{key}}' </p>
<p> 'This is the value: {{ data.key }}'<p>
{% endfor %}
{{key}} returns the keys with no problem. Even when I do {{data.server}} I get the corresponding values with no problem. Strange thing is that this line {{data.key}} does not work as I intuit it to.
In one loop the key==server, {{data.server}} works but {{data.key}} does not. What am I getting wrong here?
Only way to this dynamically in template engine is to use custom template filter
Take a look at Django template how to look up a dictionary value with a variable for primer implementation

How to iterate a queryset list in a django template

Is there a way to iterate this list of querysets in the template?
[<Director: Roman Polanski>, <Director: Alfred Hitchcock>,
<Director: Steven Spielberg>, <Director: David Lynch>]
I tried using a list syntax, but the django template language doesn't seem to accept lists, also.
Thank you all.
Django's template language does of course accept lists!
Here is what the code in your template should look like:
{% for director in director_list %}
{{ director }}
{% endfor %}
By the way: What you're having here is a queryset (that gets evaluated to a list), not a list of querysets.

django - multiplication and templates

I hope you can help me on this one. I have a template that shows the price of a, lets say a Banana, and for example the banana costs $400 and i have to calculate the 21% of this price and show it on a box of a table. I was tempted to do something like:
{% for banana in bananas %}
{{banana.price}}*(21%)
{% endfor %}
but obviously that failed miserably.
So, is there a way to do this type of simple equations in a template or i need to make a custom template tag to handle it.
its a very basic question but i would really appreciate the help.
Thank you.
You do need a custom template tag, but you could install django-mathfilters, which provides such basic operations:
{% load mathfilters %}
...
{{banana.price|mul:0.21}}
Taken from the mathfilters page, the included operations are:
sub – subtraction
mul – multiplication
div – division
abs – absolute value
mod – modulo
'Add' is provided in Django as standard.
You can use built-in widthratio template tag:
For creating bar charts and such, this tag calculates the ratio of a
given value to a maximum value, and then applies that ratio to a
constant.
{% widthratio banana.price 100 21 %}

two or more dots in a django template after the variable

In a django template, is it possible to have two (or more) dots after a variable? For example, say I have a list of objects that I first want to use a list-index lookup for and then once I have the object, I want to call its method for getting the absolute url, should that work?
For example:
{% for entry in myList %}
{{ entry.0.get_absolute_url }}
{% endfor %}
So the 0 is asking for the first item in the list which is an object, then I want to get the absolute url. It doesn't work when I try it but it doesn't return an error either. Is there a better way to accomplish what I'm trying to do?
To clarify it, what's strange is that:
This works:
{{ singleObject.get_absolute_url }}
In that case if I just try {{ singleObject }}, I get the unicode value of that object so something like: John Smith
This doesn't work:
{% for object in objectList %}
{{ object.get_absolute_url }}
{% endfor %}
But in this case, if I put in {{ object }}, I no longer get the unicode value. I get: [<Name: John Smith>] (name being the name of the model)
Basically, the method works when it's outside of a loop. Could there be any reason for that?
more than one dot absolutely works.
based on your comment, there is no entry.0 because entry IS the first item in the list cause you are already looping through `myList'
just use entry.get_absolute_url instead
but if you only want to print out the url for the first entry, forgo the for loop and just use myList.0.get_absolute_url
UPDATE:
there's a tip from 'the pragmatic programmer' that says:
``select’’ Isn’t Broken
It is rare to find a bug in the OS or the
compiler, or even a third-party product or library. The bug is most
likely in the application.
i think you assumed that django templates were behaving weird, when the truth is you were not building your list correctly. don't be afraid to show some of your actual code, by abstracting the problem for us, you removed the part that included the problem
I got it. I had brackets around each item in my list like so:
objectList = [['John Smith'], ['Jim Jones'], ['Bill White']]
Silly me! Thanks so much for your all your input
What you are doing is perfectly acceptable in Django templates. There is no better way to accomplish what you're trying to do.

use two variables in django template if tag

Hi all not sure how to explain this clearly but here goes....
I need to use two variables like so:
{% for client in clients %}
{% if user.client.username %}
I need {% if user.username %} but the value of username is in client.username from the loop.
is there a way to do this?
If I understand correctly, user is a dict, and you want to lookup the value indexed by client in each iteration of the loop - eg, user[client].username in Python.
This (deliberately) isn't possible in Django templates - the language is limited, to force you to do pre-processing in code.
Instead, you should zip your two lists/dicts together before passing them to the template.
Are you trying to do something if the value of client.username is equal to the value of user.client.username? If so, you want:
{% if client.username == user.client.username %} # Works in Django 1.2 and above
{% ifequal client.username user.client.username %} # Works everywhere

Categories