SEO in Django: meta tags, sitemaps and AI search

SEO in Django means making every page of your Django app easy for search engines to crawl, understand and present well. The essentials are a unique <title> and meta description for each page, a canonical URL, a sitemap built with django.contrib.sitemaps, a robots.txt file, and structured data in JSON-LD. All of them fit in your templates, a few views and a context processor.
The same work now decides whether your pages show up in AI answers. Google’s AI Overviews and AI Mode pick their links from the regular Search index, while ChatGPT, Claude and Perplexity send their own crawlers to read your pages. This guide sets up the essentials in Django, covers what AI search adds to them and what it doesn’t, and shows how AI tools can take on part of the work.
Why SEO matters for a Django app
Django renders HTML on the server, which already puts it ahead of many single-page apps: a crawler gets the full content on its first request. What Django leaves to you is the metadata. Without it, every page shares one title, search results show whatever text the engine picks, and new pages wait to be discovered through links.
Getting it right pays off in three ways:
- People find your pages. A sitemap and clear
robots.txtrules tell crawlers what to index and when it changed. - People click. The title and description are your page’s pitch in the results, and they decide whether someone clicks.
- AI answers cite you. AI search tools quote and link the pages they can read and understand.
Titles and meta descriptions
Both go in the page’s <head>. Search engines use them to build the result people see: the title as its first line, the description often as the text under it.
Title tag
<title>Page title | Site name</title>The title is one of the strongest signals of what a page is about, and the first thing people read in the results.
Best practices
- Write a unique title for each page.
- Put the most important words first.
- Keep it brief and descriptive, about 60 characters, so it isn’t cut off.
Avoid
- Using a single title for all pages.
- Opting for generic titles, like “Home” or “Products”.
Meta description
<meta name="description" content="A one- or two-sentence summary of this page.">Google doesn’t use the meta description to rank pages, and it may rewrite the snippet to match a query. A good description still earns the click, so write one for every page that matters.
Best practices
- Write a unique description for each page.
- Aim for one or two sentences.
- Summarize what the reader will get from the page.
Avoid
- Using generic descriptions.
- Overloading with keywords.
- Duplicating the same description across all pages.
How to add meta tags in Django
Write the tags once, in your base template, and let each view fill them in. When a view sets nothing, the site’s defaults apply:
{# templates/base.html #}
<head>
<title>{% if meta_title %}{{ meta_title }} | {% endif %}Site name</title>
<meta name="description" content="{{ meta_description|default:'A default summary of the site.' }}">
<link rel="canonical" href="{{ canonical_url }}">
<meta property="og:title" content="{{ meta_title|default:'Site name' }}">
<meta property="og:description" content="{{ meta_description|default:'A default summary of the site.' }}">
<meta property="og:url" content="{{ canonical_url }}">
</head>The og: tags are Open Graph: they give the title and description to link previews in Slack, LinkedIn and messaging apps. Each detail view passes its own values:
class ArticleDetailView(DetailView):
model = Article
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["meta_title"] = self.object.title
context["meta_description"] = self.object.meta_description or self.object.summary
return contextA meta_description field on the model lets editors write the description in the Django admin, and the summary covers the pages where they haven’t.
The canonical URL tells search engines which address is the real one when the same page is reachable through several. A context processor sets it for every page:
# core/context_processors.py
def canonical_url(request):
# The address without its query string, so links with tracking parameters
# (?utm_source=…) count as the same page.
return {"canonical_url": request.build_absolute_uri(request.path)}Add "core.context_processors.canonical_url" to the context_processors in your TEMPLATES setting. When a page’s content depends on its query string, like page 2 of a list, set canonical_url in that view instead.
How to build a sitemap in Django
A sitemap is an XML file that lists the URLs you want indexed and when each one last changed. Django builds it for you with its sitemap framework.
- Add
django.contrib.sitemapsand the sites framework,django.contrib.sites, to your installed apps, and check thatTEMPLATEShas aDjangoTemplatesbackend withAPP_DIRSset toTrue. The framework renders its XML from templates.
INSTALLED_APPS = [
# ...
"django.contrib.sites",
"django.contrib.sitemaps",
]
SITE_ID = 1
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"APP_DIRS": True,
# ...
},
]- Write a
Sitemapclass for each kind of page:
# blog/sitemaps.py
from django.contrib.sitemaps import Sitemap
from django.urls import reverse
from .models import Article
class ArticleSitemap(Sitemap):
def items(self):
# Ordered, since the sitemap is paginated.
return Article.objects.filter(is_published=True).order_by("pk")
def lastmod(self, article):
return article.updated_at
class StaticViewSitemap(Sitemap):
def items(self):
return ["home", "about", "pricing"]
def location(self, item):
return reverse(item)items() returns what to list. For each item, location() returns its address, and calls the object’s get_absolute_url() when you don’t define it. lastmod() returns the date of its last real change. StaticViewSitemap covers the pages that have no model behind them, by their URL names.
- Route it in
urls.py:
from django.contrib.sitemaps.views import sitemap
from django.urls import path
from blog.sitemaps import ArticleSitemap, StaticViewSitemap
sitemaps = {"articles": ArticleSitemap, "static": StaticViewSitemap}
urlpatterns = [
# ...
path(
"sitemap.xml",
sitemap,
{"sitemaps": sitemaps},
name="django.contrib.sitemaps.views.sitemap",
),
]-
Run the migrations, then set your real domain on the
Siteobject in the Django admin: the sitemap builds its URLs from it, and a new project starts withexample.com. -
Open
/sitemap.xmlto check it, then submit it in Google Search Console and Bing Webmaster Tools.
How to serve robots.txt in Django
robots.txt tells crawlers which paths to skip and where your sitemap is. A template and a TemplateView are enough:
from django.urls import path
from django.views.generic import TemplateView
urlpatterns = [
# ...
path(
"robots.txt",
TemplateView.as_view(template_name="robots.txt", content_type="text/plain"),
),
]# templates/robots.txt
User-agent: *
Disallow: /search/
Sitemap: https://www.example.com/sitemap.xml/search/ stands for your internal search results, which add nothing to an index and can produce endless URLs. Don’t list private paths, like the admin: the file is public, so it would only advertise them, and Django’s admin already asks crawlers not to index it. robots.txt is only followed by well-behaved crawlers, so it is not access control. Protect private pages with authentication, and keep a public page out of search results with a noindex meta tag.
How to add structured data (JSON-LD) in Django
Structured data describes a page in the schema.org vocabulary: that it is an article, who wrote it, when it was published. Search engines use it to understand the page and, for some types, to show richer results. It goes in a <script type="application/ld+json"> tag, which a small template tag can write safely:
# core/templatetags/seo.py
import json
from django import template
from django.core.serializers.json import DjangoJSONEncoder
from django.utils.html import format_html
from django.utils.safestring import mark_safe
register = template.Library()
# The same escapes as Django's json_script filter, so no value can close the tag.
_JSON_ESCAPES = {ord("<"): "\\u003C", ord(">"): "\\u003E", ord("&"): "\\u0026"}
@register.simple_tag
def json_ld(data):
payload = json.dumps(data, cls=DjangoJSONEncoder).translate(_JSON_ESCAPES)
return format_html('<script type="application/ld+json">{}</script>', mark_safe(payload))The view builds the data, and DjangoJSONEncoder turns its dates into ISO 8601:
context["structured_data"] = {
"@context": "https://schema.org",
"@type": "Article",
"headline": self.object.title,
"datePublished": self.object.published_at,
"dateModified": self.object.updated_at,
"author": {"@type": "Person", "name": self.object.author.get_full_name()},
}{% load seo %}
{% json_ld structured_data %}Keep the structured data true to the page: describe only what readers can see on it. On larger sites, REVSYS builds its JSON-LD with Pydantic models instead, which checks each type’s fields and keeps the templates clean.
How to make your Django site visible in AI search
AEO (answer engine optimization) and GEO (generative engine optimization) are the names for getting your pages cited in AI answers. For Google, it is still SEO: AI Overviews and AI Mode take their links from the regular Search index, and Google says there are no extra requirements to appear in them. ChatGPT, Claude and Perplexity run their own search crawlers, so a few checks are worth adding to everything above.
Serve your content in the HTML
Not every AI crawler runs JavaScript, so text that only appears after scripts run may never be read. Django templates already render on the server. If parts of your pages come from a React front end, render them on the server or at build time; our post on Vite, React and server-side rendering compares the options.
Let AI search crawlers in, and decide on training separately
AI companies run one crawler to find pages to cite in their answers and another to collect training data for their models. You can allow one and block the other:
| Company | Crawler for AI search | Crawler for training |
|---|---|---|
| OpenAI | OAI-SearchBot |
GPTBot |
| Anthropic | Claude-SearchBot |
ClaudeBot |
Googlebot (Search, AI Overviews, AI Mode) |
Google-Extended (Gemini) |
|
| Perplexity | PerplexityBot |
None (PerplexityBot isn’t used for training) |
To stay in AI search while opting out of training, block only the training crawlers:
# templates/robots.txt
User-agent: *
Disallow: /search/
User-agent: GPTBot
User-agent: ClaudeBot
User-agent: Google-Extended
Disallow: /
Sitemap: https://www.example.com/sitemap.xmlBlocking Google-Extended doesn’t affect Google Search or AI Overviews. Then check the layer in front of Django: some CDNs and firewalls can block AI crawlers before they reach your app, and Cloudflare, for example, has a setting for it. Make sure it lets the search crawlers through.
Write pages that answer questions
AI answers are built from passages that answer a question clearly. Open each page, and each section, with a direct answer in a sentence or two, then give the detail. Phrase headings as the questions your readers ask, and be specific: versions, numbers, steps. Experience you can show beats restating what other pages already say, for search engines and AI alike.
Skip llms.txt unless you have a reason
llms.txt is a proposed file that gives language models a Markdown map of a site. It is a proposal, not a standard, and Google says you don’t need new machine-readable or AI text files to appear in its AI features. For a typical Django app, server-rendered pages and an accurate sitemap do more. If you want one anyway, django-llms-txt builds it from your models.
Measure what AI search sends you
Google counts AI Overviews and AI Mode in Search Console’s Performance report, under the “Web” search type. Bing’s index feeds Microsoft Copilot, so Bing Webmaster Tools is worth setting up too. In your analytics, watch referrals from chatgpt.com, perplexity.ai and claude.ai.
Django SEO in the age of AI
AI changes how SEO work gets done in a Django project, not only where your pages show up. Coding agents now write a good share of new views and templates, and language models can draft the metadata nobody had time to write. Both help, as long as the rules stay in your hands.
Write your SEO rules where coding agents read them
Coding agents read an instructions file at the root of the repository before they change anything: AGENTS.md for Codex and Cursor, CLAUDE.md for Claude Code. Put your SEO rules there, and every page an agent adds follows them:
## SEO
- Every public view sets `meta_title` and `meta_description` in its context.
- Titles: unique, about 60 characters, the most important words first.
- Descriptions: one or two sentences, at most 160 characters.
- A model with a public detail page gets a `Sitemap` class in its app's `sitemaps.py`.
- Never block `OAI-SearchBot`, `Claude-SearchBot` or `PerplexityBot` in `robots.txt`.We do the same in the repository of this website: its instructions tell the agents that every page needs a unique title of at most 70 characters and a description. For how we teach agents Django’s conventions in general, see Teaching AI agents to write Django like senior developers.
Draft meta descriptions with a language model, then review them
Most Django sites have hundreds of pages without a description: products, articles, profiles. A language model can draft them from each page’s content. Google’s position is that appropriate use of AI is not against its guidelines; what it penalizes is content generated primarily to manipulate rankings. Describing pages that already exist is fine. Generating thousands of new pages to rank for every variation of a query is not.
Wagtail sites have this built in: Wagtail AI suggests titles and descriptions in the editor, and Tim Kamanin shows how to generate them for a whole site at once. In plain Django, a management command does it. This one fills only empty fields, so running it twice changes nothing, and --dry-run prints the drafts without saving them:
# blog/management/commands/draft_meta_descriptions.py
from django.core.management.base import BaseCommand
from blog.models import Article
from blog.seo import draft_meta_description # calls the language model of your choice
class Command(BaseCommand):
help = "Draft meta descriptions for published articles that have none."
def add_arguments(self, parser):
parser.add_argument("--dry-run", action="store_true", help="Print the drafts without saving them.")
def handle(self, *args, dry_run=False, **options):
for article in Article.objects.filter(is_published=True, meta_description=""):
draft = draft_meta_description(title=article.title, body=article.body)
if len(draft) > 160:
self.stdout.write(f"{article.pk}: skipped, the draft has {len(draft)} characters")
continue
self.stdout.write(f"{article.pk}: {draft}")
if not dry_run:
article.meta_description = draft
article.save(update_fields=["meta_description"])Read the dry run before you save: models get facts wrong, and a description is a promise about the page. Send the model only public page content, never user data. Editors can still rewrite any description in the Django admin.
Test the tags, whoever writes the code
When agents and people both add pages, a test keeps the basics from slipping. This one reads your sitemap and checks every page on it:
# core/tests/test_seo.py
import re
from urllib.parse import urlparse
from xml.etree import ElementTree
from django.test import TestCase
SITEMAP_NS = {"sm": "http://www.sitemaps.org/schemas/sitemap/0.9"}
class SeoTagsTests(TestCase):
@classmethod
def setUpTestData(cls):
... # Create a few published objects of each kind the sitemap lists.
def test_sitemap_pages_have_a_unique_title_and_description(self):
sitemap = ElementTree.fromstring(self.client.get("/sitemap.xml").content)
titles, descriptions = {}, {}
for loc in sitemap.findall("sm:url/sm:loc", SITEMAP_NS):
path = urlparse(loc.text).path
with self.subTest(path=path):
html = self.client.get(path).content.decode()
title = re.search(r"<title>(.*?)</title>", html, re.S).group(1).strip()
match = re.search(r'<meta name="description" content="([^"]*)"', html)
self.assertTrue(match and match.group(1), "No meta description")
description = match.group(1)
self.assertNotIn(title, titles, f"Same title as {titles.get(title)}")
self.assertNotIn(description, descriptions, f"Same description as {descriptions.get(description)}")
self.assertLessEqual(len(description), 160)
titles[title], descriptions[description] = path, pathIt catches a missing description or a repeated title in CI, before a crawler does. Adam Johnson’s guide to robots.txt in Django tests /robots.txt the same way.
Django SEO checklist
- Every page has a unique
<title>, with the most important words first - Every page that matters has its own meta description
- Every page declares a canonical URL, with
httpsbehind your proxy - Open Graph tags give link previews a title and a description
/sitemap.xmllists the pages to index, with accuratelastmoddates- The sitemap is submitted in Google Search Console and Bing Webmaster Tools
/robots.txtpoints to the sitemap and blocks only what it should- Structured data in JSON-LD matches what the page shows
- The main content is in the HTML the server sends
- AI search crawlers are allowed in
robots.txtand by your CDN - Your SEO rules are in the instructions file your coding agents read
- A test checks that every page in the sitemap has a unique title and description
Frequently asked questions
Does Django have built-in SEO features?
Django ships a sitemap framework (django.contrib.sitemaps) and renders HTML on the server, which crawlers read easily. Titles, meta descriptions, canonical URLs and structured data are up to your templates and views, and the patterns in this guide cover them without third-party packages.
Does the meta description affect rankings?
No. Google doesn’t use it as a ranking signal, but it often shows it as the snippet under your title, so a clear description gets more clicks. Google may still rewrite the snippet to match a query.
Does a small Django site need a sitemap?
Not strictly. Google says a site of about 500 pages or fewer, well linked internally, may not need one. In Django it takes a few lines, though, and accurate lastmod dates help crawlers find your changes sooner.
What is AEO, and is it different from SEO?
AEO (answer engine optimization) is the work of getting your pages cited in AI-generated answers. For Google’s AI Overviews and AI Mode it is the same as SEO, with no extra requirements. For ChatGPT, Claude and Perplexity, also make sure their search crawlers can reach your pages.
How do I keep my site out of AI training without leaving AI search?
Block the training crawlers (GPTBot, ClaudeBot, Google-Extended) in robots.txt, and keep the search crawlers (OAI-SearchBot, Claude-SearchBot, PerplexityBot) allowed. Blocking Google-Extended doesn’t affect Google Search or AI Overviews.
Can I use AI to write meta descriptions for my Django site?
Yes. Google says appropriate use of AI is not against its guidelines; what it penalizes is content generated primarily to manipulate rankings. Draft descriptions for pages that already exist, review them before they go live, and keep them editable in the admin.
Does my Django site need an llms.txt file?
No. It is a proposal, not a standard, and Google says no AI text file is needed to appear in its AI features. Server-rendered pages, an accurate sitemap and clear robots.txt rules matter more.
References
- Django documentation, The sitemap framework. https://docs.djangoproject.com/en/stable/ref/contrib/sitemaps/
- Google Search Central, SEO Starter Guide. https://developers.google.com/search/docs/fundamentals/seo-starter-guide
- Google Search Central, Build and submit a sitemap. https://developers.google.com/search/docs/crawling-indexing/sitemaps/build-sitemap
- Google Search Central, Introduction to structured data markup in Google Search. https://developers.google.com/search/docs/appearance/structured-data/intro-structured-data
- Google Search Central, AI features and your website. https://developers.google.com/search/docs/appearance/ai-features
- Google Search Central, Optimizing your website for generative AI features on Google Search. https://developers.google.com/search/docs/fundamentals/ai-optimization-guide
- Google Search Central, Google’s common crawlers (Google-Extended). https://developers.google.com/search/docs/crawling-indexing/google-common-crawlers
- OpenAI, Overview of OpenAI crawlers. https://platform.openai.com/docs/bots
- Anthropic, Does Anthropic crawl data from the web, and how can site owners block the crawler? https://support.claude.com/en/articles/8896518-does-anthropic-crawl-data-from-the-web-and-how-can-site-owners-block-the-crawler
- Perplexity, Perplexity crawlers. https://docs.perplexity.ai/docs/resources/perplexity-crawlers
- The /llms.txt file proposal. https://llmstxt.org/
- Google Search Central Blog, Google Search’s guidance about AI-generated content, February 2023. https://developers.google.com/search/blog/2023/02/google-search-and-ai-content
- Google Search Central, Spam policies for Google web search (scaled content abuse). https://developers.google.com/search/docs/essentials/spam-policies#scaled-content
- Velda Kiara, Boosting SEO with Django Ninja, Pydantic, and JSON-LD, REVSYS, August 2025. https://www.revsys.com/tidbits/boosting-seo-with-django-ninja-pydantic-and-json-ld/
- Tim Kamanin, How to generate SEO descriptions for your entire Wagtail site at once, April 2026. https://timonweb.com/wagtail/how-to-generate-seo-descriptions-for-your-entire-wagtail-site-at-once/
- Adam Johnson, How to add a robots.txt to your Django site. https://adamj.eu/tech/2020/02/10/robots-txt/
- Wagtail AI on PyPI. https://pypi.org/project/wagtail-ai/
- django-llms-txt on PyPI. https://pypi.org/project/django-llms-txt/
- django-llms-txt — Generate llms.txt files for Django sites, Django Forum, March 2026. https://forum.djangoproject.com/t/django-llms-txt-generate-llms-txt-files-for-django-sites/44500
- DjangoTricks, About dynamic website content and AI chatbots. https://www.djangotricks.com/tricks/3XGaSZ6kscS6





