Accessing a dictionary using a key from another dictionary in Django template - python

I am passing two dictionaries to a Django template (reservations , prices) inside the template i have something like this:
{% for key,value in reservations.items %}
...
...
{% if value is False %}
<div class="room">
<p class="room-id">{{ prices.{{ key }} }}</p>
</div>
{% else %}
...
...
{% endfor %}
now the problem is this line {{ prices.{{ key }} }} i am trying to evaluate the key value from the reservations dict to be used in the
prices dict how this can be done? and thank you in advance.

Only with custom template tags, for example:
# access_tags.py
from django import template
register = template.Library()
#register.filter(name='access')
def access(value, arg):
return value.get(arg, value.get(unicode(arg), None))
and in template:
{% load access_tags %}
...
<p class="room-id">{{ prices|access:key }}</p>
...

Related

How to access the dictionary keys and values in django templates

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

How to get dictionary value of a key inside a loop in Django Template?

views.py
def get(self, request, *args, **kwargs):
domains = Domain.objects.all()
context['domains'] = domains
domain_dict = {}
# ..........
# ..........some codes here for domain_dict dictionary
print(domain_dict)
context['domain_dict'] = domain_dict
return render(request, self.response_template, context)
Output after printing the domain_dict
{4: '', 3: '', 1: '', 5: '', 7: '', 2: '', 6: 'Are you a candidate for the engineering admission '}
Now the domain_dict is sent to template through context.
templates.html
<div class="col-md-8">
<div class="tab-content">
{% for domain in domains %}
{% with domain_id=domain.id %}
<div class="tab-pane container p-0 {% if forloop.first %} active {% endif %}" id="services{{domain.id}}">
<div class="img" style="background-image: url('static/counsellor/images/service-1.png');">
</div>
<h3>Name: {{domain.name}} ID: {{domain_id}}</h3>
<p>{{domain_dict.6}}</p>
</div>
{% endwith %}
{% endfor %}
</div>
</div>
In the above template I use <p>{{domain_dict.6}}</p>. domain_dict.6 to find the value of key 6. It returns perfectly.
Outputs: Are you a candidate for the engineering admission.
But in the below
<div class="col-md-8">
<div class="tab-content">
{% for domain in domains %}
{% with domain_id=domain.id %}
<div class="tab-pane container p-0 {% if forloop.first %} active {% endif %}" id="services{{domain.id}}">
<div class="img" style="background-image: url('static/counsellor/images/service-1.png');">
</div>
<h3>Name: {{domain.name}} ID: {{domain_id}}</h3>
<p>{{domain_dict.domain_id}}</p>
</div>
{% endwith %}
{% endfor %}
</div>
</div>
In the above template I use <p>{{domain_dict.domain_id}}</p>. domain_dict.domain_id to find the value of key domain_id. It returns null. Here domain_id = 4,3,1,6,5,7,2
Outputs: null
How can I return the value of a key of the dictionary here?
I've recently run into the same problem. Here is example of the solution.
Say, we have tuple
people = ('Vasya', 'Petya', 'Masha', 'Glasha')
and dictionary with their status:
st = {
'Vasya': 'married',
'Petya': 'divorced',
'Masha': 'married',
'Glasha': 'unmarried'
}
We transfer these to our template as context of corresponding view:
context['people'] = people
context['st'] = st
If we write in template
{% for person in people %}
{{ person }} is {{ st.person }}
{% endfor %}
then it won't work. Well, 'person' will be displayed, but data from dictionary will not. Because :
Note that bar in a template expression like {{ foo.bar }} will be
interpreted as a literal string and not using the value of the
variable bar, if one exists in the template context.
The solution of the problem is either to use another data structure or to use custom filter in the template. The idea of the latter is to add a filter to your dictionary in the template, which takes current value of person and returns corresponding value of the dictionary.
To do this,
create in the folder with your app new folder templatetags,
write the path to this new folder in settings.py,
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
...,
os.path.join(BASE_DIR, 'your_app/templatetags'),
],
...
}
inside the templatetags create new file, say, filter.py with our new filter called dict_value:
from django import template
register = template.Library()
#register.filter
def dict_value(d, key):
return d[key]
go back to your template and load newly created filter somewhere in first lines:
{% load filter %}
rewrite you template code like this:
{% for person in people %}
{{ person }} is {{ st|dict_value:person }}
{% endfor %}
Now it works as needed.

Django - How to access elements in list by parent loop counter in template

I have this code
{% for time in listOfTimes %}
{% for booking in someOtherList.forloop.parentloop.counter0 %}
{{ booking }}
{% endfor %}
{% endfor %}
The booking variable does not get printed. I think this was because I cannot access someOtherList by using the forloop counter. How would I get the booking value?
Assuming your data is as follows:
listOfTimes = ['time1', 'time2']
someOtherList = [['booking1', 'booking2'], ['booking3', 'booking4']]
Then in template you can do this:
{% for time in listOfTimes %}
{% for booking in someOtherList|get_index:forloop.counter0 %}
{{ booking }}
{% endfor %}
{% endfor %}
Notice the get_index filter in above code, you need to write this custom filter in your app templatetags:
from django import template
register = template.Library()
#register.filter
def get_index(l, i):
return l[i]
Note: Your two list should be of same size, otherwise an IndexError might be raised.

How to access object attribute via django variable?

I want to convert this code to something more inheritable to avoid coding. Consider that my code is simple and simple answer is need.
{{ entity.name }}
{{ entity.description }}
I want to convert to such code:
{% for attribute in attributes %}
{{ entity ??? }} == entity.get_attr(attribute)
{% end for %}
What is valid syntax for it?
The easiest example with filter:
# templatetags.ry
from django import template
register = template.Library()
#register.filter
def get_attr(object, name):
return getattr(object, name, '')
Your template:
{% load templatetags %}
{% for attribute in attributes %}
{{ entity|get_attr:attribute }}
{% end for %}

Modify django templates to check for values in a dict

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

Categories

Resources