by MJ

Django Slug

Spent far more time than I thought I would turning my URLs into slugs. 

Iniitally when creating this site, all content would be numbered. This was cool after a while--being able to see how many posts and articles I've created. With all the testing that I've done--creating and deleting my writing--the numbers stopped making sense, and it was bugging me. 

If you take a look at the URL of this post you won't see a number but instead see the title/slug. Such a small detail, but it took me 4 hours to get done--mostly because I was figuring out a script to update my old posts and articles. I had some posts that had special characters and causing a lot of errors, so for old content, I removed everything that wasn't alphanumerical and joined them. Here's the script I ran:


# import my model

from articles.models import Article

# query all articles to be used in a for loop

articles = Article.objects.all()

for article in articles:

    # use the join method with a loop to keep values that return true if they are alphanumerical

    # using article.title to make the slug name match the title.

    article.slug = ''.join(e for e in article.title if e.isalnum())

    # save