惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Fortinet All Blogs
aimingoo的专栏
aimingoo的专栏
人人都是产品经理
人人都是产品经理
G
GRAHAM CLULEY
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
L
LangChain Blog
AWS News Blog
AWS News Blog
V
Vulnerabilities – Threatpost
博客园 - 司徒正美
Last Week in AI
Last Week in AI
P
Privacy International News Feed
C
CERT Recently Published Vulnerability Notes
Simon Willison's Weblog
Simon Willison's Weblog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
S
Schneier on Security
Y
Y Combinator Blog
月光博客
月光博客
博客园 - Franky
T
Threatpost
Security Latest
Security Latest
C
Cybersecurity and Infrastructure Security Agency CISA
博客园 - 【当耐特】
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
大猫的无限游戏
大猫的无限游戏
A
Arctic Wolf
T
The Exploit Database - CXSecurity.com
A
About on SuperTechFans
I
Intezer
C
CXSECURITY Database RSS Feed - CXSecurity.com
C
Cisco Blogs
S
Securelist
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
美团技术团队
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Security Blog
Microsoft Security Blog
Know Your Adversary
Know Your Adversary
IT之家
IT之家
D
Docker
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
NISL@THU
NISL@THU
博客园 - 三生石上(FineUI控件)
L
Lohrmann on Cybersecurity
小众软件
小众软件
PCI Perspectives
PCI Perspectives
N
News and Events Feed by Topic
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Google DeepMind News
Google DeepMind News
爱范儿
爱范儿
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Engineering at Meta
Engineering at Meta

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
The Django Singleton Model: How to Manage Page Headers Without a CMS
Vicente G. R · 2026-05-27 · via DEV Community

I've always wondered how to handle those single-record things in a CMS-driven site. You know what I mean — the home page hero, the blog page header, the pricing section banner. They're not a list. There's no "add another." There's exactly one of them, and a non-technical client or even your future self needs to be able to edit them from an admin panel without touching code.

For the longest time I either hardcoded the content and lived with the guilt, or reached for something heavyweight like Wagtail. But neither felt right for a lean Django + React setup.

The actual answer turned out to be embarrassingly simple: the singleton model pattern.


The Problem

Django models are designed to store collections of things. But some things aren't collections — they're configuration. A home page header isn't a list of headers. It's the header. One row. Forever.

If you leave it as a normal model, three bad things can happen:

  1. Someone adds a second row in the admin and breaks the frontend.
  2. You delete the only row and the API 404s until someone notices.
  3. You have to write HomePageHeader.objects.first() everywhere and pray row 1 never becomes row 5.

The singleton pattern closes all three gaps.


The Implementation

The core trick lives in the model's save() method: force pk=1 before every write.

class HomePageHeader(models.Model):
    AVAILABILITY_CHOICES = [
        ("open_to_work", "Open to Work"),
        ("currently_booked", "Currently Booked"),
        ("freelance_only", "Freelance Only"),
    ]

    availability_status = models.CharField(
        max_length=20,
        choices=AVAILABILITY_CHOICES,
        default="open_to_work",
    )
    hero_image = models.ImageField(upload_to="hero/", blank=True, null=True)
    heading_line1 = models.CharField(max_length=100, default="BUILDING")
    heading_highlight = models.CharField(max_length=100, default="DIGITAL")
    heading_line2 = models.CharField(max_length=200, default="PRODUCTS THAT")
    heading_accent = models.CharField(max_length=100, default="SLAP.")
    subtitle = models.TextField(
        default="I'm Vicente Reyes. Freelance Full-Stack Developer, Shopify & WordPress Expert, & Musician.",
    )
    primary_button_label = models.CharField(max_length=100, default="View Projects")
    primary_button_url = models.CharField(max_length=200, default="#projects")
    secondary_button_label = models.CharField(max_length=100, default="Book a Call")
    secondary_button_url = models.URLField(
        default="https://calendly.com/vicentereyes/30min",
    )

    class Meta:
        verbose_name = "Home Page Header"
        verbose_name_plural = "Home Page Header"

    def __str__(self):
        return "Home Page Header"

    def save(self, *args, **kwargs):
        self.pk = 1
        super().save(*args, **kwargs)

Enter fullscreen mode Exit fullscreen mode

That's the whole trick. By pinning self.pk = 1 before calling super().save(), Django will always INSERT OR REPLACE (or UPDATE) the same row. A second save never creates a second record — it just updates the first one.

The verbose_name_plural matching verbose_name is a small cosmetic touch: Django's admin sidebar normally pluralizes the label, so "Home Page Headers" would appear. Keeping both the same gives you "Home Page Header" in the sidebar — which correctly implies there's only one.


Locking Down the Admin

The model alone prevents duplicates at the database level, but the admin still shows an "Add" button. Lock it out explicitly:

@admin.register(HomePageHeader)
class HomePageHeaderAdmin(admin.ModelAdmin):
    list_display = ("availability_status", "heading_line1", "heading_highlight")

    def has_add_permission(self, request):
        return not HomePageHeader.objects.exists()

    def has_delete_permission(self, request, obj=None):
        return False

Enter fullscreen mode Exit fullscreen mode

has_add_permission returns True only when the table is empty — meaning the first time the row is created, the "Add" button appears. Once it exists, the button disappears. has_delete_permission always returns False, making the row permanent from the admin's perspective.

The same pattern applies to every page header in the project:

@admin.register(BlogPageHeader)
class BlogPageHeaderAdmin(admin.ModelAdmin):
    list_display = ("badge_text", "heading_line1", "heading_highlight")

    def has_add_permission(self, request):
        return not BlogPageHeader.objects.exists()

    def has_delete_permission(self, request, obj=None):
        return False


@admin.register(ServicesPageHeader)
class ServicesPageHeaderAdmin(admin.ModelAdmin):
    list_display = ("heading", "subheading", "cta_heading")

    def has_add_permission(self, request):
        return not ServicesPageHeader.objects.exists()

    def has_delete_permission(self, request, obj=None):
        return False

Enter fullscreen mode Exit fullscreen mode

Each page section gets its own model, its own admin class, and its own locked-down row.


The View

With the model and admin locked down, the view is a one-liner:

class HomePageHeaderView(APIView):
    def get(self, request):
        obj, _ = HomePageHeader.objects.get_or_create(pk=1)
        return Response(
            HomePageHeaderSerializer(obj, context={"request": request}).data,
        )

Enter fullscreen mode Exit fullscreen mode

get_or_create(pk=1) is the runtime complement to the model-level pk=1 pin. If the row doesn't exist yet (fresh database, new environment), it creates one with all the field defaults. If it does exist, it returns it. The view never returns a 404 for a missing singleton — it self-heals.


The Serializer

Nothing special here, but the HomePageHeader has one field worth noting — availability_status uses Django choices, and the serializer surfaces both the raw value and the human-readable label:

class HomePageHeaderSerializer(serializers.ModelSerializer):
    availability_display = serializers.CharField(
        source="get_availability_status_display",
        read_only=True,
    )
    hero_image_url = serializers.SerializerMethodField()

    class Meta:
        model = HomePageHeader
        fields = [
            "availability_status",
            "availability_display",
            "hero_image_url",
            "heading_line1",
            "heading_highlight",
            "heading_line2",
            "heading_accent",
            "subtitle",
            "primary_button_label",
            "primary_button_url",
            "secondary_button_label",
            "secondary_button_url",
        ]

    def get_hero_image_url(self, obj):
        if not obj.hero_image:
            return None
        request = self.context.get("request")
        if request:
            return request.build_absolute_uri(obj.hero_image.url)
        return obj.hero_image.url

Enter fullscreen mode Exit fullscreen mode

get_availability_status_display is a Django built-in that returns the human-readable choice label — so the frontend gets "Open to Work" rather than "open_to_work". The hero_image_url method builds an absolute URL so the React frontend gets a fully qualified image path regardless of where the API is hosted.


The Full Flow

The full stack for any singleton page header looks like this:

  1. Model — fields with sensible defaults, save() pins pk=1
  2. Migration — standard makemigrations / migrate
  3. Adminhas_add_permission blocks duplicates, has_delete_permission blocks deletion
  4. Viewget_or_create(pk=1) for self-healing on fresh environments
  5. Serializer — flat output, no nesting needed
  6. Router — one URL, no {id} segment needed

The React side just does GET /api/home-header/ and maps the flat JSON to component props. No special handling, no conditional rendering for missing data.


When to Use This (and When Not To)

This pattern is ideal when:

  • The content is truly a one-of-a-kind configuration for a specific page or section
  • You want non-technical users to edit it from Django Admin
  • You don't want to pull in a full CMS dependency

Skip it when:

  • The content might ever need more than one instance (use a regular model)
  • You have dozens of these (consider django-solo, which packages this pattern as a reusable base class and adds caching)
  • The content changes rarely and has no images (environment variables or a settings dict is simpler)

Takeaway

The singleton model isn't exotic — it's just a model with one enforced row. Three lines of code in save() and two overrides in ModelAdmin are all it takes to turn a generic Django model into a safely editable, self-healing, single-record configuration object.

I spent way too long hardcoding hero text before I figured this out. Now every page section that needs admin-editable content but only ever has one instance gets this treatment by default.