Django - Calling list or dict item using a variable in template

2024/10/13 6:15:27

I'm trying to call a dictionary or list object in a template using a variable in that template with no results.

What I'm trying to is identical to this general python code:

keylist=['firstkey','secondkey','thirdkey',]
exampledict={'firstkey':'firstval','secondkey':'secondval','thirdkey':'thirdval',}for key in keylist:print(exampledict[key])#Produces:#firstval#secondval#thirdval

Things work a little different in the django template. I have a variable defined as key='firstkey' passed onto the template. If i want to call the same dictionary:

{{ exampledict.firstkey }} #Produces: firstval
{{ exampledict.key }} #Produces: None

Django template for loops also has a produced variable forloop.counter0, increasing from 0 in the firstloop to n-1 in the last loop, this cannot call list objects. I have a list:

tabletitles=['first table', 'second table', 'third table']

And I want to call and create tables in a loop, putting the table titles for the respective tables above like so:

{% for table in tables %}
<h3> first table </h3>
<table>
...
</table>
{% endfor %}

What I would like to do in this case is

{% for table in tables %}
<h3> {{ tabletitles.forloop.counter0 }} </h3>
<table>
...
</table>
{% endfor %}

Which doesn't work either, since I can't use a separate variable to call an object for a dict or list in the template. Is there a way to get this to work, or a better way to do it all together?

Answer

The Django template language does not let you access dictionary keys and lists with variables. You could write a template tag to do this (see this question for example), but in your case there's a simpler alternative.

In your view, zip your tables and titles together

tables_and_titles = zip(tables, tabletiles)

Then loop through them together in your template.

{% for table, title in tables_and_titles %}{{ title }}<table>{{ table }}</table>
{% endfor %}
https://en.xdnf.cn/q/118111.html

Related Q&A

Multi-Classification NN with Keras error

I am getting an error when trying to do multi-classification with three classes. Error: TypeError: fit_generator() got multiple values for argument steps_per_epochCode Giving Error: NN.fit_generator(tr…

How to do time diff in each group on Pandas in Python

Heres the phony data:df = pd.DataFrame({email: [u1,u1,u1,u2,u2,u2],timestamp: [3, 1, 5, 11, 15, 9]})What I intend to retrieve is the time diff in each group of email. Thus, after sorting by timestamp i…

How to copy contents of a subdirectory in python

I am newbie to python, I am trying to achieve following task-I have a directory WP_Test containing a sub-directory test, I want to copy all the files and folders inside this sub-directory test to anoth…

Facing issue while providing dynamic name to file in python through a function

the line : with open(new%s.txt % intg ,a) as g : is giving error in below code. Every time I call the function "Repeat", it should create file with name new1.txt, new2.txt and so on. But it …

Python Pandas: Merging data frames on multiple conditions

I wish to merge data frames as fetched via sql under multiple condition. df1: First df contains Customer ID, Cluster ID and Customer Zone ID. The second df contain complain ID, registration number.…

counterpart to PILs Image.paste in PHP

I was asked to port a Python application to PHP (and Im not very fond of PHP).The part Im having trouble to port uses a set of monochromatic "template" images based on the wonderful Map Icons…

Google Cloud Dataflow fails in combine function due to worker losing contact

My Dataflow consistently fails in my combine function with no errors reported in the logs beyond a single entry of:A work item was attempted 4 times without success. Each time the worker eventually los…

AttributeError: super object has no attribute __getattr__

Ive been searching for the solution of this problem over the all internet but I still cant find the right solution. There are lots of generic answers but none of those have solved my problem..I am tryi…

Selenium load time errors - looking for possible workaround

I am trying to data scrape from a certain website. I am using Selenium so that I can log myself in, and then start parsing through data. I have 3 main errors:Last page # not loading properly. here I am…

How to POST ndb.StructuredProperty?

Problem:I have following EndpointsModels,class Role(EndpointsModel):label = ndb.StringProperty()level = ndb.IntegerProperty()class Application(EndpointsModel):created = ndb.DateTimeProperty(auto_now_ad…