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

推荐订阅源

I
InfoQ
S
SegmentFault 最新的问题
N
Netflix TechBlog - Medium
B
Blog
Jina AI
Jina AI
人人都是产品经理
人人都是产品经理
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园 - 聂微东
Last Week in AI
Last Week in AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
V
V2EX
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
大猫的无限游戏
大猫的无限游戏
U
Unit 42
J
Java Code Geeks
IT之家
IT之家
aimingoo的专栏
aimingoo的专栏
博客园 - 叶小钗
T
The Blog of Author Tim Ferriss
博客园 - 【当耐特】
Hugging Face - Blog
Hugging Face - Blog
WordPress大学
WordPress大学
腾讯CDC

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
I built a Django admin UI with no SPA. htmx bit me where ...
ひとし 田畑 · 2026-06-17 · via DEV Community

ひとし 田畑

I built the whole admin UI for a self-hosted tool with Django + htmx + Tailwind
and zero JavaScript framework. No React, no build step, no client-side router.
Server renders HTML, htmx swaps fragments into the page, Tailwind makes it not look
like 2009. For a small ops tool maintained by one person, it's a fantastic stack.

But htmx changes one assumption you've quietly relied on for years: a redirect is
no longer a redirect.
That assumption broke in the least obvious place — session
expiry — and the bug looked absurd before it made sense.

The setup: views return fragments, not pages

In an htmx app, most of your views don't render a full page. They render a
partial and htmx drops it into a target element:

<button hx-get="/systems/new/"
        hx-target="#main-content"
        hx-swap="innerHTML">
  New system
</button>

The view just returns the fragment:

@require_GET
@htmx_login_required
def create_system_form_view(request):
    return render(request, '_system_create_form.html')

Clean. The server sends a chunk of HTML, htmx puts it where you said. This is the
whole model and it's lovely — until auth gets involved.

The bug: a login page inside a 300px panel

Here's what happens with a plain @login_required on an htmx view. The user's
session expires. They click a button that fires hx-get into some small target
div. Django's @login_required does what it always does: returns a 302 redirect
to /login/.

And htmx, being a good HTTP citizen, follows the redirectXMLHttpRequest
transparently follows 302s. It fetches /login/, gets back the full login page
HTML, and faithfully swaps that entire page into your 300px target div.

So the user clicks "New system" and watches a complete login form — header, logo,
footer and all — get crammed into a tiny panel in the corner of the screen. The
page around it is still "logged in." It looks broken because it is the wrong
mental model: htmx doesn't know a 302-to-login means "leave this page." To the
swap, it's just more HTML.

The fix: tell htmx to redirect the browser, not the fragment

htmx reads special response headers. The one that matters here is HX-Redirect:
when htmx sees it, it does a real, top-level window.location redirect instead of
swapping the body. So the fix is a decorator that branches on whether the request
came from htmx:

def htmx_login_required(view_fn):
    @wraps(view_fn)
    def wrapper(request, *args, **kwargs):
        if not request.user.is_authenticated:
            if request.headers.get('HX-Request'):
                response = HttpResponse(status=204)
                response['HX-Redirect'] = '/login/'
                return response
            return redirect('/login/')
        return view_fn(request, *args, **kwargs)
    return wrapper

Two paths, on purpose:

  • htmx request (HX-Request header is present): return 204 No Content with an HX-Redirect header. htmx navigates the whole browser to /login/. No fragment gets swapped — the 204 has no body to swap anyway.
  • Normal request (someone hit the URL directly): fall back to a regular 302 redirect, exactly like @login_required.

HX-Request is the tell. htmx sets that header on every request it makes, so it's
how the server knows whether it's talking to a fragment swap or a real page load,
and can answer in the dialect the caller actually speaks.

The second half of the lesson: the server can steer the swap

Once you accept that htmx requests carry headers and respond to them, a whole
class of "I need JavaScript for this" problems dissolves. My favorite example is
the tfstate upload modal. The upload form lives in a modal and posts into itself.
But on success I don't want to update the modal — I want to replace the main
content with the new asset list and close the modal.
Three different things, from
the server, with no JS:

response = render(request, '_asset_list.html', context)
response['HX-Retarget'] = '#main-content'   # swap somewhere else, not the form
response['HX-Reswap']   = 'innerHTML'        # ...replacing its contents
response['HX-Trigger']  = 'closeUploadModal' # fire a client-side event
return response

  • HX-Retarget overrides the hx-target the button declared — the response lands in #main-content instead of back in the modal.
  • HX-Reswap overrides the swap strategy to match.
  • HX-Trigger fires a named event in the browser; a tiny listener closes the modal when it hears closeUploadModal.

The button said "put the answer here." The server said "actually, put it there,
and also close that modal." The element that started the request doesn't have to be
the element that gets updated. That inversion — the server controls the UI from
the response, not just the body
— is the part of htmx that took me longest to
internalize and paid off the most.

Takeaways

  • With htmx, a 302 is followed transparently and the redirected page gets swapped into your target. A login redirect on an expired session means the login page appears inside whatever tiny div triggered the request.
  • Branch on the HX-Request header: for htmx callers return 204 + HX-Redirect so the browser navigates; for direct hits, fall back to a normal 302.
  • Lean into server-driven control: HX-Retarget, HX-Reswap, and HX-Trigger let the response decide where the swap goes and fire client events — no SPA, barely any JavaScript.

This is the admin UI of a self-hosted tool I build to track AWS assets and detect
Terraform drift — Django + htmx + Tailwind, no SPA. It's open source (MIT), one
docker compose up: syncvey.com.
If you've gone the htmx-instead-of-React route, what was the gotcha that made you
finally read the response-header docs?