Custom filters for django templates

497 views
Skip to first unread message

hairylarry

unread,
Jul 21, 2008, 5:33:35 PM7/21/08
to Google App Engine
Hi,

Here's the article.

http://daily.profeth.de/2008/04/using-custom-django-template-helpers.html

I found it in another post.

Pay attention to the comment. The line.

webapp.template.register_template_library('common.templatefilters')

usually comes right after the import statements.

Also you must create an empty text file called __init__.py

This is shown in the illustration but not mentioned in the article.

I followed his instructions exactly without modifying any code. I got
an error until I created the __init__.py file. Then it worked.

Then I easily created 2 filters, one to replace underscores with
spaces and one to replace spaces with underscores. I prefer
underscores in urls to %20 but I always want spaces not underscores
when displaying values on the screen.

You do have to import your methods into templatefilters.py just like
any python code.

Here's my modified code.

-----
# import the webapp module
from google.appengine.ext import webapp
from string import replace

# get registry, we need it to register our filter later.
register = webapp.template.create_template_register()

def truncate(value,maxsize,stopper = '...'):
""" truncates a string to a given maximum
size and appends the stopper if needed """
stoplen = len(stopper)
if len(value) > maxsize and maxsize > stoplen:
return value[:(maxsize-stoplen)] + stopper
else:
return value[:maxsize]

register.filter(truncate)

def under2space(value):
return replace(value,"_"," ")

register.filter(under2space)

def space2under(value):
return replace(value," ","_")

register.filter(space2under)
-----

Thanks,

Hairy Larry

g-man

unread,
Jul 21, 2008, 11:19:25 PM7/21/08
to Google App Engine
I, for one, appreciate your keeping all of us up-to-date on your
explorations and discoveries, Larry!

As a companion piece, here's my Django template tag that creates a
table of a fixed number of columns, for display of my growing tag
collection, as in:

{% table_row_cells 4 forloop.counter %}

... which simply divides the current count by the desired column
cutoff (4 in my case), and if the remainder (modulo) is zero, starts a
new row; comes in handy for those long lists of things.

ps - I don't know why you need to bring webapp into the mix; I never
need to get near it!

-----
from django import template
register = template.Library()

@register.tag
def table_row_cells(parser, token):
try:
tag_name, cells, loop_count = token.split_contents()
except ValueError:
msg = '%r tag requires a single number of row cells desired...' %
token.contents[0]
raise template.TemplateSyntaxError(msg)
return TableRowCellsNode(int(cells))

class TableRowCellsNode(template.Node):
def __init__(self, cells):
self.cells = cells
def render(self, context):
if context['forloop']['counter']%self.cells is 0:
return '</tr>'
return ''
-----

My learning app is here:

http://archi-checker.appspot.com

(I think the above implementation is hidden behind my 'admin' curtain,
but it works, trust me!)


On Jul 21, 2:33 pm, hairylarry <hairyla...@gmail.com> wrote:
> Hi,
>
> Here's the article.
>
> http://daily.profeth.de/2008/04/using-custom-django-template-helpers....

Arun Shanker Prasad

unread,
Aug 1, 2008, 6:11:28 AM8/1/08
to Google App Engine
Hi,
@g-man ,

I am also not using the webapp with google app engine,
but when I try to load the filter in the template an exception is
raised

'customfilters' is not a valid tag library: Could not load template
library from django.templatetags.customfilters, No module named
customfilters

My Code:
import django
from django import template

register = template.Library()

@register.filter('modulo')
def modulo(value, arg):
if value % arg == 0:
return True
else:
return False

In Template
{% load customfilters %}

Am i missing something? any help will be appricicated

joune

unread,
Sep 3, 2008, 9:28:24 AM9/3/08
to Google App Engine
Hi there,

just meant to say that i have the very same problem..
i followed django documentation to create a custom filter in
my_utils.py that i put under a templatetags directory under my app and
along with an empty __init__.py file
the {% load my_utils.py %} tag throws the same
TemplateSyntaxError: 'my_utils' is not a valid tag library

i came to wonder if there was a limitation on custom filters in google
appEngine.. (but it seems to work for g-man)
i based my code on this sample:
http://google-app-engine-samples.googlecode.com/files/django_example_20080409.tar.gz
and didn't change anything to settings.py (maybe i should have?)

any input no this would be very helpful!

thanks..



On Aug 1, 12:11 pm, Arun Shanker Prasad <ArunShankerPra...@gmail.com>
wrote:

Fred

unread,
Sep 23, 2008, 4:46:39 PM9/23/08
to Google App Engine
Hello,

Just had this same problem myself, and found the solution -- you need
to do the following:

- create a templatetags directory INSIDE one of what Django calls your
'installed apps.' Apps are modules directly under your project root,
for example, if your project has an app named home, your directory
structure should look like:

project/
home/
templatetags/

- Create an empty __init__.py in the templatetags directory.
- In the templatetags folder, create another file for your filter,
e.g., my_awesome_filter.py

You have, now:
project/
home/
templatetags/
__init__.py
my_awesome_filter.py

Now, at this point, tutorials leave the expectation that {% load
my_awesome_filter %} should just work, but there's one little piece of
magic they leave out: you have to add your app to Django's list of
INSTALLED_APPS so that the template tag loader can find it. Edit
settings.py, add an entry to the INSTALLED_APPS tuple as follows
(excerpted from my live app, yours will differ):
INSTALLED_APPS = (
'appengine_django', # Use the App Engine helper
'django.contrib.auth', # Load up the Django auth system
(optional, but I like it)
'home' # <-- Added
)

Worked like a charm for me.

best,
- Fred.


On Sep 3, 6:28 am, joune <jounepan...@gmail.com> wrote:
> Hi there,
>
> just meant to say that i have the very same problem..
> i followed django documentation to create a custom filter in
> my_utils.py that i put under a templatetags directory under my app and
> along with an empty __init__.py file
> the {%loadmy_utils.py %} tag throws the same
> TemplateSyntaxError: 'my_utils' is not a valid tag library
>
> i came to wonder if there was a limitation on custom filters in google
> appEngine.. (but it seems to work for g-man)
> i based my code on this sample:http://google-app-engine-samples.googlecode.com/files/django_example_...
> and didn't change anything to settings.py (maybe i should have?)
>
> any input no this would be very helpful!
>
> thanks..
>
> On Aug 1, 12:11 pm, Arun Shanker Prasad <ArunShankerPra...@gmail.com>
> wrote:
>
> > Hi,
> > @g-man ,
>
> > I am also not using the webapp with google app engine,
> > but when I try toloadthe filter in the template an exception is
> > raised
>
> > 'customfilters' is not a valid tag library: Could notloadtemplate
> > library from django.templatetags.customfilters, No module named
> > customfilters
>
> > My Code:
> > import django
> > from django import template
>
> > register = template.Library()
>
> > @register.filter('modulo')
> > def modulo(value, arg):
> >     if value % arg == 0:
> >         return True
> >     else:
> >         return False
>
> > In Template
> > {%loadcustomfilters %}
>
> > Am i missing something? any help will be appricicated
>
> > On Jul 22, 8:19 am, g-man <gregor...@gmail.com> wrote:
>
> > > I, for one, appreciate your keeping all of us up-to-date on your
> > > explorations and discoveries, Larry!
>
> > > As a companion piece, here's my Djangotemplate tagthat creates a
Reply all
Reply to author
Forward
0 new messages