Adding a Blog to a Django Marketing Site: Models, Categories and Feeds

Why a marketing site benefits from a Django blog

A marketing site often begins with a small set of pages: a home page, product or service descriptions, contact information and legal notices. Over time, visitors need more detailed explanations, product updates, technical guidance and answers to recurring questions. A blog provides a structured place for that material without forcing every article into a static page model.

In Django, a blog can remain focused while sharing the same project, templates, authentication system and deployment process as the rest of the site. The main design challenge is not creating a database table. It is defining a content model that supports editorial work, predictable URLs, search engine indexing, accessible navigation and future changes.

This guide presents a practical architecture for a blog application. It covers post and category models, publication states, slugs, relationships, pagination, RSS and Atom-style feeds, administrative workflows, testing and security. The examples are intentionally adaptable. A marketing site may need fewer fields than a publication, while a larger editorial operation may require authors, tags, scheduled publishing and revision management.

Plan the content model before writing views

Start by listing the content a reader must see and the decisions an editor must make. A typical blog post needs a title, a URL identifier, an introduction, body content, a publication status, a publication date and an update date. It may also need an image, an excerpt, an author, categories and metadata for search engines.

Separate fields into three groups:

This separation helps prevent a common design problem: using a field intended for display as the source of publication logic. For example, a non-empty publication date does not necessarily mean that an editor wants an article to be visible. A dedicated status field makes that decision explicit.

Before migrating the first version, decide whether the body will contain trusted HTML, sanitized rich text or structured content. Django templates escape variable output by default, which is an important protection against cross-site scripting. Marking user-submitted content as safe without sanitizing it can remove that protection. A blog editor used only by trusted staff still benefits from a clear policy and controlled HTML output.

Create a Post model with explicit publication rules

A robust post model can use a status choice such as draft, published and archived. The exact names are less important than making the workflow visible in the database and administration interface. A post should be considered public only when its status is published and its publication date is not in the future.

A representative model design contains these fields:

Use a timezone-aware datetime field for publication. Django projects should have timezone support configured, and the application should compare publication dates using aware datetimes. Mixing naive and aware datetimes can cause errors or make scheduled content appear at the wrong time.

The public query should express the complete rule rather than relying on a template condition. In conceptual terms, the queryset should filter for status equal to published and published_at less than or equal to the current time. Place this logic in a custom queryset or manager such as a public posts method. Reusing one definition across archive pages, category pages, feeds and sitemaps reduces the risk of exposing drafts through a secondary endpoint.

For ordering, use published_at in descending order and add a stable secondary field if two posts can have the same timestamp. A deterministic ordering is useful for pagination because records should not move unpredictably between pages when a database returns tied values.

Design categories for navigation and maintenance

Categories describe broad editorial areas such as security, web development, infrastructure or productivity. They should not be created for every keyword. A category page is a public landing page that needs enough relevant content to justify its existence, so a short, stable vocabulary usually serves readers better than a large collection of narrow labels.

A category model commonly includes a name, a unique slug, an optional description and an active flag. The description can explain the topic on the category page and provide useful context for search engines and readers. A unique slug prevents two categories from competing for the same URL.

Use a many-to-many relationship when a post can belong to more than one category. This reflects normal editorial practice: an article about securing a Django deployment may belong to both web development and security. Use a foreign key instead when every post must have exactly one category and the hierarchy is central to the site. The choice should reflect the reader's navigation needs rather than database convenience.

Category URLs can follow a stable pattern such as category followed by the category slug, while post URLs can use blog followed by the post slug. Adding a date to a URL can help identify old content, but it also makes URL changes more likely when an article is republished or corrected. A short slug is often more durable for evergreen material.

When a category or post title changes, do not silently break existing URLs. Options include preserving the original slug, recording redirect history in a separate model or managing redirects through the application. If redirects are added, test both the old and new paths and avoid redirect chains.

Configure the Django admin for editorial work

The Django admin should make the safe action the visible action. Register the post and category models, then configure list displays for title, status, publication date and update date. Add filters for status and categories, and make the search fields include title and slug. These choices reduce the need to open each record during routine maintenance.

Useful admin features include:

Slug generation requires editorial care. Automatic slugification can remove accents, collapse punctuation and produce a value that does not communicate the intended URL. Generate a first draft, then let an editor review it before publication. A unique database constraint should remain in place even when the admin validates the field, because concurrent requests can bypass an application-level check.

Deletion also deserves a policy. Deleting a published post can create broken links and remove content from feeds. An archived status or a soft-delete field provides a safer first step. Permanent deletion should be reserved for content that must be removed and should be accompanied by a decision about redirects, references and backups.

Build views that expose only public content

The blog usually needs an index view, a detail view, a category archive and possibly an author archive. Each view should use the shared public queryset. The detail view should look up a post by slug only after applying the public filter. Filtering after retrieving the object can accidentally reveal the existence of drafts through different response behavior or administrative assumptions.

Use pagination for the index and archive views. The number of posts per page should be chosen according to the design, image weight and reading pattern rather than treated as a universal rule. Display the current page, total navigation options and useful next and previous links. Ensure that pagination links remain accessible to keyboard and screen-reader users.

Optimize database access deliberately. A post list that displays an author and categories may cause repeated queries if related data is loaded one record at a time. Use select_related for a single-valued relationship such as an author, and prefetch_related for many-to-many categories. Confirm the result with query inspection or tests rather than applying optimization without measuring the page's actual access pattern.

For detail pages, return a clear not-found response for unknown, unpublished or future posts. Avoid exposing different error messages for a missing post and a private post unless an authenticated editorial interface needs that distinction. Public behavior should not disclose unpublished titles or publication schedules.

Choose templates and URLs that support SEO and accessibility

Keep URL patterns readable and predictable. A named URL for the post detail view allows templates, feeds and redirects to reverse the route without hard-coded paths. A canonical URL should use the preferred scheme, host and path configured for the deployment. Incorrect host configuration can produce duplicate or misleading canonical addresses, so treat it as an infrastructure setting rather than a template guess.

Each detail page should provide:

Do not use the excerpt as a substitute for the first paragraph if the two serve different purposes. The excerpt works in listings, social previews and feeds, while the article introduction should provide context on the detail page. If an excerpt is optional, create a fallback in the model or presentation layer and test it for length and punctuation.

Rich text content needs a controlled rendering path. Store trusted editor output in a format supported by the chosen editor, sanitize HTML when content can come from untrusted users and avoid applying a safe-output filter to raw request data. Security is a property of the entire input and rendering workflow, not a setting added at the final template line.

Add RSS or Atom feeds from the public queryset

A feed allows readers and compatible applications to detect new posts without repeatedly checking the archive. Django provides feed framework components that can generate RSS or Atom-style output from a view and a feed class. The feed should be treated as another public delivery channel, not as a shortcut around the blog's visibility rules.

For a feed implementation, define:

  1. A feed title that identifies the publication area.
  2. A feed description that explains what readers will receive.
  3. A link to the blog index.
  4. An item queryset containing published posts only.
  5. An item title, canonical URL, publication date and summary.
  6. Optional full content, according to the site's editorial and security policy.

Order feed items by publication date, newest first. Use the same timezone-aware publication condition as the archive views. If a post is edited, decide whether the feed should expose an updated date or only the original publication date. Either choice can be valid, but the behavior should be consistent.

Feed content can create an unexpected data exposure if it includes drafts, internal notes, hidden image paths or unsanitized HTML. Test the generated XML with content containing accented characters, quotation marks, ampersands and line breaks. XML escaping is handled by the framework when values are passed through the expected feed APIs, but custom feed construction can reintroduce encoding errors.

Category-specific feeds can be useful when categories represent durable subjects. They should reuse the category-filtered public queryset and return a not-found response for an unknown category. Avoid creating feeds for temporary filters that have no stable editorial meaning.

Compare common blog architecture choices

DecisionOption oneOption twoPractical consideration
Post statusBoolean published flagExplicit status choicesA status field supports drafts, archived content and future workflow changes more clearly.
Topic structureOne category per postMany categories per postChoose one category for strict hierarchy, or many categories for cross-topic discovery.
Body storageTrusted HTMLStructured or sanitized contentTrusted HTML is convenient for editors, while sanitization reduces risk when input sources vary.
URL designDate-based pathStable slug pathDate paths provide chronology, while stable slugs reduce URL changes for evergreen articles.
Removal policyPermanent deletionArchive or redirectArchiving protects links and editorial history when a post should no longer appear in normal listings.

None of these choices is universally correct. The appropriate design depends on how many editors work on the project, whether content is evergreen, whether URLs are already public and whether the body includes user-generated material. Record the decision in project documentation so later changes do not rely on assumptions hidden in code.

Secure the publishing workflow

A public blog expands the site's attack surface through forms, media uploads, authentication and rendered content. Keep the editorial interface behind Django authentication and permissions. Protect state-changing forms with Django's CSRF mechanism, use secure session and cookie settings in production and enforce HTTPS at the deployment layer.

Uploads require particular attention. Restrict accepted file types, validate content rather than trusting the filename, impose sensible size limits and store media outside locations where uploaded files can execute as server-side code. Image processing can also consume significant resources, so image dimensions and processing limits should be considered during upload validation.

Use the project user model through the configured user-model setting rather than importing Django's default user class directly in reusable application code. For the author relationship, decide what happens when an author account is deactivated or removed. A protected relationship, a nullable field or a separate author profile can preserve the public byline without keeping an inactive account accessible.

Keep secrets, database credentials and deployment-specific host values outside source code. Apply migrations in a controlled deployment process, back up the database and media files, and test restoration. A backup that has never been restored in a test environment has not demonstrated that it can recover the blog.

Test publication, feeds and URL behavior

Blog tests should cover business rules as well as page rendering. A useful test suite verifies that a draft is absent from the index, a future post is absent before its publication time and a published post appears after that time. It should also verify that a category archive cannot expose an unpublished post assigned to that category.

Include tests for:

Use a controllable clock or explicit timestamps in tests rather than depending on the machine's current time. This makes scheduled publication rules deterministic. When changing a public slug, test the redirect policy and verify that the canonical URL points to the new address.

Review the generated HTML and feed output as part of release checks. Automated tests can confirm status codes and fields, but a rendered review can reveal duplicate headings, missing alt text, invalid navigation or an excerpt that exposes formatting characters.

A practical implementation sequence

A staged implementation reduces the risk of building presentation features before the publishing rules are reliable.

  1. Create the blog application and define the post and category models.
  2. Add explicit status and timezone-aware publication fields.
  3. Run migrations in development and create representative test records.
  4. Configure the admin with search, filters, fieldsets and publishing permissions.
  5. Implement a shared public queryset and use it in every public endpoint.
  6. Add index, detail and category views with named URL patterns.
  7. Build templates with semantic headings, accessible navigation and metadata.
  8. Add pagination and database loading optimizations after checking actual queries.
  9. Implement the feed from the same public queryset as the archive.
  10. Add automated tests for visibility, slugs, permissions, pagination and XML output.
  11. Review backups, media handling, HTTPS, host configuration and deployment settings.

Build the first version with the smallest model that supports real editorial needs, but do not omit publication safety. A clean status rule, protected admin and tested public queryset are more valuable than a large set of optional fields. Later additions such as tags, related posts, scheduled tasks or revision history are easier when the core boundaries are clear.

FAQ about Django marketing site blogs

Should the blog use a separate Django project?

Usually, a blog that shares branding, users, deployment and navigation with a marketing site fits naturally into the existing project as a dedicated application. A separate project may be justified when the blog has independent ownership, infrastructure or release requirements.

Are categories and tags the same thing?

No. Categories usually represent a small, stable navigation structure. Tags are more granular descriptors and can multiply quickly. Start with categories when readers need broad topic navigation, then add tags only when a clear search or discovery use case exists.

How can scheduled posts be published?

Store a future publication datetime and make public querysets require that the time has arrived. The site can show the post automatically when a request occurs after that time. A background task may be useful for notifications or cache invalidation, but it should not replace the visibility condition in the queryset.

Should a feed contain full articles?

Either summaries or full content can be appropriate. Summaries direct readers to the site, while full content provides a complete reading experience in feed applications. Decide according to editorial goals and ensure that the selected representation is sanitized, correctly escaped and consistent.

What is the most important model decision?

The most important decision is to make public visibility explicit and reusable. When every archive, detail page and feed applies the same published-and-not-in-the-future rule, the rest of the blog architecture becomes easier to maintain and test.

Learn more about this: