remy
remy

Reputation: 4743

Django, how to override slugify function

I want my colons slugified into dashes instead of empty strings. I guess I could put something like slugify(self.name.replace(":", "-")) into my save() methods but that wouldn't be DRY at all (I think).

Also I could add that .replace() operation directly into django.utils.text.slugify

def slugify(value):
    value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
    value = value.replace(":", "-")
    value = re.sub('[^\w\s-]', '', value).strip().lower()
    return mark_safe(re.sub('[-\s]+', '-', value))

This doesn't seem like a good idea. How do I do it with regex?

  1. How do I do it with regex?
  2. How do I tie this override to a project rather than doing it inside django package?

Upvotes: 4

Views: 835

Answers (1)

Simeon Visser
Simeon Visser

Reputation: 122436

I would implement a custom slugify function within your project with the desired changes:

def myslugify(value):
    return slugify(value.replace(":", "-"))

You can use this function in your save() methods of your models. This keeps your code free from "magic" as others would expect slugify to work the way Django implemented it.

Upvotes: 2

Related Questions