Reputation: 51
I can't access a dictionary value declared in my views.py, from my .html file.
I've been trying to use the several previous threads about this for hours and I just can't see it. I'm sure I'm doing something wrong.
views.py
def test(request):
now = datetime.now()
day = now.strftime("%Y-%m-%d")
year = now.strftime("%Y")
month = now.strftime("%m")
context = {
"content": [day,year,month],
"object_list": queryset
}
return render(request, "test.html", context)
filter.py
from django.template.defaulttags import register
@register.filter(name='get_item')
def get_item(dictionary, key):
return dictionary.get(key)
test.html
{% load filtres_dictionary %}
{% with content.get_item.day as content.day %}
<p>{{ content|get_item:content.day }}</p>
{% endwith %}
I am currently getting the following error message, and what I wanted to get is: 2019-06-13. Printed in my website.
VariableDoesNotExist at /test/ Failed lookup for key [day] in ['2019-06-13', '2019', '06']
Upvotes: 1
Views: 5126
Reputation: 477794
The above is not a dictionary value. It is a list. You can however access list elements through the index, like:
<p>{{ content.0 }}</p>
the line {% with content.get_item.day as content.day %}
makes not much sense: you here seems to assign a non-existing value to a hypothetical subdictionary.
That being said, I'm not convinced that using a list is a good idea here. You in fact indeed better use a dictionary, like:
context = {
'content': {
'day': day,
'month': month,
'year': year
},
'object_list': queryset
}
then you can access this in the template as:
<p>{{ content.day }}</p>
Note: the
get_item
template filter you use here, is useful if the key itself is variable, in which case you can thus pass an arbitrary key. That is not the case here.
Upvotes: 3