Make your Django app SEO friendly in an afternoon

· 5 min read

Search engines are not magic. They fetch your pages, read the HTML and decide what each page is about. Django already gives you clean URLs and server rendered pages, which is most of the battle. What is left is a short list of basics that vibe coded apps often skip. Here is that list, with code.

One title and one description per page

The title is the blue link in the result and the description is the grey text under it. Every page needs its own. Put blocks in your base template so each page can fill them in.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{% block title %}My App{% endblock %}</title>
  <meta name="description" content="{% block description %}A short sentence about the whole site.{% endblock %}">
  <link rel="canonical" href="{{ request.scheme }}://{{ request.get_host }}{{ request.path }}">
</head>

Keep titles under about 60 characters and descriptions between 70 and 160. Say what the page is, in the words a visitor would use. "Pricing" is weak. "Pricing: one plan, 14-day trial" is better. Do not repeat the same title on every page.

The canonical link tells search engines which address is the main one for a page. Building it from the path, as above, drops tracking parameters like ?utm_source= so they do not create duplicate pages.

Also note the lang attribute on html and the viewport tag. Both are cheap and both are checked by tools.

One h1

Each page should have exactly one h1 that says what the page is. Use h2 and below for sections. A page with no h1, or with five, is a common sign of a template pasted together in a hurry.

A sitemap in four lines

Django ships a sitemap framework. Add it to your settings:

INSTALLED_APPS = [
    # ... your existing apps
    "django.contrib.sitemaps",
]

Then describe the pages:

from django.contrib.sitemaps import Sitemap
from django.urls import reverse


class StaticPages(Sitemap):
    """List the fixed pages of the site."""

    changefreq = "monthly"
    protocol = "https"

    def items(self):
        return ["home", "about", "pricing"]

    def location(self, item):
        return reverse(item)

And wire it up in urls.py:

from django.contrib.sitemaps.views import sitemap

urlpatterns = [
    path("sitemap.xml", sitemap, {"sitemaps": {"pages": StaticPages}}, name="sitemap"),
]

For pages that come from the database, such as blog posts, write a second class whose items() returns a queryset and give your model a get_absolute_url. Without the sites framework installed, Django builds the addresses from the host of the request, which is what you want for an app that can be reached on more than one address.

robots.txt

Search engines look for /robots.txt before anything else. A tiny view is enough:

from django.http import HttpResponse


def robots(request):
    lines = [
        "User-agent: *",
        "Allow: /",
        "Disallow: /admin/",
        f"Sitemap: {request.build_absolute_uri('/sitemap.xml')}",
    ]
    return HttpResponse("\n".join(lines), content_type="text/plain")

Add path("robots.txt", robots) to your URLs. Two warnings. First, never leave Disallow: / in place from a staging copy, because it tells every search engine to skip the whole site. Second, robots.txt is not security. It asks polite crawlers to stay away, and it also publishes the paths you list. Protect private pages with a login, not with a Disallow line.

Structured data

Structured data is a block of JSON in the page that states facts in a format machines read well. For a small business, a page can describe itself as an organisation or a local business. Build it in Python so quotes are escaped properly:

import json


def organisation_json(name, url):
    data = {"@context": "https://schema.org", "@type": "Organization", "name": name, "url": url}
    return json.dumps(data).replace("<", "\\u003c")

Print it in the template with <script type="application/ld+json">{{ organisation|safe }}</script>. The replace on the angle bracket matters: it stops a name containing </script> from closing your tag early.

Return a real 404

When a page does not exist, the server must say so with a 404 status. A common mistake is to redirect unknown addresses to the home page, or to show a friendly "not found" page with a 200 status. Search engines call that a soft 404 and it confuses them.

With DEBUG = False, Django returns a 404 status for unknown paths and renders 404.html from your templates folder. Add that file with a link back to the home page and leave the rest to Django. In your own views, use get_object_or_404 or raise Http404 instead of returning an empty page.

Speed and HTTPS

Speed is part of ranking and a lot more part of whether a visitor stays. For a Django app the cheap wins are:

  • Serve static files with WhiteNoise and turn on compression and file names with a hash: STORAGES = {"staticfiles": {"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage"}, ...} together with python manage.py collectstatic.
  • Resize images before you upload them. A 4 MB photo on a home page is the usual culprit.
  • Avoid loading fonts and scripts from other sites unless you need them.

For HTTPS, the visitor should end up on https:// whichever address they type. If your host terminates HTTPS before your app, tell Django to trust the forwarded header so it knows the request was secure:

SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")

Without that line, absolute links and the canonical tag come out as http://, and the admin login can fail its CSRF check.

Check your work

Open your site and view the source of the home page. You should see a title, a description, a canonical link, one h1 and a lang attribute. Visit /robots.txt, /sitemap.xml and a made up address like /no-such-page/. The last one must show your 404 page, and the browser's network tab should say 404.

If your app is on Pharos, the Launch checklist on your app page runs these same checks from the outside after each deploy and tells you which ones failed, with a one line fix. A trial is 14 days, and a plan is A$27 a month after that. See what the launch checklist checks.