Can I access specific key values in dictionary from django template? - python

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.

Related

Django dict key,value in for loop does not work

I'm getting a little stuck on a Django problem where I can't access the values of a dict in a for loop. It works outside the for loop, just not inside.
Am I missing the obvious here?
Python:
err{}
err['else'] = {'class': 'Low', 'txt': 'zero'}
err['if'] = {'class': 'High', 'txt': 'one'}
data = { 'errors': err }
return render(request, 'index/error.html', data)
HTML template:
<p>{{ errors }}</p>
<p>{{ errors.if }}</p>
<p>{{ errors.if.class }}</p>
{% for error in errors %}
<div class="{{ error.class }}"><p>{{ error.txt }}</p></div>
{% endfor %}
The upper 3 lines are for code debugging and work just fine.
The for loop doesn't produce any code.
Best regards,
LVX
You probably need to access .items() of the dict that you called errors. Just iterating over a dict gives you the keys, but not the values.
You can change your code to:
{% for k, v in errors.items %}
<div class="{{ v.class }}"><p>{{ v.txt }}</p></div>
{% endfor %}
Of course, if you don't need the keys (if and else) then you could also use .values() instead of items() to just get the values inside the dict.
The answer by Ralf is sufficient for the question, I just want to add an extra piece of information here.
When the template system encounters a dot in a variable name, it tries the following look-ups, in this order:
Dictionary Lookup (eg: foo['bar'])
Attribute Lookup (eg: foo.bar)
Method Call (eg: foo.bar())
List-Index Lookup (eg: foo[2])
The system uses the first lookup type that works.
You should try like this -
error['class']
Second way -
error[key]['class']
Use forloop -
for k,v in errors:
print(v['class'])

Django template language unpacking a dict

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 %}

Dealing with json type data in a template

I am after some advice. I know what I need to do, but not sure how I can do it
I send data to a template that comes from from a database
Let's say the database has two fields
Field one (name)
Name of a person
Field two some json (the json has a structure like this, with many field:value)
{
"field1":"value1",
"field2":"value2"
}
I can output this as
Field one (name) Field two (json)
What I actually want to do though, is loop through the json, and print out the values, so like this
Name of a person field1|field2
I am a bit lost on how I can do that
I tried something like this
{% for anitem in fieldtwo %}
<div>{{ anitem }}</div>
{% endfor %}
But that just seems to print out each character
Is what I need to do achievable? I am thinking I just have the whole approach wrong
Thanks
Grant
In the end, I ended up using another dictionary and then pass that through to the template
I loop through the queryset in the view to populate the dictionary
In the template I then did this (alloweddomains is from the view)
{% for testcaseid, domains in alloweddomains.items %}
{% if listtestcase.id == testcaseid %}
{% for key, value in domains.items %}
<div><a class="sendtolinkdisabled" data-testcasename="{{ listtestcase.name }}" data-testcaseid="{{ $
{% endfor %}
{% endif %}
{% endfor %}
This basically looped through the dictionary and if there was a match to my unique ID I get the data and do something with it
I tried various ways to not need the if statement and just get the right point in the dictionary, but nothing seemed to work (so I took the if approach)
Grant

Accessing individual objects in a Django template file

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.

Django dictionary in templates: Grab key from another objects attribute

I have a dictionary called number_devices I'm passing to a template, the dictionary keys are the ids of a list of objects I'm also passing to the template (called implementations). I'm iterating over the list of objects and then trying to use the object.id to get a value out of the dict like so:
{% for implementation in implementations %}
{{ number_devices.implementation.id }}
{% endfor %}
Unfortunately number_devices.implementation is evaluated first, then the result.id is evaluated obviously returning and displaying nothing. I can't use parentheses like:
{{ number_devices.(implementation.id) }}
because I get a parse error. How do I get around this annoyance in Django templates?
Thanks for any help!
A workaround could be using the keys from number_devices and check in the for loop if it is equal to the key provided by number_devices.
{% for key in number_devices.keys %}
{% for implementation in implementations %}
{% ifequal key implementation.id %} you got it {% endifequal %}
{% endfor %}
{% endfor %}
Seems a bit ugly, but should work.

Categories