121π
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 ^_^
- [Django]-Disable session creation in Django
- [Django]-405 "Method POST is not allowed" in Django REST framework
- [Django]-Django limit_choices_to for multiple fields with "or" condition
26π
{{ 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.
- [Django]-How to set a value of a variable inside a template code?
- [Django]-Can't compare naive and aware datetime.now() <= challenge.datetime_end
- [Django]-Resource temporarily unavailable using uwsgi + nginx
2π
@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.
- [Django]-You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application
- [Django]-Get protocol + host name from URL
- [Django]-Django: Grab a set of objects from ID list (and sort by timestamp)
0π
first make sure that the app contain custom tag function is added to INSTALLED APP follow the instruction below
1 in the main directory app create another directory with name templatetags at the same level as model.py,views.py,urls.py.
2 inside of templatetags directory create init.py and another file with the name of your custom tags, for example: my_tags.py.
MainApp/
__init__.py
models.py
templatetags/
__init__.py
my_tags.py
views.py
in your template you would use the following:
{% load my_tags.py %}
in my_tags.py:
from django import template
register = template.Library()
@register.filter(name="get")
def get(indexable, i):
return indexable[i]
in views.py:
number = [0,1,2,3,4,5]
return render(
"index.html", {"number":number}
)
in index.html:
{% load my_tags %}
{{numer|get:forloop.counter0}}
reference How to create custom template tags and filters
i hope you understand, because ingles not my native language
- [Django]-Function decorators with parameters on a class based view in Django
- [Django]-Http POST drops port in URL
- [Django]-Django index page best/most common practice