I have created a dictionary of message senders which is updating dynamically. If I print the dictionary keys in the python console window, I am getting the expected output but when I try to access the values in the Django template, I am getting nothing here is my python code;
views.py
def home(request):
senders = {}
chatting =Message.objects.filter(seen=False)
for msg in chatting:
user = User.objects.get(id=msg.sender.id)
if user != request.user and user not in senders.values():
senders.update({user.id : user})
return render(request, 'home.html', senders)
template Home.html
<div>
{% for key, val in senders %}
<div>
{{val}}
</div>
{% endfor %}
</div>
first of all,
are you sure you really need a dict here? usually Django has a list of dicts. So, you loop just list, like here: https://github.com/ansys/aedt-testing/blob/cefebb91675dd54391d6324cd78e7bc97d9a8f6b/aedttest/static/templates/project-report.html#L220
however,
answer to a direct question:
{% for key, value in data.items %}
{{ key }}: {{ value }}
{% endfor %}
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for
use below instruction in template of django :
{{ key }}: {{ value }}
Related
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 %}
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.
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 %}
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'
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 %}
My context dictionary for my Django template is something like the following:
{'key1':'1',
'key2':'2',
'key3':'3',
'key4':{'key5':{'key6':'6', 'key7':'7', 'key8':'8'}}}
I would like to iterate through the dictionary and print something like:
some label = 6
some label = 7
some label = 8
How can I achieve this in my Django template?
What's wrong with this ?
<ul>
{% for key, value in key4.key5.items %}
<li>{{ key }} : {{ value }}</li>
{% endfor %}
</ul>
NB: you didn't ask for looping over all keys in the context, just about accessing key4['key5'] content. if this wasn't wath you were asking for pleasit eadit your question to make it clearer ;-)
I am guessing you want to use a for loop in the django template to do this you must first pass the dictionary to the template in the views file like so make sure you add square brackets around the dictionary like this:
data = [{'key1':'1',
'key2':'2',
'key3':'3',
'key4':{'key5':{'key6':'6', 'key7':'7', 'key8':'8'}}
}]
return render(request,'name of template',{'data':data})
then in the html template:
{% for i in data%}
<p>{{i.key1}}</p>
<p>{{i.key2}}</p>
<p>{{i.key3}}</p>
<p>{{i.key4.key5.key6}}</p>
{% endfor %}
Now when you do the for loop you can access all the iteams in key4 like i have above when I put {{i.key4.key5.key6}}
Here is the docs for the for loop in django templates https://docs.djangoproject.com/en/3.0/ref/templates/builtins/
I am assuming thats what you want to do.
This has worked for me:
{% for key, value in context.items %}
{% ifequal key "key4" %}
{% for k, v in value.items %}
some label = {{ v.key6 }}
some label = {{ v.key7 }}
some label = {{ v.key8 }}
{% endfor %}
{% endif %}
{% endfor %}
If you want to print only what you have mentioned in question then it is possible but if we don't know the exact structure of dictionary then it is possible in django views not in django template.
You can't print value which is also a dictionary one by one in django template,
But you can do this in django view.
Check this post click here and do some changes in views.
I'm trying to iterate over the keys of a dictionary passed as context variable in template. But it's just not happening.
And when I put {{ key }} in template I get the value corresponding to that key but just couldn't iterate over.
logic.py
global table
table = {}
for i in range(9):
for j in range(9):
key = 'i'
key = key + str(i) + str(j)
table[key] = 1
view.py
from django.shortcuts import render
from .formss import SudokuForm, RealSudoku
from .logic import table
# Create your views here.
def sudokuf(request):
title = "Sudoku Puzzle"
if request.method == 'POST' :
print(request.POST)
return render (request,"sudoku.html",table)
sudoku.html
<form method="POST" action=""> {% csrf_token %}
{% for key,value in table.items %}
{{ key }}:{{ values }}
{% endfor %}
{{ i04 }} # If I do this I get the value table['i04'] but not in the above for loop
<input type="submit" align="centre" value="Solve">
The third argument to render is a "context", a dictionary whose keys will be available to your HTML as names. You're passing your table object as the context, so its keys (like i04) are available as variables... but there is no key named table in your table, so the name table isn't available to your HTML.
Change this line in view.py:
return render (request,"sudoku.html",table)
to:
return render(request, "sudoku.html", {"table": table})
And you'll have the name table available in your HTML. (But not the name i04).
You could also do something like:
import logic
render(request, "sudoku.html", logic)
And that would make all the names defined in your logic module available to your HTML.
If there's anything that's not clear about this answer, leave a comment and let me know, and I'll try to explain further.
It's probably that you have {{ values }} where you should have {{ value }}.
So instead of
{% for key,value in table.items %}
{{ key }}:{{ values }}
{% endfor %}
try...
{% for key,value in table.items %}
{{ key }}:{{ value }}
{% endfor %}
I have the following Django template.
{% load custom_tags %}
<ul>
{% for key, value in value.items %}
<li> {{ key }}: {{ value }}</li>
{% endfor %}
I need to check for the value and do some modifications.
If the value is True , instead of value I have to print Applied , else if it False I need to print Not Applied.
How to achieve that?
Very simple if-else clause here. Take a look at the django template docs to familiarize yourself with some of the common tags.
{% if value %}
APPLIED
{% else %}
NOT APPLIED
{% endif %}
You asked how to do this as a filter... I'm not sure why, but here is it:
In your app's templatetags directory create a file called my_tags.py or something and make the contents
from django import template
register = template.Library()
#register.filter
def applied(value):
if value:
return 'Applied'
else:
return 'Not applied'
Then in your template make sure to have {% load my_tags %} and use the filter with {{ value|applied }}
I am trying to retrieve the value of a dictionary key and display that on the page in a Django template:
{% for dictkey in keys %}
<p> {{ mydict.dictkey }} </p>
{% endfor %}
(let's say 'keys' and 'mydict' have been passed into the template in the Context)
Django renders the page but without the dictionary contents ("Invalid template variable")
I assume the problem is that it is trying to do mydict['dictkey'] instead of mydict[actual key IN the variable dictkey]? How does one "escape" this behavior?
Thanks!
UPDATE:
Based on the answers received, I need to add that I'm actually looking specifically for how to achieve a key lookup inside a for loop. This is more representative of my actual code:
{% for key, value in mydict1.items %}
<p> {{ mydict2.key }} </p>
{% endfor %}
Basically, I have two dictionaries that share the same keys, so I can't do the items() trick for the second one.
See this answer to a (possibly duplicate) related question.
It creates a custom filter that, when applied to a dictionary with a key as it's argument, does the lookup on the dictionary using the key and returns the result.
Code:
#register.filter
def lookup(d, key):
if key not in d:
return None
return d[key]
Usage:
{% for dictkey in dict1.keys %}
<p> {{ dict2|lookup:dictkey }} </p>
{% endfor %}
Registering the filter is covered in the documentation.
I find it sad that this sort of thing isn't built in.
From http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for
This can also be useful if you need to access the items in a dictionary. For example, if your context contained a dictionary data, the following would display the keys and values of the dictionary:
{% for key, value in data.items %}
{{ key }}: {{ value }}
{% endfor %}
The trick is that you need to call dict.items() to get the (key, value) pair.
See the docs: http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for
{% for key, value in data.items %}
{{ key }}: {{ value }}
{% endfor %}