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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With