Pass 2 or more variables to django template - python

i want to pass 2 lists to django template but only first is rendered
this is index.html:
enter code here
{% if latest_poll_list %}
<ul>
{% for poll in latest_poll_list %}
<li>{{ poll.question }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
{% if menu_items_list %}
<table id="menu_items_list">
<tr>
{% for item_url, item_name in menu_items_list %}
<td>item_name
{% endfor %}
</tr>
</table>
{% endif %}
<h3>{{ index_name }}</h3>
and this is urlconf:
urlpatterns = patterns('zzz.polls.views',
url(r'^$',
ListView.as_view(
queryset=Poll.objects.order_by('pub_date')[:5],
context_object_name='latest_poll_list',
template_name='index.html')),
and views:
def index(request):
latest_poll_list = Poll.objects.all().order_by('pub_date')[:5]
index_name = 'INDEX PAGE'
menu_items_list = ['somesite.com', 'Googy') for x in xrange(5)]
return render_to_response('index.html', {'latest_poll_list': latest_poll_list,
'menu_items_list' : menu_items_list,
'index_name': index_name})
where i make mistake??

The syntax of the LC is wrong.
>>> ['somesite.com', 'Googy' for x in xrange(5)]
File "<stdin>", line 1
['somesite.com', 'Googy' for x in xrange(5)]
^
SyntaxError: invalid syntax
>>> [('somesite.com', 'Googy') for x in xrange(5)]
[('somesite.com', 'Googy'), ('somesite.com', 'Googy'), ('somesite.com', 'Googy'), ('somesite.com', 'Googy'), ('somesite.com', 'Googy')]

Related

Calculation in your template with values passed in as context to display content

Im having trouble displaying some divs using the context passed in through my view. In my views.py, i'm passing a value "total_used"" and "total".
views.py:
def home(request):
context = {
"reward": [
{
"total": 5,
"total_used": 2
}
]
}
return render(request, "web/index.html", context)
Template:
{% with ''|center:reward.total_used as range %}
{% for _ in range %}
<div class="red"></div>
{% endfor %}
{% endwith %}
<div class="blue"></div>
<div id="reward-count">
<h5>{{ reward.total_used }}/{{ reward.total }}</h5>
</div>
So for example, I want 2 divs with class red, and 3 divs (reward.total- reward.total_used) with the class blue.
I have tried this but it didn't work:
{% with ''|center:reward.total_used as range %}
{% for _ in range %}
<div class="red"></div>
{% endfor %}
{% endwith %}
{% with ''|center:reward.total-reward.total_used as range %}
{% for _ in range %}
<div class="blue"></div>
{% endfor %}
{% endwith %}
<div id="reward-count">
<h5>{{ reward.total_used }}/{{ reward.total }}</h5>
</div>
Remove the square brackets [] from context definition. Your views.py should look like this:
def home(request):
context = {
"reward": {"total": 5, "total_used": 2}
}
return render(request, "web/index.html", context)
I ended up calculating total-total_used in my views, then adding it to my context:
views.py:
def home(request):
context = {
"rewards": [
{
"total": 5,
"total_used": 2
},
{
"total": 7,
"total_used": 1
}
]
}
for reward in context['rewards']:
reward['total_not_used'] = reward['total'] - reward['total_used']
return render(request, "web/index.html", context)
Template:
{% with ''|center:reward.total_used as range %}
{% for _ in range %}
<div class="reward reward-shaded"></div>
{% endfor %}
{% endwith %}
{% with ''|center:reward.total_not_used as range %}
{% for _ in range %}
<div class="reward"></div>
{% endfor %}
{% endwith %}
<div id="reward-count">
<h5>{{ reward.total_used }}/{{ reward.total }}</h5>
</div>

Django - Template does not show DetailView

I am encountering the following error when trying to set DetailView for each of the post in my postlist:
NoReverseMatch at /blog/post-list/ Reverse for 'postdetail' with
keyword arguments '{'id': ''}' not found. 1 pattern(s) tried:
['blog\/post-list/(?P\d+)/$']
Here the code:
views.py
def PostList(request):
postlist = Post.objects.all()
context = {
"postlist":postlist
}
template_name = "postlist.html"
return render(request,template_name,context)
def PostDetail(request,id):
post = get_object_or_404(Post,id=id)
context = {
'post':post
}
template_name = "postdetail.html"
return render(request,template_name,context)
postlist.html
{% extends "base.html" %}
{% block content %}
<div class="container">
<div class="row">
<div class="col">
{% for item in postlist %}
<ul>
<li><h3>Title:</h3> {{ item.title }} <smal>{{ item.timestamp }}</smal></li>
<li><h3>description:</h3>{{ item.description }}</li>
<li><h3>Updated:</h3>{{ item.updated }}</li>
<li><h>Author: {{ item.Author }}</h></li>
{{ item.id }}
</ul>
{{ item }}
{% endfor %}
</div>
</div>
</div>
{% endblock %}
urls.py
urlpatterns = [
re_path(r'^post-list/$',views.PostList,name ='postlist'),
re_path(r'^post-list/(?P<id>\d+)/$',views.PostDetail,name="postdetail"),
path ('post-create',views.CreatPost, name='post-create'),
re_path (r'^post-list/update/(?P<id>\d+)/$',views.PostUpdateis,name='update-post'),
# re_path(r'^(?P<slug_post>[-\w])+/$',views.PostDetail,name="postdetail"),
]
Does anybody know how to solve this?

Python Jinjna variable doesnt keep value outside loop

I am currently trying to fix an issue by using jinja variables, but somehow the variable does not keep the value outside the loop, even though I declared it before the loop begins:
{% set disablecounter = 0 %}
{% if disablecounter == 0 %}
{% for einzelroom in all_einzelzimmer %}
{% if zimmer.id == einzelroom.zimmer_id %}
{% set price = einzelroom.preis %}
<div class="preis-element">
<p class="preis"> <span class="smallab"> ab </span> {{ price|int }}€ </p>
</div>
{% set disablecounter = disablecounter + 1 %}
{{ disablecounter }}
{% endif %}
{% endfor %}
{% endif %}
{{ disablecounter }}
The variable is disablecounter inside the loop it is 1 but outside it is still 0
Thanks!
EDIT
Surrounding with a with statement also didnt worked:
{% with foo = 42 %}
{{ foo }}
{% endwith %}
{% with %}
{% set foo = 42 %}
{{ foo }}
{% endwith %}
I found a great solution here on SO by #Chris Warth.
Original answer by #Peter Hollingsworth:
https://stackoverflow.com/a/32700975/5291566
{% with disablecounter = [0] %}
{% if disablecounter == [0] %}
{% for einzelroom in all_einzelzimmer %}
{% if zimmer.id == einzelroom.zimmer_id %}
<div class="preis-element">
<p class="preis"> <span class="smallab"> ab </span> {{ einzelroom.preis|int }}€ </p>
</div>
{% if disablecounter.append(disablecounter.pop() + 1) %}{% endif %}
{% endif %}
{% endfor %}
{% endif %}

Loop over dictionary of dictionaries in Django Template for 1 line of code

The dictionary I'm passing to the Django template contains 2 dictionaries, each with a list:
'nav_dict': {
'class_name': ['Chemical', 'Avian', 'Mammal'],
'tab_label': ['Chemical!', 'Avian!', 'Mammal!']
}
I want to loop over the lists in each dict to fill out this line of code:
<li class="{{ item_className }} tabSel">{{ item_tabLabel }}</li>
where item_className = each value in the class_name list and item_tabLabel = each value in the tab_label list. The result would 3 <li> tags with a class_name and tab_label.
I have tried something like this (This code only handles the class_name part), but I can't get the loops to append to the same line of code (each <li>):
{% for key, value in nav_dict.items %}
{% if key == 'class_name' %}
{% for item_className in value %}
{% if forloop.counter0 == 0 %}
<li class="{{ item_className }} tabSel">{{ item_tabLabel }}</li>
{% else %}
<li class="{{ item_className }} tabUnsel">{{ item_tabLabel }}</li>
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
The problem you have is with the way you are presenting your data.
Why don't you create your dictionary like this, where each key is the class name and the associated value is the label. It would be more semantic and readable.
'nav_dict': {
'Chemical': 'Chemical!',
'Avian': 'Avian!',
'Mammal': 'Mammal!,
}
Then you can just loop over this and place the key as the class attribute, and the value as the label attribute.
{% for key, value in nav_dict.items %}
{% if forloop.counter0 == 0 %}
<li class="{{ key }} tabSel">{{ value }}</li>
{% else %}
<li class="{{ key }} tabUnsel">{{ value }}</li>
{% endif %}
{% endfor %}
If the order of the elements is important (as dictionaries are un-ordered), you could use an OrderedDict from the collections module to retain insertion order. You would do something like this inside your view...
>>> from collections import OrderedDict
>>> nav_dict = OrderedDict(zip(['Chemical', 'Avian', 'Mamma!'], ['Chemical!', 'Avian!', 'Mammal!']))
OrderedDict([('Chemical', 'Chemical!'), ('Avian', 'Avian!'), ('Mammal', 'Mammal!')])
Similarly you could use a list of tuples as your data
'nav_list': [('Chemical', 'Chemical!'), ('Avian', 'Avian!'), ('Mammal', 'Mammal!')]
And loop over this object like so
{% for class_name, label_name in nav_list %}
{% if forloop.counter0 == 0 %}
<li class="{{ class_name }} tabSel">{{ label_name }}</li>
{% else %}
<li class="{{ class_name }} tabUnsel">{{ label_name }}</li>
{% endif %}
{% endfor %}
If you only want to append an exclamation mark to your string to create the label, you could of course create a custom template filter instead - or just append the exclamation mark inside the template itself.
If you have to use that dictionary, you can use this template code:
{% for item_className in nav_dict.class_name %}
{% with forloop.counter0 as index_className %}
{% for item_tabLabel in nav_dict.tab_label %}
{% with forloop.counter0 as index_tabLabel %}
{% ifequal index_className index_tabLabel %}
{% if index_className == 0 %}
<li class="{{ item_className }} tabSel">{{ item_tabLabel }}</li>
{% else %}
<li class="{{ item_className }} tabUnsel">{{ item_tabLabel }}</li>
{% endif %}
{% endifequal %}
{% endwith %}
{% endfor %}
{% endwith %}
{% endfor %}

Jinja2: Change the value of a variable inside a loop

I want to change the value of the variable declared outside the loop within a loop. But always changing, it keeps the initial value outside the loop.
{% set foo = False %}
{% for item in items %}
{% set foo = True %}
{% if foo %} Ok(1)! {% endif %}
{% endfor %}
{% if foo %} Ok(2)! {% endif %}
This renders:
Ok(1)!
So the only (bad) solution have found so far was this:
{% set foo = [] %}
{% for item in items %}
{% if foo.append(True) %} {% endif %}
{% if foo %} Ok(1)! {% endif %}
{% endfor %}
{% if foo %} Ok(2)! {% endif %}
This renders:
Ok(1)!
Ok(2)!
But, its is very ugly! Is there another more elegant solution?
Try also dictionary-based approach. It seems to be less ugly.
{% set vars = {'foo': False} %}
{% for item in items %}
{% if vars.update({'foo': True}) %} {% endif %}
{% if vars.foo %} Ok(1)! {% endif %}
{% endfor %}
{% if vars.foo %} Ok(2)! {% endif %}
This also renders:
Ok(1)!
Ok(2)!
as mentioned in the documentation:
Please note that assignments in loops will be cleared at the end of
the iteration and cannot outlive the loop scope.
but as of version 2.10 you can use namespaces:
{% set ns = namespace(foo=false) %}
{% for item in items %}
{% set ns.foo = True %}
{% if ns.foo %} Ok(1)! {% endif %}
{% endfor %}
{% if ns.foo %} Ok(2)! {% endif %}
You could do this to clean up the template code
{% for item in items %}
{{ set_foo_is_true(local_vars) }}
{% if local_vars.foo %} Ok(1)! {% endif %}
{% endfor %}
{% if local_vars.foo %} Ok(2)! {% endif %}
And in the server code use
items = ['item1', 'item2', 'item3']
#---------------------------------------------
local_vars = { 'foo': False }
def set_foo_is_true(local_vars):
local_vars['foo'] = True
return ''
env.globals['set_foo_is_true'] = set_foo_is_true
#---------------------------------------------
return env.get_template('template.html').render(items=items, local_vars=local_vars)
This could be generalized to the following
{{ set_local_var(local_vars, "foo", False) }}
{% for item in items %}
{{ set_local_var(local_vars, "foo", True) }}
{% if local_vars.foo %} Ok(1)! {% endif %}
{% endfor %}
{% if local_vars.foo %} Ok(2)! {% endif %}
And in the server code use
items = ['item1', 'item2', 'item3']
#---------------------------------------------
local_vars = { 'foo': False }
def set_local_var(local_vars, name, value):
local_vars[name] = value
return ''
env.globals['set_local_var'] = set_local_var
#---------------------------------------------
return env.get_template('template.html').render(items=items, local_vars=local_vars)

Categories