Login

Using the built-in slugify filter outside a template

Author:
jcroft
Posted:
February 27, 2007
Language:
Python
Version:
Pre .96
Tags:
template filter django slug built-in
Score:
4 (after 4 ratings)

This is just a very short (and mostly useless on it's own) example of how the built in slugify filter can be used in a Python script to generate slugs. It was pulled from a script I've written to pull in items from Upcoming.org's API.

I post it because "sunturi" posted Snippet #29, which duplicates the functionality of the built-in slugify filter. In the comments of that snippet, santuri (and others) seem to believe that template filters can only be used within templates. This is incorrect, and I think it's important people understand they can be used elsewhere.

sunturi's snippet does remove prepositions from values before slugifying them, so if you need that, his code will work work. But if all you need is slugification, the built-in slugify filter will work fine -- in a Python script, as well as in a template.

1
2
3
4
5
6
7
8
if city:
    from django.template import defaultfilters
    city_slug = defaultfilters.slugify(city)
    state_slug = defaultfilters.slugify(state_abbr)
    if state_slug:
        location_slug = city_slug + '-' + state_slug
    else:
        location_slug = city_slug

More like this

  1. Built-in Slugify with filtering. by jcrawford 6 years, 2 months ago
  2. slugify js -> python by santuri 8 years, 4 months ago
  3. Automatically slugify slug fields in your models by Aliquip 8 years, 3 months ago
  4. Database template loader by doomatel 3 years, 3 months ago
  5. slug_and_slash_to_dash - modified slugify for urls by bradmontgomery 4 years, 10 months ago

Comments

obeattie (on February 28, 2007):

Yeah, I do this all the time too when importing stuff from APIs

#

canen (on February 28, 2007):

People just need to realize that filters are just functions. I usually use the striptags filter when sending emails.

#

Please login first before commenting.