I am editing a template to display an attribute of the first member in a list. I am trying to access it like so:
{{ food_list.index(0).id }}
I get an error that says Could not parse the remainder: '(0).id'.
What is the correct way to access an individual member in a list?
{{ food_list.0.id }}
Alternatively,
{% with f=food_list|first %}
{{ f.id }}
{% endwith %}
You can't call methods in a template. Either write a template tag for this, or do it in your view. If what you wanted to do was just index the list, then you don't use the index() method for that; just use normal dot notation instead.
Related
I have a dictionary passed (as part of another object) to the django template language.
The object, called 'poll' has attributes self.text and self.votes, where the former is a string, and the latter is a dict.
The dict, looks like this:
{'a1': 45.92422502870264, 'a2': 53.50172215843857}
I am trying to list each label, with its accompanying number, using the following:
{% for l, x in poll.votes %}
<p>{{ l }} {{ x }}</p>
{% endfor %}
Django responds with
Exception Type: ValueError
Exception Value: Need 2 values to unpack in for loop; got 3.
I tried .iteritems - The docs explain that .iteritems is not the correct way to do this, but they don't explain what the correct way is.
You just iterate the same way you would in python, but in Djangos templating language (DTL) syntax
{% for key, value in dictionary.items %}
Your poll.votes is a dict but you're not iterating the items but the keys in your code.
You can find an overview of jinja here. Its worth noting that jinja isn't what django uses but its handy for a condensed reference since many things are the same (jinja is based upon DTL) instead of digging through djangos docs.
For Djangos tempaltes heres the documentation reference
you too can do this:
{% for variable in poll %}
{{ variable.name }} - {{ variable.votes }}
{% endfor %}
I am passing list called 'list' to view and i want to create links with href attribute as value of list element iterated by forloop.counter0.
As far as I know getting list element requires such code :
{{ list.0 }}
But how can I iterate with forloop.counter0 values?
What I do is something like this :
{% for name in names %}
<tr>
<a href="/foo/bar/{{ list.forloop.counter0 }}">
{{ name }}
</a>
</tr>
{% endfor %}
But that doesnt apply any value and I tried with some more bracketting, but no succes.
How can I do it?
Edit: OK, thanks for the clarification. I'd suggest a custom templatetag.
Create a yourapp/templatetags/ dir. In that, create a blank file named __init__.py (this is required for Django to acknowledge the folder) and a file called custom_tags.py.
In custom_tags.py create a tag like so:
from django import template
register = template.Library()
#register.filter('list_index')
def list_index(mylist,index):
return mylist[index]
Not in your template, add to the top:
{% load custom_tags %}
to import/initialize the library.
Now you can use this tag like so:
<a href="/foo/bar/{% list_index list forloop.counter0 %}">
to retrieve the item from your list at index provided by forloop.counter0.
Quick note - list is in the Python standard library, so never use it as a variable name (just in case this is mirroring your code).
I am using django i18n for supporting i18n. I've found out that in django blocktrans an object, dict directly doesn't work.
For example if I've got a object with name obj and i try using it like
{% blocktrans %} My name is {{ obj.name }} {% endblocktrans %}
will not work, but if I use it like
{% blocktrans with name=obj.name %} My name is {{ name }} {% endblocktrans %}
will work.
I just wish to know why first example didn't work but second worked.
Django's blocktrans are passed to ugettext, which mark them as translation strings in the u"My name is %(name)s" form, which at runtime are processed with the context as mapping, ie `u"My name is %(name)s" % context. This does not allow for Django template style attribute resolution.
From the Django documentation "To translate a template expression -- say, accessing object attributes or using template filters -- you need to bind the expression to a local variable for use within the translation block"
Without delving into the template code I would guess that the translation operation is performed before the getattr/automatic calling stuff that django does when rendering a template.
Is there any get() function for this instead?
{% for key, value in choices.items %}
<li>{{key}} - {{value}}</li>
{% endfor %}
From python I have the get() function to get values from a specific key. But I couldn't find a corresponding way to do that with django template tags. So I wonder is it possible?
I need to get specific values since using loops adds a lot of new lines in the html source.
Or should take care of the output inside the view before sending it out to the template, which method is better?
You can use {{ choices.items.key }} to access a specific dict element.
There is no reason to care about whitespace in the HTML code though; the typical end-user has no real business in reading it and if he's curious he an always use a DOM viewer or run it through a HTML beautifier.
If you want a specific value, just add it to the dotted-path:
{{ choices.items.somekey }}
will get you the value of choices.items['somekey'] if choices.items is a dict.
I think you are way advance now, just to share my point. you could do this way as well
{% for value in dict %}
{{value}}
{% endfor %}
or with key, value like
{% for key,value in dict.items %}
{{key}} : {{ value }}
{% endfor %}
If choices type is DICT like {}.
{{choices.somekey|default:""}}
If choices.items is DICT type.
{{choices.items.somekey|default:""}}
Try See little example.
# In Views.py
def dict_test(request):
my_little_dict = {"hi": "Hello"}
....
# in Template
{{my_little_dict.hi}}
You can specify as {{ choices.key_name }}
It worked for me. Just simple
{{ choices.values }}
This gives you a list of all the values in the dictionary at once.
This may be simple, but I looked around and couldn't find an answer. What's the best way to reference a single item in a list from a Django template?
In other words, how do I do the equivalent of {{ data[0] }} within the template language?
It looks like {{ data.0 }}. See Variables and lookups.
A better way: custom template filter: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/
such as get my_list[x] in templates:
in template
{% load index %}
{{ my_list|index:x }}
templatetags/index.py
from django import template
register = template.Library()
#register.filter
def index(indexable, i):
return indexable[i]
if my_list = [['a','b','c'], ['d','e','f']], you can use {{ my_list|index:x|index:y }} in template to get my_list[x][y]
It works fine with "for"
{{ my_list|index:forloop.counter0 }}
Tested and works well ^_^
{{ data.0 }} should work.
Let's say you wrote data.obj django tries data.obj and data.obj(). If they don't work it tries data["obj"]. In your case data[0] can be written as {{ data.0 }}. But I recommend you to pull data[0] in the view and send it as separate variable.
#jennifer06262016, you can definitely add another filter to return the objects inside a django Queryset.
#register.filter
def get_item(Queryset):
return Queryset.your_item_key
In that case, you would type something like this {{ Queryset|index:x|get_item }} into your template to access some dictionary object. It works for me.