DEV Community

Cover image for SEO For Django: 5 Methods To Improve SEO
Maciej
Maciej

Posted on • Edited on • Originally published at janowski.dev

SEO For Django: 5 Methods To Improve SEO

This Week I decide to look into improving the SEO of my personal website. I don't know much about it, but after some research I found few things developers can do on their Django websites to improve your SEO.

What is SEO?

What is Search engine optimisation? It's a huge topic, but all you need to know as a web developer is that it's about making changes (optimising) to your website, to make it easier for search engines like Google to crawl, and index your content, which makes it easier for people to discover your content.

Why Should You Learn It?

Developers should learn SEO so they can plan for it when developing for the web. If you don’t optimise your page, it will not show up in searches, so other people won’t know your site exists. Also it’s a great complementary skill for freelancing web developers, so they can offer their clients fuller service package.

Let’s look at few ways to improve SEO of our Django site.

Slugs

Django provides a SlugField for its models. Slugs are short labels containing only letters, numbers, underscores or hyphens. We should create the URLs based on Slug fields. To create a canonical URL for the Post model, we use a Django convention to add a method for creating the URLs get_absolute_url()

from django.db import models
from django.utils import timezone


class Post(models.Model):
    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250, unique_for_date=publish)
    publish = models.DateTimeField(default=timezone.now)    

    def get_absolute_url(self):
        return reverse(blog:post_detail,
                            args=[self.publish.year,
                                    self.publish.month,
                                    self.publish.day, self.slug])
Enter fullscreen mode Exit fullscreen mode

Here we create a Post model, and the canonical URL will be created based on the published date and the slug for example /2020/04/07/post-title/

Meta Tags

Meta tags provide the search engines with information about your site, they should be placed within <head> tag in the HTML document.

title
When your page appears in the search results this, will be the first line/link.

Each page should have an unique title tag, and it should be short and descriptive.

Don't use generic titles, or the same title on multiple pages.

<title>This is page Title</title>
Enter fullscreen mode Exit fullscreen mode

description
This is the most important tag, it provides a description about the page of your website. Google will often use them as a preview snippet in the results of search.
The descriptions should be unique for each page, summarise what the page is about, and be 1-2 sentences short. Same as with title, don't make it generic or repeating over page.

<meta name="description" property="og:description" content="This article looks at 6 methods developers can use to improve SEO of their Django Website">
Enter fullscreen mode Exit fullscreen mode

keywords
This is a meta tag for keywords, it’s pretty self explanatory. Here we enter the keywords summarising our page.

<meta name="keywords" content="seo, python, django, web development">
Enter fullscreen mode Exit fullscreen mode

author
In this tag we specify the name of the author if it’s an article or something similar.

<meta name="author" content="Maciej Janowski">
Enter fullscreen mode Exit fullscreen mode

Open Graph Meta Tags

Open Graph was created by Facebook to promote integration between Facebook and 3rd party website, by allowing pasted content to become “graph” objects. It gives control over how information travels from your page to 3rd party website. Other websites that recognize Open Graph meta tags are Twitter, LinkedIn, Google+. You can identify them by their property attribute begging with “og:”

<meta property="og:url" content="https://janowski.dev/blog/2020/04/05/Intresting-article" />
<meta property="og:title" content="Intresting Article" />
<meta property="og:image" content="https://janowski.dev/static/cover.png" />
<meta property="og:image:alt" content="A green cover image with Django logo" />
Enter fullscreen mode Exit fullscreen mode

Twitter Tags

Another Type of Meta Tags are Twitter Tags.

They decide how will our link show up in twitter as a twitter card when we share it. We can test it here

<meta name="twitter:image" content="https//example.com/image.png" />
<meta property="twitter:image:alt" content="Description of the image" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@MaciejJanowski" />
Enter fullscreen mode Exit fullscreen mode

Sitemap

A sitemap is an XML file that tells search engines the pages of your website, their relevance, and how frequently they are updated. Using Sitemaps will make your site more visible in search engine ranking because sitemaps help crawlers to index your website's content.

Django comes with a sitemap framework, which allows us to generate sitemaps dynamically.

To install the Sitemap framework open [settings.py](http://settings.py) and add django.contrib.sites and django.contrib.sitemaps to the INSTALLED_APPS setting, and define a new ID for the site.

SITE_ID = 1

INSTALLED_APPS = [
   ...
    'django.contrib.sites',
    'django.contrib.sitemaps',
]
Enter fullscreen mode Exit fullscreen mode

Now create the tables for the site application

python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

Inside the application of your site let's say "blog" create a new file called sitemaps.py

Assuming we have a model called Post inside our "blog" application

from django.contrib.sitemaps import Sitemap

from .models import Post

class PostSitemap(Sitemap):
        changefreq = "weekly"
        priority = 0.9

        def items(self):
                return Post.objects.all()

        def lastmod(self, obj):
                return obj.updated
Enter fullscreen mode Exit fullscreen mode

Finally go to the main urls.py of the project and add the sitemap, as follows

from django.urls import path, include
from django.contrib.sitemaps.views import sitemap

from blog.sitemaps import PostSitemap

sitemaps = {
        "posts": PostSitemap,
}

urlpatterns = [
        path('blog/', include('blog.urls', namespace='blog')),
        path('sitemap.xml', sitemap, {'sitemaps': sitemaps},
                        name='django.contrib.sitemaps.views.sitemap')
]
Enter fullscreen mode Exit fullscreen mode

Now you can access the sitemap after opening http://127.0.0.1:8000/sitemap.xml

You should see output similar to this.
sitemap preview
This only scratches the surface of SEO, there is much much more to it.

Check out the tools and resources below to learn more about SEO for Developers.

Useful Tools

  • Lighthouse - Tool from google for calculating score for SEO, Accessibility and few other key metrics.
  • Google Pagespeed Insights - Another Google Tool, gives our site’s speed score or desktop and mobile.
  • Twitter Card Validator - Twitter tool for validating and previewing the Twitter Card.

Other Resources

Top comments (10)

Collapse
 
corentinbettiol profile image
Corentin Bettiol

Nice post!

Shameless advertising :

You can use django-check-seo (a django module I made) to ensure that your page don't have any SEO-related problem.
Here is how it look:

django-check-seo screenshot

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

It would be nice if you can make non-Django one, like a CLI script to analyze static HTML.

Collapse
 
corentinbettiol profile image
Corentin Bettiol

I searched on github topics (topic = seo, language = python) and I found python-seo-analyzer. It's exactly what you said: a CLI script which will analyze a page and return result (json or html) :)

Collapse
 
druidmaciek profile image
Maciej

That looks great! I will give it a go.

Collapse
 
c_v_ya profile image
Constantine

Thanks a lot! I literally just improved my blog's SEO score to 91% (although it's a SSRed site), great article 🚀

Site score

Collapse
 
druidmaciek profile image
Maciej

That's Awesome, great job!

Collapse
 
danidiaztech profile image
Daniel Diaz

Where do you check the SEO score

Collapse
 
c_v_ya profile image
Constantine

Chrome dev tools -> Lighthouse -> Generate report

Collapse
 
lucassimpsonfkse profile image
LucasSimpsonFKSE • Edited

These tips are really good. Thanks for sharing. I have talked with the guys from justseo.co.nz and they said that they use some of these tips. These guys are professionals and they know what are they doing. I have used their SEO services and I think that these services are the most effective. I am really happy with the results. I recommend everyone to contact them. These guys will help everyone with everything. These guys helped me to improve my website and my website became a lot more SEO friendly. I never seen a company that would do such a great job.

Collapse
 
zuridantethea_5bb0b546160 profile image
Zuridantethea

Thank you for sharing these valuable insights on enhancing SEO for Django applications. The emphasis on optimizing URLs and utilizing meta tags is particularly pertinent, as these elements significantly contribute to search engine discoverability. For those seeking further strategies, exploring Pearl Lemon Leads reviews could provide additional methodologies and insights that align with best practices in SEO enhancement