How to Access a Dictionary Element in a Django Template

How to access a dictionary element in a Django template?

To echo / extend upon Jeff's comment, what I think you should aim for is simply a property in your Choice class that calculates the number of votes associated with that object:

class Choice(models.Model):
text = models.CharField(max_length=200)

def calculateVotes(self):
return Vote.objects.filter(choice=self).count()

votes = property(calculateVotes)

And then in your template, you can do:

{% for choice in choices %}
{{choice.choice}} - {{choice.votes}} <br />
{% endfor %}

The template tag, is IMHO a bit overkill for this solution, but it's not a terrible solution either. The goal of templates in Django is to insulate you from code in your templates and vice-versa.

I'd try the above method and see what SQL the ORM generates as I'm not sure off the top of my head if it will pre-cache the properties and just create a subselect for the property or if it will iteratively / on-demand run the query to calculate vote count. But if it generates atrocious queries, you could always populate the property in your view with data you've collected yourself.

How to access list of dictionary in Django template

Your message is not a list of dictionaries. It is simply a string that contains some data that looks like a list of dictionaries.

You probably should change it to a JsonField [Django-doc]:

class Leads(models.Model):
Name = models.CharField(max_length=50)
Mobile = models.CharField(max_length=13)
Email = models.CharField(max_length=50)
Message = models.JSONField()
created_on = models.DateTimeField(auto_now_add=True)
modified_on = models.DateTimeField(auto_now=True)

and re-populate the database with data. In that case accessing the message will indeed return a list of dictionaries that you can then render with:

<td>
{% for item in user.Message %}
{{ item.key }}<br>
{{ item.value }}
{% endfor %}
</td>


Note: normally a Django model is given a singular name, so Lead instead of Leads.



Note: normally the name of the fields in a Django model are written in snake_case, not PascalCase, so it should be: message instead of Message.



Note: Django's DateTimeField [Django-doc]
has a auto_now_add=… parameter [Django-doc]
to work with timestamps. This will automatically assign the current datetime
when creating the object, and mark it as non-editable (editable=False), such
that it does not appear in ModelForms by default.

Accessing dictionary by key in Django template

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.

How to access a dictionary in a list in Django Template?

This did the trick:
In views.py:

    from itertools import izip_longest
def course(request, dept_code):
....
sum_credits_total = list()
....
for i in credits_total: sum_credits_total.append(i['sum'])
....
total_list = izip_longest(sum_credits_total,hours_total,sum_sem_credits,sum_sem_hours)
context_dict['total_list'] = total_list
return render (request,'course.html', context_dict)

And in template:

    {% for i,j,k,l in total_list %}
{{i}}....{{j}}....{{k}}....{{l}}
{% endfor %}

Access a dictionary element in the Django template with a variable

This has been covered before, and the best solution I've found is to create a quick custom filter. In case that link goes dead, here's the code (which I did not write, but am providing as reference):

@register.filter 
def get_item(dictionary, key): return dictionary.get(key)

And in the template:

{{ dict|get_item:object.key }}

Of course, make sure to call load on your template tags so they're visible to the renderer.

Django template how to look up a dictionary value with a variable

Write a custom template filter:

from django.template.defaulttags import register
...
@register.filter
def get_item(dictionary, key):
return dictionary.get(key)

(I use .get so that if the key is absent, it returns none. If you do dictionary[key] it will raise a KeyError then.)

usage:

{{ mydict|get_item:item.NAME }}

Accessing lists inside a dictionary with Django Template tags

You should pre-process the data in the view:

checkoutList = [
{'id': id, 'title': title, 'location': location, 'imageurl': imageurl, 'url': url}
for id, title, location, imageurl, url in zip(
checkoutList['id'],
checkoutList['title'],
checkoutList['location'],
checkoutList['imageurl'],
checkoutList['url']
)
]

then you can render this with:

{% for record in checkoutList %}
{% for key, value in record.items %}
{{key}} {{value}}
{% endfor %}
{% endfor %}

Django templates accessing dictionary from another dictionary key

You cannot access dictionary indices from django template. You have to register a custom template tag like this.

@register.filter
def from_dict(d, k):
return d[k]

And use it like this.

{% for choice in choices %}
{{ percentages|from_dict:choice.id }}
{% endfor %}


Related Topics



Leave a reply



Submit