Login

Built-in Slugify with filtering.

Author:
jcrawford
Posted:
April 10, 2009
Language:
Python
Version:
1.0
Score:
1 (after 1 ratings)

This is based on snippets 29 and 43, both of which had good ideas, and I thought, "why not combine them?"

Given the new_topic string above, the resulting slug will be:

"test-long-string-which-has-many-words-here"

John Crawford

Note - requires python 2.5, for list comprehensions. Otherwise you could just use a for loop to build the clean_list.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
    from django.template.defaultfilters import slugify

    removelist = ["a", "an", "as", "at", "before", "but", "by", "for",\
    "from","is", "in", "into", "like", "of", "off", "on",\
    "onto","per","since", "than", "the", "this", "that",\
    "to", "up", "via","with"]

    new_topic = "this is a test with a long string which has many words up to here."

    clean_list = [str(word) for word in new_topic.split() if word not in removelist]

    new_slug = slugify(clean_list)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

carljm (on April 10, 2009):

List comprehensions have been in Python a lot longer than 2.5; since 2.0, I believe. Even generator expressions were introduced already in 2.4.

#

jcrawford (on April 10, 2009):

Arg, you're right - I was thinking ternary operators, for some reason... wups.

#

Please login first before commenting.