Changes all slugify calls to support translat automatically, behind the scenes. Using this one doesn't have to change any models or code to make it work everywhere.
Create new project, I call it myself autoslugifytranslat, and add the following to project's __init__.py
file. It will automatically add translat slugify support for all default slugify calls.
This script is depending on the fact that slugify function in Django is always in django.template.defaultfilters.slugify.
Note: The snippet is supposed to have "ä","Ä" and "ö","Ö" in the char_translat
list, but djangosnippets does not let me put ä's and ö's to the code part!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | # -*- coding: utf-8 -*-
from django.template import defaultfilters
# TODO: Study whether this is enough, if Django does not do any strange stuff this should be enough to make it overwrite the slugify function in any case.
# Get the old slugifier
old_slugify = defaultfilters.slugify
def translat_slugify(str):
char_translat = {
("ä","Ä",) : "a",
("ö","Ö",) : "o",
}
for chars,trans in char_translat.items():
for char in chars:
str = str.replace(char.decode('utf-8'),trans)
return old_slugify(str)
# "Overwrite" the old slugify
defaultfilters.slugify = translat_slugify
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
The idea is good, it should be extended to do total ASCII replacement like AsciiDammit.py. Also, I recommend using re.sub for multiple replacements like this.
#
Exogen, thanks! I didn't knew about AsciiDammit.py before.
Although it looks like (what I've found from google) that the translat table is hardcoded to python code in AsciiDammit.py. It is not good, after all it really isn't languages problem to handle such general things. I know better solution, using iconv and it's ratherly new feature translat to convert umlauts and friends to ASCII. Unfortunately I have no time to implement that.
And yes, this was more of intended as example how you can get rid of the "My 3rd party app (for example one in contrib) uses slugify function that does not support my umlauts blah blah..."
#
Please login first before commenting.