django inclusion tag not rendering - python

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

Related

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

django tag 'get_recent_articles' received too many positional arguments

I am trying to make a recent article list in the sidebar of my blog. So I make a tag in templatetags.
I use django1.8 and python2.7.
templatetags/blog_tags.py
from ..models import Article,Category
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
#register.simple_tag
def get_recent_articles(num=5):
return Article.objects.all()[:num]
base.html
{% load blog_tags %}
<!DOCTYPE html>
...
<div class="widget widget-recent-posts">
<h3 class="widget-title">recent</h3>
{% get_recent_articles as article_list %}
<ul>
{% for article in article_list %}
<li>
{{ article.title }}
</li>
{% endfor %}
</ul>
</div>
When I runserver,Template error,Traceback display the problem line is {% get_recent_articles as article_list %}
TemplateSyntaxError at /blog/index/
'get_recent_articles' received too many positional arguments
How do I solve this error? Please give me some advices.
Any help will be much appreciated.
The ability for simple tags to store their results in a variable was added in Django 1.9.
In previous versions, you should use the assignment_tag decorator instead.

Breaking template on {% load rango_template_tags %}

So I am half way through a tutorial useing the book Tango With Django trying desperately hard to take on as much information as i can about Django.
Now i am trying to set up a template that lists all the category's but i get an error
invalid syntax (rango_template_tags.py, line 8)
I have no idea why i am getting this line, absolutely none i have checked it with the book 5 + times but i cant find anything that looks out of place of wrong. Can anyone please tell me why i am getting this error.
Base.html
{% load rango_template_tags %}
<div>
{% block sidebar_block %}
{% get_category_list %}
{% endblock %}
</div>
# This file has more within it these are the new pieces of code that break the template system. If these are in it wont work.
rango_template_tags
from django import template
from rango.models import Category
register = template.Library()
#register.inclusion_tag('rango/cats.html')
def get_category_list():
return {'cats' Category.objects.all()}
cats.html
<ul>
{% if cats %}
{% for c in cats %}
<li>{{ c.name }}</li>
{% endfor %}
{% else %}
<li><strong> There ar eno categories presen. </strong></li>
{% endif %}
</ul>
In python dictionary, each key is separated from its value by a colon (:)
Change your return statement from {'cats' Category.objects.all()} to {'cats': Category.objects.all()} and code within function or block should be idented.
from django import template
from rango.models import Category
register = template.Library()
#register.inclusion_tag('rango/cats.html')
def get_category_list():
return {'cats': Category.objects.all()}

What are some useful non-built-in Django tags?

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

django:error with the custom inclusiong_tag, error info:Invalid block tag

I'm trying to write a custom inclusion_tag in django.
Following the example on http://docs.djangoproject.com/en/dev/howto/custom-template-tags/
I'm just writing
from django import template
from libmas import models
register = template.Library()
#register.inclusion_tag('records.html')
def display_records(book_id):
book = models.book.objects.get(id__exact=book_id)
records = models.objects.filter(books=book)[0:10]
return {'records':records}
But I'm getting a
Invalid block tag: 'libmas_tags'
error in ie .
'records.html' file:
{% for record in records %}
<blockquote>{{record.id}}</blockquote>
{% endfor %}
my other html file is :
{% extends "admin/change_form.html" %}
{% libmas_tags %}
{% block after_field_sets %}
{% if object_id %}
{% display_records object_id %}
{% endif %}
{% endlock %}
The problem lies in your template. Its calling {% libmas_tags %}. Have you created template tags called libmas_tags? If so you might need to change it to
{% load libmas_tags %}
What is libmas_tags? The tag you have defined is called display_records, and that's what you should be calling in your template. If the tags file is called libmas_tags, you'll need to load that first as czarchaic points out.

Categories