I'm trying to implement some custom template tags to to a little more with my app and structure it better. The annoying part is that I've followed a tutorial type post to get the code & it still doesn't work.
I've tried to follow this and current_time to implement some tags but I'm getting errors which I don't understand.
First off, the filter of latest posts, or in my case latest screens gives
Exception Value: No module named gallery
My project is called 'S3gallery', my app is called 'gallery' and my model is called 'screenshots'. The model arg of the tag says in the docs it takes app_name.Model_name which is what I give it, so I'm stuck on this.
My custom tag code looks like this;
from django.template import Library, Node
from django.db.models import get_model
register = Library()
class LatestContentNode(Node):
def __init__(self, model, num, varname):
self.num, self.varname = num, varname
self.model = get_model(*model.split('.'))
def render(self, context):
context[self.varname] = self.model._default_manager.all()[:self.num]
return ''
def get_latest(parser, token):
bits = token.contents.split()
if len(bits) != 5:
raise TemplateSyntaxError, "get_latest_screens tag takes exactly three arguments"
if bits[3] != 'as':
raise TemplateSyntaxError, "second argument to the get_latest_screens tag must be 'as'"
return LatestContentNode(bits[1], bits[2], bits[4])
get_latest = register.tag(get_latest)
I try to load that in the template using {% load get_latest gallery.screenshots 5 as recent_screens %}
and the examples I've seen don't use 'load' in the tag but if I do that Django doesn't recognise the tag. Do I'm lost by that, but think I'm going to the right way.
Any help on this would be greatly appreciated :)
The {% load %}
template tag is used to load your custom template tag, not render it. If your get_latest
tag is defined in a module my_tags.py
, then you should load it using
{% load my_tags %}
See the code layout section of the docs for more information.
Once you've loaded the tag in your template, then you can use it:
{% get_latest gallery.screenshots 5 as recent_screens %}