Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pretty and seo friendly urls in django

Tags:

url

seo

django

I am currently writing a web-blog, learning django. I need a view to display a single blog-post and my first try was to create a url for it like the following:

myblog.com/blog/view/1

This uses the blog-id to identify the specified blog-post.

Now if you look at many blogs/website, you see that they use the title of a blog-post in the url, this is because this is more search-engine friendly, so it can be easier found. This might look like this.

myblog.com/blog/view/a-python-backup-script

How do I implement this in django?

Bonus Question: A lot of sites also include the month and the year of a post. I guess this has also to do with SEO, but how exactly is that useful?

like image 279
Luke Avatar asked Aug 09 '12 08:08

Luke


1 Answers

Add a slug field to your Blog model.

from django.template.defaultfilters import slugify

Class Blog(models.Model):
    title = models.CharField(max_length=40)
    slug = models.SlugField(_('slug'), max_length=60, blank=True)

    #Then override models save method:
    def save(self, *args, **kwargs):
        if not self.id:
            #Only set the slug when the object is created.
            self.slug = slugify(self.title) #Or whatever you want the slug to use
        super(Blog, self).save(*args, **kwargs)

In your urls.py

(r'^blog/view/(?P<slug>[-\w]+)/$', 'app.views.blog_view'),

In views.py

def blog_view(request, slug):
    blog = Blog.objects.get(slug=slug)
    #Then do whatever you want

EDIT: I added a check in the save method since you want the slug to be created when the object is created. It shouldn't be saved everytime.

like image 64
Mikael Avatar answered Oct 11 '22 20:10

Mikael