print list of dictonaries to template - python

this may be silly question, But newbie here, need some help
I need to print dictionary to template
template_var = {}
settings = Article.objects.filter().values('title','content')
for some in settings:
pprint.pprint(some)
the output of console log is
{'content': u'add blog ', 'title': u'blog here'}
{'content': u'fweferwgfwefw', 'title': u'few'}
{'content': u'fsvbfsvbsfvsdfv', 'title': u' fsfsbfsbvsfvb'}
this is the way i am passing some to template_var['article']= some. And in my html i do like this
{% for content in some %}
{{ content }}
{% endfor %}
but that's not working.

You're iterating settings in the for statement:
for some in settings:
pprint.pprint(some)
But, the view code is passing some instead of settings to the template, and iterating it. In addition to that, the code is passing the variable as article, but it is used as some in the template.
Make them to be consistent:
view
template_var['settings'] = settings
template
{% for some in settings %}
{{ some }}
{% endfor %}

If you want to print the dictonary to templates the you can do
in viwes.py
return render(request, "template.html", { 'settings' : settings})
and in template.html
this is for getting entire dictonary
{% for set1 in settings %}
{{set1}}
{% endfor %}
and this is for getting each element of dictonary
{% for set1 in settings %}
{{set1.content}}<br/>
{{set1.title}}
{% endfor %}

Related

Django Python, Pass a dictionary and print it's content in html template

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.

How to slice a list in Django template?

I'm doing some pagination in Django. I want to show the pages' number which are ahead of the current page. I am using the following code:
{% for page in blogs_page.paginator.page_range|slice:"0:{{ blogs_page.number }}" %}
But this seems useless; the result does the same as the following:
{% for page in blogs_page.paginator.page_range %}
The slice does not work here. How do I fix this?
Never use {{ }} inside of {% %}, don't do this {% {{ }} %}.
{% for page in blogs_page.paginator.page_range|slice:"0:blogs_page.number" %}
I think it won't work. If I were you I would create a custom tag and executed all the logic there. So, it will look like this:
Template:
{% custom_tag blogs_page as result %}
{% for page in result %}
templatetags/tags.py:
from django import template
register = template.Library()
#register.simple_tag
def custom_tag(bl_page):
return bl.page.paginator.page_range[0:bl_page.number]
Details: custom tags

Creating a custom template tag to replace the for loop - Django

I am trying to simplify my code by creating a custom template tag for a 'for loop' that use frequently on my Django web application. I thought it would be a simple straight process, but something isn't working right... I can use some assistance in catching my error.
Here is my code.
views.py
class ArticleView(DetailView):
model = Articles
def get_context_data(self, **kwargs):
context = super(ArticleView, self).get_context_data(**kwargs)
context['s_terms'] = scientific_terms.objects.all()
return context
template tag
#register.filter(name='term')
def term(value):
{% for term in s_terms %}
{{ term.short_description }}
{% endfor %}
template.html
{% Neurons|term %}
Thank you for your assistance, in advance.
You are mixing Python code with the Django Template Language. The template tags are plain Python code, as they are defined inside a Python module. A working example would be:
#register.filter(name='term')
def term(terms):
output = ''
for term in terms:
output = '{0} {1}'.format(output, term.short_description)
return output
Then you could use it like this:
{{ s_terms|term }}
Maybe what you want is simply to create a reusable Django template.
For example, create a new template named terms.html:
templates/terms.html
{% for term in terms %}
<p>{{ term.short_description }}</p>
{% endfor %}
Then, in another template, you could include this partial template:
templates/index.html (name is just an example)
{% extends 'base.html' %}
{% block content %}
<h1>My application</h1>
{% include 'terms.html' with terms=s_terms %}
{% endblock %}

Pass and View Dictionary from view to template in django

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

Generate dynamic URLs with Flask

I'm trying to build a simple flask page that displays links from a dictionary of text/links:
urls = {'look at this page': www.example.com, 'another_page': www.example2.com}
#app.route('/my_page')
def index(urls=urls):
return render_template('my_page.html',urls=urls)
My template page looks like this:
{%- block content %}
{%- for url in urls %}
{{ url }}
{%- endfor %}
{%- endblock content %}
I can't quite seem to understand how to create dynamic urls like this. The code produces this error:
TypeError: 'NoneType' object has no attribute '__getitem__'
Can anyone point out my problem or a solution?
UPDATE: Here's my updated code:
#app.route('/my_page')
def index():
context = {'urls': urls}
return render_template('index.html', context=context)
And the template:
{%- block content %}
{% for key, data in context.items() %}
{% for text, url in data.items() %}
{{ text }}
{% endfor %}
{% endfor %}
{%- endblock content %}
This solution is close, however each link get prepended with my app's url. In other words I get this:
look at this page
I just want:
look at this page
Try this instead:
urls = {
'A search engine.': 'http://google.com',
'Great support site': 'http://stackoverflow.com'
}
#app.route('/my_page')
def index(): # why was there urls=urls here before?
return render_template('my_page.html',urls=urls)
{%- block content %}
{%- for text, url in urls.iteritems() %}
{{ text }}
{%- endfor %}
{%- endblock content %}
url_for is only for building URLs with Flask. Like in your case:
print url_for('index') # will print '/my_page' ... just a string, no magic here
url_for takes an endpoint name as first parameter which is by default the name of the view function. So the endpoint name for your view function index() is simply 'index'.

Categories