I have the followed class-based views in my views.py file:
class HomeView(TemplateView):
template_name = 'annual_means/home.html'
site_list = AnnualMean.objects.values("site").distinct()
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
context['sites'] = AnnualMean.objects.values("site").distinct()
return context
At the top of my html template, just for testing this out, I have {{sites}} and it is displaying:
Below, I have the following html code:
{% for value in sites %}
<li>{{value}}</li>
{% endfor %}
And it lists all the key:value pairs as shown above, eg {'site': 'Belfast Centre'}, instead of just the values. I assume this is due to the dictionary in the QuerySet being nested within a list. Is there a way I can return just the a dictionary or otherwise get around this problem?
I think you should use this as :
{% for value in sites %}
<li>{{value.site}}</li>
{% endfor %}
It will now print the values in list
You can access a key in a dictionary using the dot notation :
Dictionary lookup, attribute lookup and list-index lookups are implemented with a dot notation:
{{ my_dict.key }} {{ my_object.attribute }} {{ my_list.0 }}
For your code, that would be:
{% for value in sites %}
<li>{{value.site}}</li>
{% endfor %}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.