How to display array elements in python - python

I'm trying to browse this array and display it on my django project but it doesn't work.
Views.py
def(request):
{"product":[
{
"name":"sogi",
"desc":"solo"
},
{
"name":"molo",
"desc":"kanta"
},
]
}
context={"tab":"product"}
return render(request,'api/myapi.html',context)
myapi.html
{% for pro in tab %}
{{pro.name}}
{% endfor %}

You have to change your context creation:
def(request):
tab = {"product": [...]}
products = tab["products"]
context = {"products": products}
return render(request, "api/myapi.html", context)
And change usage in your template:
{% for product in products %}
{% for key, value in product.items %}
{{ key }}: {{ value }}<br>
{% endfor %}
{% endfor %}

Related

How can I view the JSON array as a list in Django

I am rendering a queryset on views.py like this:
person = MyDict.objects.filter(search_description = name)
return render(request,'myPage/find.html',{'person':person})
Its rendering like this:
person=[{
'gender': 'male',
'description': ['24', 'Student', 'NY']
}]
If i apply the following code on my html:
{% for item in person %}
{{ item.description }}
{% endfor %}
It returns as ['24', 'Student', 'NY']
But I want to view as like this:
24
Student
NY
How to do it???
You can use join template tag of django
{{ item.description|join:"<br>" }}
You nee to make templatetags for check value type is list or not.
templatetags code:
from django import template
register = template.Library()
#register.simple_tag
def is_list_type(data):
return isinstance(data, list)
html code:
{% load <templatetag file name> %}
{% for item in person %}
{% is_list_type item as result %}
{% if result %}
{% for value in item %}
{{value}} <br>
{% endfor %}
{% else %}
{{ item}}<br>
{% endif %}
{% endfor %}
Output:
male
24
Student
NY

Django Template: key, value not possible in for loop

Error I get:
Need 2 values to unpack in for loop; got 1.
Here is my view:
class Index(View):
def get(self, request, slug):
test = {
1: {
'id': 1,
'slug': 'test-slug-1',
'name': 'Test Name 1'
},
2: {
'id': 2,
'slug': 'test-slug-2',
'name': 'Test Name 2'
}
}
context = {
'test': test
}
return render(request, 'wiki/category/index.html', context)
Here is my template:
{% block content %}
<div>
{{ test }}
<ul>
{% for key, value in test %}
<li>
{{ key }}: {{ value }}
</li>
{% endfor %}
</ul>
</div>
{% endblock %}
I also tried the template like:
{% block content %}
<div>
{{ test }}
<ul>
{% for value in test %}
<li>
{{ value }}: {{ value.name }}
</li>
{% endfor %}
</ul>
</div>
{% endblock %}
No error then, but {{ value }} shows key (which is fine), but {{ value.name }} shows nothing. While {{ test }} shows my dict.
Loop through the dictionary's items to get the keys and values:
{% for key, value in test.items %}
Not familiar with Django. However, by default, Python iterates over the keys for a dictionary. I am also going to assume you are using Python2. To get the values, you need to do:
{% for value in test.itervalues() %}
If you want both, you need to do:
{% for key, value in test.iteritems() %}
That will give you both the key and the value.

django sort dict after query

have a table with websites and a many to one table with descriptions
trying to get a list, firstly getting the latest descriptions and then displaying them ordered by the content of the descriptions...
have the following in views.py
def category(request, category_name_slug):
"""Category Page"""
context_dict = {}
try:
category = Category.objects.get(slug=category_name_slug)
subcategory = SubCategory.objects.filter(category=category)
websites = Website.objects.filter(sub_categories=subcategory, online=True, banned=False)
sites = websites
descriptions = WebsiteDescription.objects.prefetch_related("about")
descriptions = descriptions.filter(about__in=sites)
descriptions = descriptions.order_by('about', '-updated')
descs = []
last_site = "" # The latest site selected
# Select the first (the latest) from each site group
for desc in descriptions:
if last_site != desc.about.id:
last_site = desc.about.id
desc.url = desc.about.url
desc.hs_id = desc.about.id
desc.banned = desc.about.banned
desc.referral = desc.about.referral
descs.append(desc)
context_dict['descs'] = descs
context_dict['websites'] = websites
context_dict['subcategory'] = subcategory
context_dict['category'] = category
except SubCategory.DoesNotExist:
pass
return render(request, 'category.html', context_dict)
this gives me a list with sites and their latest descriptions, so i have the following in category.html
{% if category %}
<h1>{{ category.name }}</h1>
{% for subcategory in category.subcategory_set.all %}
{{ subcategory.name }} ({{ subcategory.website_set.all|length }})
{% endfor %}
{% if descs %}
{% load endless %}
{% paginate descs %}
{% for desc in descs|dictsortreversed:"description"|dictsortreversed:"officialInfo" %}
<ul id='list' class='linksteps'>
<a href="/{{ desc.about_id }}" rel="nofollow" target="_blank">
<img src="/static/screenshots/{{ desc.about_id }}.png" />
</a>
<li><h3>{{ desc.about_id }}{% if desc.title %} - {{ desc.title }} {% endif %}</h3>
{% if desc.description %}<b>Description: </b>{{ desc.description }}
<br />{% endif %} {% if desc.subject %}<b>Keywords: </b>{{ desc.subject }}
<br />{% endif %} {% if desc.type %}<b>Type: </b>{{ desc.type }}
<br />{% endif %} {% if desc.officialInfo %} {% if desc.language %}<b>Language: </b>{{ desc.language }}
<br />{% endif %} {% if desc.contactInformation %}<b>Contact info: </b>{{ desc.contactInformation }}
<br />{% endif %}
{% else %}
{% endif %}
</li>
</ul>
</div>
{% endfor %}
{% show_pages %}
{% else %}
<strong>No websites currently in category.</strong>
{% endif %}
{% else %}
The specified subcategory {{ category_name }} does not exist!
{% endif %}
Initially i used dictsort
{% for desc in descs|dictsortreversed:"description"|dictsortreversed:"officialInfo"|dictsortreversed:"referral" %}
to give me the list in the desired order, so i was all happy ;)
Then however i decided i needed some pagination because the lists became too long.
django-endless-pagination works fine and does what its supposed too, however it splits up my list before the dictsort kicks in.
is there a way to sort before pagination happens and after i ordered_by at the initial query to have the latest descriptions selected?
much obliged
EDIT:
not getting any answers so my question might not be clear.
as far as i understand i need to sort the values in context_dict at the end in views.py replacing the dictsort as in the template
SOLVED:::
doing this did the trick for me to replace the dictsort.
descs1 = sorted(descs, key=operator.attrgetter('referral', 'officialInfo', 'description'), reverse=True)
context_dict['descs'] = descs1
SOLVED:::
doing this did the trick for me to replace the dictsort.
descs1 = sorted(descs, key=operator.attrgetter('referral', 'officialInfo', 'description'), reverse=True)
context_dict['descs'] = descs1

Paginating based on the alphabet (A-Z)

I have a simple contacts application where I want to paginate the contact list based on first name alphabet.
Here is my views.py
def contacts(request):
contact_list = Contact.objects.filter(user=request.user).order_by('first_name')
pages = [contact_list.filter(first_name__istartswith=i) for i in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
return render(request, 'contact/contact.html', {'contact_list': contact_list, 'pages': pages})
Here is my template
{% for alphabet in pages %}
{% if alphabet %}
<p>{{ alphabet }}</p>
{% for contact in contact_list %}
{% if contact in pages %}
<ul>
<li>{{ contact.first_name }}</li>
</ul>
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
The output from this is something like
[<Contact: Steve>, <Contact: Su>]
Steve
Su
[<Contact: Ted>]
Ted
[<Contact: Zedd>]
Zedd
The {{ alphabet }} prints a list. What should I write to print the alphabet instead?
Capture the alphabet in the context variable:
pages = [{"letter": i, "contacts": contact_list.filter(first_name__istartswith=i) }
for i in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
return render(request, 'contact/contact.html', {'pages': pages}) # why pass contact_list?
Your template should be simplified to:
{% for alphabet in pages %}
{% if alphabet.contacts %}
<p>{{ alphabet.letter }}</p>
{% for contact in alphabet.contacts %}
<ul>
<li>{{ contact.first_name }}</li>
</ul>
{% endfor %}
{% endif %}
{% endfor %}

how to get the current thing in my django filter and template

this is my views.py :
a=[{'s':'sss'},{'s':'wwww'},{'s':'ssaawdw'},{'s':'qqqww'}]
def main(request, template_name='index.html'):
context ={
'a':a,
}
return render_to_response(template_name, context)
this is my filter :
def return_next_element(list, index):
if(index<len(list)-1):
return list[index+1]
else :
return 0
register.filter('return_next_element',return_next_element)
and this is my template :
{% load myfilters %}
{% for i in a %}
{{ i }}ww{{ (a|return_element:forloop.counter0).s }}
{% endfor %}
but , this cant get the a.s ,
so what can i do ,
thanks
updated
this is not a same question , because i will use like this :
a|return_element:forloop.counter0).s|other filter
For your situation, I'd suggest doing the following:
{% for dictionary in a %}
{% for key, value in dictionary.iteritems %}
{{ key }}ww{{ value }}
{% endfor %}
{% endfor %}
But to answer your question, use the with tag.
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#with
{% with a|return_element:forloop.counter0 as result %}
{{ result|other_filter }}
{% endwith %}

Categories

Resources