I am passing the dictionary to the view but it is now showing on the page.
i also have print the dictionary on the before passing, and it prints the whole dictionary on the screen perfectly. but when i pass it to the html page, it does not show at all..
view.py
def show_log_messages(request):
context = RequestContext(request)
log_dictionary = {}
count = 0
e = log_messages.objects.filter(log_status='Queue').values('sent_to', 'unique_arguments')
count = 0
logs = {}
for d in e:
count +=1
new_dict = {'email': d["sent_to"], 'log_id': d["unique_arguments"]}
logs[count] = new_dict
for keys in logs:
print logs[keys]['log_id']
print logs[keys]['email']
return render_to_response('show_logs.html', logs, context)
show_logs.html
{% if logs %}
<ul>
{% for log in logs: %}
{% for keys in log %}
<li>{{ log[keys]['email'] }}</li>
{% endfor %}
</ul>
{% else %}
<strong>There are no logs present.</strong>
{% endif %}
it only show the heading not the list element.
Your code is very unpythonic and undjango. You should pass to template a list instead of dictionary.
Also shortcuts.render is much simpler to use than render_to_response.
def show_log_messages(request):
messages = log_messages.objects.filter(log_status='Queue') \
.values('sent_to', 'unique_arguments')
logs = [{'email': msg['sent_to'], 'log_id': msg['unique_arguments']}
for msg in messages]
return render(request, 'show_logs.html', {'logs': logs})
Template:
{% if logs %}
<ul>
{% for log in logs %}
<li>{{ log.email }} - {{ log.log_id }}</li>
{% endfor %}
</ul>
{% else %}
<strong>There are no logs present.</strong>
{% endif %}
BTW, logs list is unnecessary here. You can pass messages queryset directly into template and show {{ log.sent_to }} and {{ log.unique_arguments }} in the <li> tag.
The render_to_response shortcut takes a dictionary. If you want to access logs in the template, it should be in that dictionary:
return render_to_response("show_logs.html", {'logs': logs}, context)
The second problem is that your django template is invalid. It looks like you're trying to write Python in the template. You'd probably find it helpful to read through the Django template language docs.
It's not clear to me what you're trying to display, so here's an example of looping through each log, and displaying its id and email. You should be able to adjust this to get the result you want.
{% if logs %}
{% for key, value in logs.items %}
{{ key }}, {{ key.log_id}}, {{ key.email }}
{% endf
{% else %}
<strong>There are no logs present.</strong>
{% endif %}
Related
I have this function just for learning and want to print out the xxxxx and yyyyy on the html page.
I have tried everything but the best I can get is aaa bbb
def index(request):
template = loader.get_template('bsapp/index.html')
listan = {'aaa':'xxxxxx','bbb':'yyyyyy'}
context = {
'listan': listan
}
return HttpResponse(template.render(context, request))
This is the html page, how would I write it?:
{% for item in listan %}
{{ item }}<br>
{% endfor %}
You can iterate your dictionary in Django as:
{% for key, value in listan.items %}
{{ value }}<br>
{% endfor %}
You can use {{ key }} if you want to display key as well.
Edited my code: In the custom fieldset of a model admin:
{%load app_extras %}
{% if field.field.name == 'mobile' %}
<a target="hiddenIframe" href="http://url_to_call.php?exten={{request.user.employee_profile.extension}}&phone={{ field.field.value }}">Click-to-call</a>
{% my_mobile mobile=field.field.value as mob %}
{% endif %}
{% if field.field.name == 'sms_message' %}{{ mob }}
<a target="hiddenIframe" href="http://url_for_send_sms.php?sms_message={{ field.field.value }}&phone={{ mob }}">Click-to-send-sms</a>
{% endif %}
Here I am trying to access mobile number as well as sms_message fields of the model admin form simultaneously.
I have figured that I need to use custom tags, so I created the templatetags module, with app_extras.py containiging the function to assign the value of mobile and return it as follows:
#register.assignment_tag
def my_mobile(*args, **kwargs):
m_mobile = int(kwargs['mobile'])
return {'m_mobile': m_mobile }
In the template fiedset.html above note changes: This returns a Long value as: {'m_mobile': 1234534519L}
When seen on the browser for url for hyperlink shows:
http://url_for_send_sms.php/?sms_message=fgdfg&phone={%27m_mobile%27:%1234534519L}
How do I access the mobile number? Is my custom tag correct?
I formatted the output in my tag as:
#register.assignment_tag
def my_mobile(*args, **kwargs):
m_mobile = ("%d" %int(kwargs['mobile']))
return {'m_mobile': m_mobile }
In the template fieldset.html changed the code as:
{% if field.field.name == 'sms_message' %}
<a target="hiddenIframe" href="http://url_for_send_sms.php?sms_message={{ field.field.value }}&phone=={{ mob.m_mobile }}">Click-to-send-sms</a>
{% endif %}
Important: Both the mobile number and the sms_message are in the same line of the fieldset in the django modeladmin (in my case). So above code belongs to the loop {% for line in fieldset %} loop
Try
{% for ln in fieldset %}
{% for fld in ln %}
{% if f.field.name == 'mobile' %}
{{ f.field.value }}
{% endif %}
{% endfor %}
{% endfor %}
Maybe this is not the best solution ... but it is solution :)
I'm working on an Inclusion Tag. In the super shell, the tag returns the appropiate data set nevertheles, I dont see the inclusion template rendered on the calling template. I can only guess the inclusion template is in the wrong location. As of this moment, the template is at MYPROJECT/templates which is the ONLY folder in TEMPLATE_DIRS. Please help me figure out what am I doing wrong here. TIA!
MYPROJECT/newsroom/templatetags/blog_extras.py -> http://pastebin.com/ssuLuVUq
from mezzanine.blog.models import BlogPost
from django import template
register = template.Library()
#register.inclusion_tag('featured_posts.html')
def featured_posts_list():
"""
Return a set of blog posts whose featured_post=True.
"""
blog_posts = BlogPost.objects.published().select_related("user")
blog_posts = blog_posts.filter(featured_post=True)
# import pdb; pdb.set_trace()
return {'featured_posts_list': blog_posts}
MYPROJECT/templates/featured_posts.html -> http://pastebin.com/svyveqq3
{% load blog_tags keyword_tags i18n future %}
Meant to be the the infamous "Featured Posts" Section!
{{ featured_posts_list.count }}
<ul>
{% for featured_post in featured_posts_list %}
<li> {{ featured_post.title }} </li>
{% endfor %}
</ul>
MYPROJECT/settings.py -> pastebin.com/Ed53qp5z
MYPROJECT/templates/blog/blog_post_list.html -> pastebin.com/tJedXjnT
As #Victor Castillo Torres said, you need to change the name of the tag you're loading, which will fix that aspect of your template tag. However, even though they are in different namespaces, I would still change the name of the context variable your tag returns just for sanity:
#register.inclusion_tag('featured_posts.html')
def featured_posts_list():
blog_posts = BlogPost.objects.published().filter(
featured_post=True).select_related("user")
return {'blog_posts': blog_posts}
Then in your template:
{{ blog_posts.count }}
<ul>
{% for blog_post in blog_posts %}
<li>{{ blog_post.title }} </li>
{% endfor %}
</ul>
And finally, in your main template:
{% load blog_extras keyword_tags i18n_future %}
...
{% featured_posts_list %}
I have for example a JSON File
{
"Google":{
"Web":"www.web.de",
"Apps":{
"Drive": "DriveLink",
"Dropbox": "DropboxLink"
},
"Google Main":"http://mail.google.com",
"G+":"http://plus.google.com"
},
"Social":{
"Facebook":"http://www.facebook.de",
"G+":"https://plus.google.com",
"Xing":"http://www.xing.de",
"LinkedIn":"http://www.linkedin.com",
"Tumblr":"http://www.tumblr.com"
},
"Fun":{
"Reddit":"http://www.reddit.com"
}
}
As you can see I have under the section Google a Nested Section named Apps
With CherryPy I hand over this JSON Object as following with the name linksList:
#cherrypy.expose
def index(self):
linksFile = open('links.json', 'r')
linksList = json.load(linksFile)
template = jinjaEnv.get_template('index.html')
return template.render(linksList=linksList)
What I want is to render following:
Google
Web (as a link)
Google Main
G+
Apps
Drive
Dropbox
Social
Facebook
G+
Xing
and so on
What I don't understand is to do is to render this nested Objects like "Apps" recursively
The documentation reads:
It is possible to use loops recursively. This is useful if you are
dealing with recursive data such as sitemaps. To use loops recursively
you basically have to add the recursive modifier to the loop
definition and call the loop variable with the new iterable where you
want to recurse.
In your case this would be accomplished with the following:
<ul>
{% for key, value in linksList.items() recursive %}
<li>
{% if value is string %}
{{ key }}
{% else %}
{{ key }}
<ul>{{ loop(value.items()) }}</ul>
{% endif %}
</li>
{% endfor %}
</ul>
My 2 cents, just if someone comes here looking for rendering a JSON using Jinja, and complementing the response from #Ryon Sherman :)
Since JSON may have int values as well as strings, you can use if value is mapping (and flip the if-condition)
If your output must feel like a JSON you can use {{key|indent(width)}} + loop.depth
In my case, the template was for an email and key|indent() didn't work as expected so I ended up using an auxiliar {% for %} loop:
<div>
<code>{
{% for key, value in dic.items() recursive %}
{% if value is mapping %}
<p>
{% for it in range(loop.depth) %} {% endfor %}{{key}}: {
</p>
{{ loop(value.items()) }}
<p>
{% for it in range(loop.depth) %} {% endfor %}}
</p>
{% else %}
<p>
{% for it in range(loop.depth) %} {% endfor %}{{key}}: {{value}},
</p>
{% endif %}
{% endfor %}
}</code>
</div>
I'm relatively new to Django and I'm trying to build up my toolbox for future projects. In my last project, when a built-in template tag didn't do quite what I needed, I would make a mangled mess of the template to shoe-horn in the feature. I later would find a template tag that would have saved me time and ugly code.
So what are some useful template tags that doesn't come built into Django?
I'll start.
http://www.djangosnippets.org/snippets/1350/
Smart {% if %} template tag
If you've ever found yourself needing more than a test for True, this tag is for you. It supports equality, greater than, and less than operators.
Simple Example
{% block list-products %}
{% if products|length > 12 %}
<!-- Code for pagination -->
{% endif %}
<!-- Code for displaying 12 products on the page -->
{% endblock %}
smart-if. Allows normal if x > y constructs in templates, among other things.
A better if tag is now part of Django 1.2 (see the release notes), which is scheduled for release on March 9th 2010.
James Bennet's over-the-top-dynamic get_latest tag
edit as response to jpartogi's comment
class GetItemsNode(Node):
def __init__(self, model, num, by, varname):
self.num, self.varname = num, varname
self.model = get_model(*model.split('.'))
self.by = by
def render(self, context):
if hasattr(self.model, 'publicmgr') and not context['user'].is_authenticated():
context[self.varname] = self.model.publicmgr.all().order_by(self.by)[:self.num]
else:
context[self.varname] = self.model._default_manager.all().order_by(self.by)[:self.num]
return ''
<div id="news_portlet" class="portlet">
{% get_sorted_items cms.news 5 by -created_on as items %}
{% include 'snippets/dl.html' %}
</div>
<div id="event_portlet" class="portlet">
{% get_sorted_items cms.event 5 by date as items %}
{% include 'snippets/dl.html' %}
</div>
I call it get_sorted_items, but it is based on James' blog-post
In come case {% autopaginate queryset %} (http://code.google.com/p/django-pagination/) is useful. For example:
#views.py
obj_list = News.objects.filter(status=News.PUBLISHED)
# do not use len(obj_list) - it's evaluate QuerySet
obj_count = obj_list.count()
#news_index.html
{% load pagination_tags %}
...
# do not use {% if obj_list %}
{% if obj_count %}
<div class="news">
<ul>
{% autopaginate obj_list 10 %}
{% for item in obj_list %}
<li>{{ item.title }}</li>
{% endfor %}
</ul>
</div>
{% paginate %}
{% else %}
Empty list
{% endif %}
Note, that obj_list must be lazy - read http://docs.djangoproject.com/en/dev/ref/models/querysets/#id1