Search code examples
pythondjangounicodeslug

How to create slugs in arabic characters in Django?


I am wondering how to make slugs out of Arabic/Persian strings in django? What I am trying to achieve is to create slugs like:

این-یک-تیتر-است

out of این یک تیتر است

That is, all spaces, commas and parentheses need to be converted to hyphens.


Solution

  • Alright, thanks python's excellent string library, turned out to be easier than what I thought. Just need to define a function like this:

    def slugify(str):
        str = str.replace(" ", "-")
        str = str.replace(",", "-")
        str = str.replace("(", "-")
        str = str.replace(")", "")
        str = str.replace("؟", "")
        return str
    

    Then in your model's class you should have a function like:

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
    

    Note: This line should be present at the beginign of the module.py

    # -*- coding: utf-8 -*-
    

    otherwise you may get an error like:

    SyntaxError: Non-ASCII character ...