segunchrist segunchrist - 2 months ago 12
Python Question

Django Slugfield removing articles ('the', 'a', 'an', 'that')

I'm using django 1.10 and I have this setup:

class Chapter(models.Model):
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(unique=True)
date_completed = models.DateTimeField(blank=True, null=True)

completed = models.BooleanField(default=False)

def __str__(self):
return self.title


In the admin, I have :

class ChapterAdmin (admin.ModelAdmin):

list_display = ('title','slug', 'date_completed',)
list_filter = ['title', 'date_completed']
prepopulated_fields = {"slug": ("title",)}


I noticed that when I create a chapter with a title like "A boy and the pig", I get "boy-and-pig" as the slug. Django is stripping of the articles from my slug. Why is this so and what's the way around it?

Answer

Why is this so?

Well, that's the default behaviour of the Slugfield, in Django. Why is it like that? Because generally, it's been considered better for SEO.

(I say considered, as the article linked mentions this might be dated thinking. The premise is that articles and the like are usually considered Stop Words, the most common words in a language; they're so common that they are unhelpful for a search engine to index, as they feature in most, if not all titles. )

What's the Way Around It?

Firstly - why do you want to get around it? What's the use case?

But if you're satisified you really want to do it, then it's quite simple:

from django.template.defaultfilters import slugify
would_be_slug = 'This is one of those rarest of things: A blog that uses article.'
slugify(would_be_slug)
>>>u'this-is-one-of-those-rarest-of-things-a-blog-that-uses-article'

This answer has some great advice on overriding standard fields and slugfields.

There's also a nice package that will do this for you if you don't want to roll your own.