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.
Related
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
I have a simple contacts application where I want to paginate the contact list based on first name alphabet.
Here is my views.py
def contacts(request):
contact_list = Contact.objects.filter(user=request.user).order_by('first_name')
return render(request, 'contact/contact.html', {'contact_list': contact_list})
Here is my template
<ul>
{% for contact in contact_list %}
<li>{{ contact.first_name }}</li>
{% endfor %}
</ul>
Is there a default way in Django that does this? There is Django pagination but I think that only splits data across pages. What would be the easiest way to do so?
It seems a letter-wise paginator does not exist by default. Pages like https://djangosnippets.org/snippets/1364/ <<< this one show hand-made implementations.
However, it's not so hard to implement: you can base yourself on startswith keyword and:
pages = [myQuerySet.filter(myfield__istartswith=i) for i in "ABC...XYZ"] #full alphabet here
(let myQuerySet be, actually, contact_list; let myfield be, actually, first_name).
I've done this once, by adding a letter field to my model and "paginating" manually. This raised a lot of interesting situation with foreign alphabets. Found this useful: https://pypi.python.org/pypi/Unidecode
Didn't find any "smarter" way to go about it. But I'd be interested in hearing about more "plug-n-play" solution...
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.
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
I have a formset created using inlineformset_factory. It doesn't matter what it looks like to answer this question. In the template I am looping through it with for form in forms.formset:
I want to be able to display the form index of the form in my template. By form index, I mean the number associated with that form in all of the formfields. Is there a variable that does this? I tried form.index and form.form_id and form.id is a field.
No, objects in a collection don't generally have access to their index or key.
However if you're outputting the formset in a template, you're presumably looping through the forms. So you can use {% forloop.counter %} to get the index of the iteration.
Although it is not pretty, based on the formset source and the comment by #yuji-tomita-tomita above, you could do something like this in your template:
{{ form.prefix|cut:formset.prefix|cut:'-' }}
This just takes the form prefix string, which includes the form index, then removes the irrelevant parts. In the view you could simply do e.g. form.prefix.split('-')[1].