Django templates check whether key is existing - python

Urgently needed solution
I have dictionary say
dictcontents = {"product1":{"subproduct1":["value1","value2"]},"product2":{"subproduct2":["value3","value4"]}}
I have sent dictcontents to template .I want to iterate the dictionary in template and check the key existence dictcontents["product1"]["subproduct1"] and get the value of that checked key
where "subproduct1" key is intialised value by user. I need to access the information whether the user has entered the "subproduct1" value or not manually?
Thanks in advance

You can do this:
{% for key, val in d.items %}
{% if val.subproduct1 %}
{% for value in val.subproduct1 %}
{{ value }}
{% endfor %}
{% endif %}
{% if val.subproduct2 %}
{% for value in val.subproduct2 %}
{{ value }}
{% endfor %}
{% endif %}
{% endfor %}
or this:
{% for key, val in d.items %}
{% for key2, val2 in val.items %}
{% if val2 %}
{% for value in val2 %}
{{ value }}
{% endfor %}
{% endif %}
{% endfor %}
{% endfor %}

Related

Django: Nested Loop In Template

category = ['cat1','cat2','cat3']
inventory = CurrentInventory.objects.all()
for cats in categories
inventorybycat = inventory.filter(category =cats)
setofinventories.append(inventorybycat)
dictofstuff = [zip(setofinventories,categories)]
context = {
'setofinventories':setofinventories
'category':category
'dictofstuff':dictofstuff
}
In views.py above this loop creates a list of objects per each category.
In the template below this loop prints a filtered object list per every item in the category list.
{% for inventory in setofinventories%}
{% for item in inventory %}
{{ item.category }}
{{ item.productName }}
{% endfor %}
{% endfor %}
The only thing I am missing is I do not now how to reference the category in the template. I pass the whole list in context, but {{category{{forloop.counter}}}} is not a valid statement.
I would either like to use zip(category,setofinventories) to pass these two items together,
or create a category model, filter by that model and then I can reference that model by item?
If I zip these items dictofstuff = [zip(setofinventories,categories)]
How do I reference the category in the template?
{% for inventory,categories in dictofstuff %}
{% for inventory in setofinventories%}
{% for item in inventory %}
{{ item.quantity }}
{{ item.productName }}
{% endfor %}
{% endfor %}
{% endfor %}
Returns Error: "Need 2 values to unpack in for loop: got 1."
If i right understand you, you want to print category only one time.
In your case:
{% for inventory in setofinventories%}
{% ifchanged inventory.category %}
{{ inventory.category }}
{% endifchanged %}
{% for item in inventory %}
{{ item.quantity }}
{{ item.productName }}
{% endfor %}
{% endfor %}
i use ifchanged, more here:
https://docs.djangoproject.com/en/4.1/ref/templates/builtins/#ifchanged
in views i zipped this to a *listofstuff. Forgive the nomenclature.
dictofstuff = [zip(categories,setofinventories)]
in template. Again, forgive bad nomenclature. I should go back and rename these but it works.
{% for category in dictofstuff %}
{% for item in category %}
{{item.0}}
{% for stuff in item %}
{% for thing in stuff %}
{{thing.productId}}{{thing.productName}}
{% endfor %}
{% endfor %}
{% endfor %}
{% endfor %}

How to check condition with the value of a key in data and also display all the nested values if present

I have the sample mongo document data as (for ref):
from view as:
data=wordscollection.find({'word':word})
return render_template('wordsearch.html',data=data)
In the template I have this just for the first index and doesn't check if example or synonym is empty:
{% for word in data %}
<tr>Meaning :{{ word['meanings'][0]['def'] }}</tr><br>
<tr>Example :{{ word['meanings'][0]['example'] }}</tr><br>
<tr>Parts Of Speech :{{ word['meanings'][0]['speech_part'] }}</tr>
{% endfor %}
which outputs as:
1) How can I display all indexes results as
meaning1: def1
speechpart1: speech_part1
example1: //2)writing condition for this to show if exits
synonym: //2)writing condition for this to show if exits
Meaning2: def2
........
........
I have tried my luck for 2) as below :
{% for word in data if word['meanings'][0]['example'] %}
but this didn't work either
Any help is appreciated, TIA
You have to use nested for loop to iterate meanings also and check for empty values before
{% for word in data %}
{% for meaning in word['meanings'] %}
<tr>Meaning :{{ meaning['def'] }}</tr><br>
{% if meaning['example'] %}
<tr>Example :{{ meaning['example'] }}</tr><br>
{% endif %}
{% if meaning['speech_part'] %}
<tr>Parts Of Speech :{{ meaning['speech_part'] }}</tr>
{% endif %}
{% endfor %}
{% endfor %}
updated answer for synonyms
{% for word in data %}
{% for meaning in word['meanings'] %}
<tr>Meaning :{{ meaning['def'] }}</tr><br>
{% if meaning['example'] %}
<tr>Example :{{ meaning['example'] }}</tr><br>
{% endif %}
{% if meaning['speech_part'] %}
<tr>Parts Of Speech :{{ meaning['speech_part'] }}</tr><br>
{% endif %}
{% for synonyms in meaning['synonyms'] %}
{% if meaning['synonyms'] %}
<tr>synonyms : {{ synonyms }} </tr><br>
{% endif %}
{% endfor %}
{% endfor %}
{% endfor %}

Shorten the construction

The challenge is to reduce the construction and, if possible, speed up the processing of the code.
{% for tp1 in test.tab_tp1s %}
{{ tp1.name }}
{% endfor %}
{% for tp2 in test.tab_tp2s %}
{{ tp2.name }}
{% endfor %}
{% for tp3 in test.tab_tp3s %}
{{ tp3.name }}
{% endfor %}
{% for tab in test %}
{% for tp in test[tab]
{{ tp.name }}
{% endfor %}
{% endfor %}
Maybe, it's hard to tell because we don't know what is stored in test, I'm assuming test is a dictionary holding 3 keys which each hold a sub key called name?

Flask/Python - How can I render this data in a text-form instead of list

I am trying to get data from an calendar URL using flask. I have an URL which I am requesting data from. I am getting the output in a list which is not what I want. I want the data from the URL to be rendered in a text-form (like https://www.w3schools.com/html/html_forms.asp) so I can edit the results I get. Right now I can't edit it since its in a list, like this word.
I want it to be something like this "Key : value (the value is in a text-form)".
My current code iterates through the data and renders it in a list instead of a form.
import requests
from flask import Flask
from flask import render_template
app = Flask('__name__')
def get_json(id):
url = 'https://cloud.timeedit.net/ltu/web/schedule1/{0}.json'.format(id)
r = requests.get(url)
return r.json()['reservations']
#app.route('/')
def index():
reservations = get_json('ri107357055Z76Q506656Q65yZ075W2313Y63Q5Q')
return render_template('reservations.html', reservations=reservations)
if __name__ == '__main__':
app.run()
HTML:
e {% for reservation in reservations %}
<ul>
{% for key in reservation %}
{% if key == 'columns' %}
<li>{{ key }} -</li>
<ul>
{% for item in reservation[key] %}
{% if item %}
<li>{{ item }}</li>
{% endif %}
{% endfor %}
</ul>
{% else %}
<li>{{ key }} - {{ reservation[key] }} </li>
{% endif %}
{% endfor %}
</ul>
{% endfor %}
<hr>
see if this works for you,
Only need to make changes in the html file
{% for reservation in reservations %}
<ul>
{% for key in reservation %}
{% if key == 'columns' %}
<li>{{ key }} -</li>
<ul>
{% for item in reservation[key] %}
{% if item %}
<li>{{ item }}</li>
{% endif %}
{% endfor %}
</ul>
{% else %}
<form action="/action_page.php">
{{ key }} - s <input type="text" name="lname", value="{{ reservation[key] }}"><br>
</form>
{% endif %}
{% endfor %}
</ul>
{% endfor %}
<hr>
Output

Django loop through list

How do you loop trough a list in Django templates with a for loop?
my problem is with trying to fetch list.0 list.1 list.2
But when running the code i don't get anything
{% for i in range %}
{% for key, value in list.i.items %}
{{ key }}
{{ value }}
{% endfor %}
{% endfor %}
where i should be list.0-2 but it doesn't show anything on screen
If it is just a list containing a dict?
Just use the following code
{% for element in lst %}
{% for key, value in lst.items %}
{{ key }} --> {{ value }}
{% endfor %}
{% endfor %}

Categories