Accessing dictionary by key in Django template

PythonDjangoJson

Python Problem Overview


I'm passing a dictionary from my view to a template. So {"key1":"value1","key2":"value2"} is passed in and looping through key,value pairs is fine, however I've not found an elegant solution from access directly in the view from a specific key, say "key1" for example bu json.items["key1"]. I could use some if/then statements, but I'd rather do directly is there a way?

Here is looping code in the html template:

{% for key, value in json.items %} 
  <li>{{key}} - {{value}}</li>
 {% endfor %}

Python Solutions


Solution 1 - Python

The Django template language supports looking up dictionary keys as follows:

{{ json.key1 }}

See the template docs on variables and lookups.

The template language does not provide a way to display json[key], where key is a variable. You can write a template filter to do this, as suggested in the answers to this Stack Overflow question.

Solution 2 - Python

As @Alasdair suggests, you can use a template filter. In your templatetags directory, create the following file dict_key.py:

from django.template.defaultfilters import register

@register.filter(name='dict_key')
def dict_key(d, k):
    '''Returns the given key from a dictionary.'''
    return d[k]

Then, in your HTML, you can write:

{% for k in json.items %} 
  <li>{{ k }} - {{ json.items|dict_key:k }}</li>
{% endfor %}

Solution 3 - Python

For example, to send the below dictionary dict = {'name':'myname','number':'mynumber'}

views : return render(request, self.template_name, {'dict': dict})

To render the value in html template: <p>{{ dict.name }}</p>

It prints 'myname'

Solution 4 - Python

To overcome this problem you could try something like this:

def get_context_data(self, **kwargs):
    context['cart'] = []
    cart = Cart()
    cart.name = book.name
    cart.author = book.author.name
    cart.publisher = book.publisher.name
    cart.price = 123
    cart.discount = 12
    cart.total = 100
    context['cart'].append(cart)
    return context


class Cart(object):
    """
    Cart Template class
    
    This is a magic class, having attributes
    name, author, publisher, price, discount, total, image
    You can add other attributes on the fly
    """
    pass


By this way you can access your cart something like this:
{% for item in cart %}
    <div class="jumbotron">
    <div>
    <img src="{{item.image}}" />
    <div class="book_name"> <b>{{item.name}}</b></div>
    <div class="book_by"><i>{{item.author}}</i></div>
    <span>Rs. {{item.price}}</span> <i>{{item.discount}}% OFF </i>
    <b>Rs. {{item.total}}</b>
{% endfor %}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondisruptiveView Question on Stackoverflow
Solution 1 - PythonAlasdairView Answer on Stackoverflow
Solution 2 - PythonMicah WalterView Answer on Stackoverflow
Solution 3 - PythonNandhitha RamarajView Answer on Stackoverflow
Solution 4 - PythonDeepak VermaView Answer on Stackoverflow