SEO friendly urls in Django

Last updated 13 days ago by Dani Hodovic

django

Examples sites built with Django usually use primary keys as the URL identifier for a resource. While this is the simplest and cleanest approach to resource urls, it's not optimized for SEO.

It's debatable on whether or not keywords in urls matter for Google, but it's obvious that most of the major players have adopted this technique. Below are five examples of popular sites that all use keywords in urls to improve their SEO.

  • Stackoverflow - https://stackoverflow.com/questions/8318911/why-does-html-think-chucknorris-is-a-color
  • Wikipedia - https://en.wikipedia.org/wiki/Python(programminglanguage)
  • Amazon.com - https://www.amazon.com/Django-Unchained-Jamie-Foxx/dp/B00BJS7104/
  • Reddit - https://www.reddit.com/r/soccer/comments/c22vuf/refereetrollsplayer/
  • Dev.to - https://dev.to/danihodovic/optimizing-postgres-full-text-search-with-django-42hg

If you poke around at the top 100 sites as ranked by Alexa you will notice that most sites with public facing content use some sort of keywords approach in their urls.

Besides being a possible SEO optimization strategy it also improves the chances that a user will click on your link over other links.. Both Chrome and Firefox will match and highlight parts of urls that match the keywords if the user has visited the site previously.

Google search bar

Show me the code

Django doesn't have views that use keywords in urls out of the box, but it's trivial to add. I'll go through a basic example with job postings that we use at findwork.dev.

Suppose we have a model for job postings that have a company name and a role.

``` # models.pyfrom django.db import models

class JobPosting(models.Model): companyname = models.CharField(maxlength=50) role = models.CharField(max_length=50) ```

We have a view which shows each job by primary key in the url:

``` # views.py

from django.httpimport HttpResponse from django.shortcuts import getobjector_404

from .models import JobPosting def jobpostingview(request, pk): job = getobjector404(JobPosting, pk=pk) html = f"""

{job.role} at {job.companyname}

""" return HttpResponse(html) ```

Read full Article