Home > Enterprise >  Creating more SEO friendly urls in Django
Creating more SEO friendly urls in Django

Time:08-26

I have a slug field for my Article model:

class Article(models.Model):
    Title = models.CharField(max_length=100, blank=False, null=False)
    Hero_image = models.ImageField(upload_to='hero-images/', blank= False, null=False)
    Image_caption = models.CharField(max_length=50, blank=False, null=False, default=" ")
    Content = tinymce_models.HTMLField(null=False, blank=False)
    Category = models.ManyToManyField(ArticleCategory,blank=False,related_name="articles")
    Published_date = models.DateTimeField(auto_now_add=True)
    Last_modified = models.DateField(auto_now=True)
    slug = models.SlugField(null=False, unique=True)

    def get_absolute_url(self):
        return reverse('blog-details', kwargs={"slug": self.slug})

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.Title)
        return super().save(*args, **kwargs)

And here is the blog-details view:

def blog_details(request, slug):
    Articles = Article.objects.get(slug=slug)

    context = {
        "Articles": Articles,
        }
    return render(request, "blog-details.html", context)

The URL path for the blog-details is :

path('(?P<slug>[-a-zA-Z0-9_] )/', views.blog_details, name='blog-details'),

which gives me URLs like : http://127.0.0.1:8000/blogs/(?Pkonstantin-the-guy-who-whatevers[-a-zA-Z0-9_] )/ I wonder if this URL format is SEO friendly, and can I make it more human-readable .i.e: http://127.0.0.1:8000/blogs/konstantin-the-guy-who-whatevers/

CodePudding user response:

You have left in your regular expressions when you just want to use the slug

path('(?P<slug>[-a-zA-Z0-9_] )/', views.blog_details, name='blog-details'),

can simply be

path('<slug: slug>', views.blog_details, name='blog-details'),

see the docs for more

  • Related