r/django

▲ 13 r/django

Detect N+1 problems with nplus1 to improve Django performance

Hi everyone, I want to introduce an enhanced version of nplusone called nplus1.

The original nplusone has been unmaintained for around 8 years. I used it for a while and although it was helpful in many cases, I ran into false positives that forced me to whitelist a lot of things, and I also wanted nicer trace messages (inspired by django-zeal). So I decided to maintain and improve it.

A few things that are new or fixed compared to the original:

• Python 3.11+, full type hints (mypy strict + pyright strict)
• Django 4.2 to 5.2 support, SQLAlchemy 2.0 support
• No more false positives on nullable foreign keys (they are valid optimizations and now skipped)
• Proper handling of multi-table inheritance and polymorphic models via PK-based cross-model matching
• Skips checks on 4xx/5xx responses by default (configurable)
• Stack trace with registration site included in every detection message, so you know exactly where the offending query was set up
• New batch reporting mode that collects all detections and reports at the end of a request
• A NPLUSONE_ENABLED = False switch for zero overhead in prod
• Celery support out of the box
• Debug mode that logs every signal during a request

I have been using it in my real project and it works really well, even with complex Django patterns like polymorphic models. It catches almost all N+1 issues as well as redundant prefetch_related and select_related calls.

One thing to note: please only use this in your dev or test environment. The package uses middleware and monkey patches the ORM, so it is not meant for production. For production monitoring, tools like Sentry or Datadog are better suited. There is a NPLUSONE_ENABLED flag that makes it a no-op in prod if you want a single config.

I tested it intensively on Django. For SQLAlchemy and Peewee I mostly ported the original logic and the test suite passes, but I have not battle-tested those ORMs in a real project yet, so feedback is welcome.

Repo: https://github.com/huynguyengl99/nplus1

Hope you find it useful.

Disclaimer: I used Claude Code to help with parts of this, but I read every line, tested it against my own project, and have plenty of open source experience, so please do not write it off as AI slop. And again, since it is dev-only, there is no production performance concern.

reddit.com
u/huygl99 — 6 hours ago
▲ 1 r/django

API testing

How do you currently test your API endpoints? Do you use Postman/Insomnia? What's the most painful part?

reddit.com
u/agh_98 — 20 hours ago
▲ 3 r/django

Would a one-to-many field make things easier?

Disclaimer: I already found a way to make the database structure work, I just curious about this concept and if it would make sense to exist.

So in our project, every Team of people has an Account that stores their points. Originally, every team has one account and vice versa, so I just used a OneToOne Field. For convenience, Accounts can be automatically created when a Team is created if the admin doesn't make an account in advance. Originally there was no problem. The Team Model file imports the Account Model to both u

In Team's model (simplified for privacy issues):

import Account

account = models.OneToOneField(Account)

def save(self, *args, **kwargs):

account = Account(name=self.name + " points")

account.save()

self.account = account

Meanwhile, Account never imports Team, so things were fine.

However, I reread the requirements and noticed that the client wants each team to have multiple accounts, but each account can only belong to one team.

Since one-to-many doesn't really exist, I assume the best way is to define a ForeignKey in Account to point to Team:

import Team

team = models.ForeignKey(Team)

Here's the problem. We still import Account in Team in order to create the accounts for the teams, since the teams need the accounts (it needs at least one, and it is required to have a certain number of accounts based on conditions). This leads to circular import.

Now the problem has already been fixed using Lazy relationships, but I wonder: if there was a one-to-many field, would I be able to connect to Account in Team and therefore only import Account in Team and not vice versa? This is embarrassing, but I first asked Chatgpt and it kept telling me that it's not how it works. Thank you.

reddit.com
u/AyrtonHS — 1 day ago
▲ 0 r/django

It’s live!!!

Hey guys!! THANK YOU SOO MUCH TO ALL THOSE THAT ADVISED ME ON WHAY I SHOULD DO AND USE

It’s live

https://encrypted.pythonanywhere.com

But there is a little bit of things I wanna add
If you have any advice or suggestions I’m all ears
Once again thank you soo much
Have not bought a domain though

reddit.com
u/Sad-mike14 — 1 day ago
▲ 34 r/django+1 crossposts

DjangoCon US 2026

Hey everyone!

DjangoCon US 2026 will be in Chicago again this year from August 24–28. Early bird tickets are available through May 31.

We’re looking forward to a week of talks, workshops, open-source sprints, and connecting with the Django community. We’re also still welcoming sponsors interested in supporting DjangoCon US and the broader open-source ecosystem.

https://2026.djangocon.us

▲ 15 r/django

management commands + celery beat turned my weekend project into something 3 investors use daily

a friend who buys rental properties asked me to build him a simple dashboard where he pastes an address and sees if the numbers work. zestimate vs asking price, estimated rent, cash flow at different down payments, school ratings. he was doing this manually on zillow 10-15 times every morning.

the django side came together fast. a Property model with the address, the cached api data as a jsonfield, and a last_updated timestamp. a single view that takes an address, hits a rest api called zillapi that returns zillow data as json, saves it to the model, and returns the summary. basic template with the numbers laid out. nothing fancy.

the part that made this actually useful was management commands. i wrote one called refresh_properties that loops through every saved property and pulls fresh data from the api. hooked it up to celery beat running every sunday night. so every monday morning when my friend opens the dashboard, all his saved properties have current zestimates and rent estimates without him doing anything.

i also wrote a find_deals command that searches active listings in his target zip codes and flags anything where the asking price is more than 10% below the zestimate. that one runs daily. if it finds something it sends him a slack message with the address and the numbers. he's gotten 3 actual leads from this that he wouldn't have found manually.

the jsonfield for caching the api response was the right call. the api returns 300+ fields per property and i only display about 15 of them. but when my friend asks me to add something new to the dashboard i don't have to make another api call. the data is already sitting in the jsonfield. last week he wanted tax assessed value added. took me 5 minutes because the field was already cached.

for the ai side i set up a skill so he can ask claude about his saved properties:

npx clawhub@latest install zillow-full

two more investors from his meetup group asked for access. i added a simple user model with a foreign key to their saved properties and basic login. the multi-tenant part took maybe an afternoon.

total infra is a $7/month render instance running django + celery + redis + postgres. handles 3 users doing 30-40 lookups a day without breaking a sweat.

reddit.com
u/straightedge23 — 2 days ago
▲ 10 r/django+1 crossposts

Reflex-Django For full-Stack django with only Python

For years, Django developers building web applications have had to split their work across multiple technologies.

You write your backend in Django or FastAPI, then switch context completely for the frontend:
React, Vue, Angular, TypeScript, APIs, state management, frontend routing, hydration issues, build pipelines, and endless JavaScript tooling.

Even simple internal applications can quickly become overengineered.

But what if Python developers could build modern full-stack applications while staying entirely inside the Python ecosystem?

That’s exactly the problem I’ve been working on solving with reflex-django.

The Problem with Traditional Django Frontends

Django is one of the most productive backend frameworks ever created.

It gives developers:

  • A powerful ORM
  • Authentication system
  • Middleware
  • Admin panel
  • Internationalization
  • Mature ecosystem
  • Excellent scalability

But when it comes to frontend development, most teams usually end up choosing between two approaches:

1. Django Templates

The classic approach works well for many projects, but modern interactive applications often become difficult to maintain as complexity grows.

You eventually deal with:

  • Large template files
  • JavaScript sprinkled everywhere
  • Complex UI interactions
  • State synchronization issues

2. Separate Frontend Frameworks

The modern approach usually means:

  • Django REST API or GraphQL
  • React/Vue/Angular frontend
  • Separate deployments
  • Separate authentication flows
  • Duplicate routing systems
  • Cross-origin issues
  • Increased infrastructure complexity

This architecture is powerful, but it comes with a significant development and operational cost.

Especially for small teams or backend-focused developers.

Introducing reflex-django

reflex-django combines the power of Django and Reflex into a unified developer experience.

The goal is simple:

>

No HTML.
No CSS.
No JavaScript.
No separate frontend framework.

Instead of treating frontend and backend as separate worlds, reflex-django allows both Django and Reflex to run together in the same process while preserving Django’s ecosystem and capabilities.

What Makes reflex-django Different?

Unlike traditional frontend integrations, reflex-django is deeply connected to Django itself.

Inside your Reflex application, you can still access:

✅ Django ORM
✅ Django authentication
✅ Request object
✅ Middleware
✅ Context processors
✅ Sessions
✅ Internationalization (i18n)
✅ Django Admin
✅ Existing Django apps
✅ Existing Django models

This means you are not replacing Django.

You are extending it with a modern reactive UI layer built entirely with Python.

One Process Architecture

One of the core ideas behind reflex-django is simplicity.

Instead of maintaining:

  • A frontend server
  • A backend API server
  • Separate deployments
  • Separate authentication systems

You run Reflex and Django together in one process.

That architecture provides several advantages:

Simpler Development Workflow

You don’t need to constantly switch between frontend and backend projects.

Everything lives in Python.

Shared Context

Because Reflex runs alongside Django, you can directly access Django concepts naturally inside the application.

Examples include:

  • Request user
  • Sessions
  • Middleware state
  • Django authentication
  • Context processors

Without manually exposing APIs for everything.

Reduced Infrastructure Complexity

You avoid:

  • CORS problems
  • API synchronization issues
  • Duplicate authentication logic
  • Frontend/backend version mismatches

Which dramatically simplifies deployment and maintenance.

Why This Matters for Python Developers

A large number of backend developers want to build products quickly without becoming frontend specialists.

Not every application requires a massive SPA architecture.

Many applications primarily need:

  • Dashboards
  • Admin systems
  • Internal tools
  • AI platforms
  • Educational systems
  • ERP systems
  • CRUD applications
  • Business automation platforms

For these types of systems, productivity and maintainability are often more important than frontend complexity.

reflex-django focuses heavily on that productivity layer.

AI Applications Are a Great Fit

One area where I believe this architecture becomes especially powerful is AI applications.

Modern AI systems already rely heavily on Python:

  • LLM orchestration
  • RAG pipelines
  • Agents
  • Data processing
  • Machine learning
  • Vector databases

Adding a separate JavaScript frontend stack on top of an already Python-heavy architecture increases complexity significantly.

With reflex-django, AI developers can remain fully inside the Python ecosystem while still building modern interactive interfaces.

Core Capability: Django Context Inside UI Events

The real breakthrough is stateful event handling.

Every event handler has access to Django context:

import reflex as rx
from reflex_django.state import AppState

class DashboardState(AppState):
greeting: str = “”

rx.event
async def load(self):
if not self.request.user.is_authenticated:
return rx.redirect(“/login”)

self.greeting = f”Welcome {self.request.user.username}”

What this unlocks:

  • Direct access to authenticated user
  • Session persistence without extra layers
  • ORM queries inside UI logic
  • No API serialization layer

This removes the traditional frontend-backend boundary entirely.

Full-Stack CRUD Without APIs

A typical task system becomes straightforward:

from myapp.models import Task
from reflex_django.state import AppState

class TaskState(AppState):
tasks: list[dict] = []
title: str = “”

u/rx.event
async def load_tasks(self):
user = self.request.user
qs = Task.objects.filter(user=user)
self.tasks = [
{“id”: t.id, “title”: t.title}
async for t in qs
]

u/rx.event
async def create_task(self):
await Task.objects.acreate(
user=self.request.user,
title=self.title,
)
return TaskState.load_tasks

Key takeaway:

No REST API. No serializers. No frontend fetch calls.

Just domain logic.

Reactive UI in Pure Python

The UI layer is declarative and fully reactive:

import reflex as rx
from frontend.state import TaskState

def task_page():
return rx.vstack(
rx.input(
value=TaskState.title,
on_change=TaskState.set_title,
),
rx.button(“Add”, on_click=TaskState.create_task),
rx.foreach(TaskState.tasks, lambda t:
rx.text(t[“title”])
),
)

No JSX. No templates. No JavaScript runtime logic.

When This Architecture Makes Sense

This model is optimal when:

  • You want Django-grade backend reliability
  • You want reactive UI without JavaScript complexity
  • You value monolithic deployment simplicity
  • You are building SaaS, internal tools, dashboards, or AI apps

It is less suitable when:

  • You require fully decoupled frontend teams
  • You rely heavily on frontend-native ecosystems (React-only tooling)

📦 Package & Documentation

You can install and explore the project here:

Reflex-Django

reddit.com
u/EmergencyJackfruit87 — 2 days ago
▲ 6 r/django

Windows Services for Waitress: NSSM alternatives?

Howdy everyone!

Deploying on Windows (non-negotiable) - there is no IIS but instead, Caddy as a reverse proxy in front of Waitress as the server.

How best to create this a as a service in Windows so it will be able to automatically restart?

I've googled and found NSSM, but to the best of my additional googling - it looks like it's no longer maintained and is not the best way to go about that.

What other options exist for something like this?

Caddy was setup as a service simply by using the built-in sc.exe.

I created a 'serve.py' (which serves the wsgi application via waitress) - from the command line it works great. When I add it as a service via sc.exe, it times out (because a Python script won't return the signal it's ready to the Windows Service Control Manager).

I realize this is a pretty niche thing - but has anyone else done this? What are you using?

reddit.com
u/chaoticbean14 — 2 days ago
▲ 5 r/django

Can anyone recommend instructions for baby's first deployment pipeline?

Hi everyone! I've deployed manually before, but I would like to try to automate it. I'd appreciate it if someone could point me in the directions of instructions for the simplest version of "make a commit -> ... -> deployment server gets updated".

I know that this is something that I can Google, and I have, but my frustrations are that (1) it is difficult to tell if advice is appropriate for Django and up-to-date and (2) it seems that a lot of the most popular advice is aimed at paid services. I'm willing (and expecting) to pay, but I would like to feel more confident that I'm on the right track before I pull the trigger on that.

Here are some details:

  • It is a very small project and I expect almost no users. It is a hyper-specific tool for displaying project info to clients.
  • I am not tied to any specific server service.
  • I'd like to keep costs under $20/month, but I would consider going up to like $50/month. Hopefully that is reasonable.
  • I am not currently tied to a specific database; any is fine.
  • My stack is really just Django, Bootstrap, and a dream.

Thanks in advance for your help!

reddit.com
u/androgynyjoe — 3 days ago
▲ 9 r/django+4 crossposts

Built an open-source outbound API gateway in Django/DRF.

​

The idea started after getting tired of re-implementing the same things every time I integrated third-party APIs:

* auth handling

* OAuth token refresh

* rate limiting

* quotas

* logging

* endpoint wrappers

* response formatting

So I built **Asstgr**: a self-hosted platform where you register external APIs once, define endpoints/params/methods, and then access everything through a unified REST interface.

Architecture is basically:

`Your App -> Asstgr -> Stripe/GitHub/OpenWeather/etc`

Features:

* OAuth2 (`client_credentials`, `authorization_code`, `password`)

* API key auth (`sk-...`)

* per-user quota system

* DRF throttling

* endpoint modeling

* audit logs

* unified `/execute/` endpoint

* response formatting modes

* Django admin support

* PostgreSQL + ASGI stack

One thing I wanted was to make external APIs behave more like internal services instead of every project having bespoke integration code.

Tech stack:

* Django 5

* Django REST Framework

* PostgreSQL

* Daphne / Channels

* SimpleJWT

It’s fully open source (MIT), and I also built a hosted SaaS version with a UI layer on top because the admin-only workflow wasn’t great for daily use.

Open source:

https://github.com/botyut/asstgr

Hosted version:

https://www.asstgr.com/home/

Would genuinely love feedback from people who’ve built internal API platforms / gateways before — especially around:

* schema design

* quota systems

* OAuth architecture

* execution abstraction

* scaling concerns

Curious if others ended up building similar internal tooling instead of using RapidAPI / Kong / Tyk / etc.

u/ELMG006 — 3 days ago
▲ 307 r/django

django in 2026 is quietly the most productive framework

i keep seeing twitter arguments about whether next.js 16 or remix or tanstack start is the future, meanwhile im just shipping stuff in django and nobody talks about it

the admin alone has saved me probably a month of work this year across like 3 small projects. nobody else has anything close to it. you get a working backoffice for free, real auth, real permissions, real CRUD, the moment you define your models. it isnt sexy and nobody screenshots it on twitter but its incredible

the ORM gets clowned for being "opinionated" or "magic" but in practice it just stays out of the way. ive been writing django apps for years and i still find query patterns that work first try. compare that to fighting prisma or drizzle migrations at 11pm trying to figure out why the relation isnt generating

async support is finally in a place where i dont have to think about it. every async question on django used to be answered with "well it depends." now its just working

last month i shipped a small saas mvp in like three weeks. django + htmx, no build step, no node_modules folder eating my SSD, no vite config, no tailwind compile pipeline, just python rendering html. felt almost illegal how little setup it needed

the lack of hype is actually a feature at this point i think. nothing new to learn every 6 months, patterns that worked in 2018 still work, you can google (if you still do at least) something and answer from 7 years ago is still correct. boring tech is its own kind of productivity

idk maybe everyone else is right and im missing out on something fundamental, but every time i try to start a project in some modern js stack i lose half a day to tooling before writing a single line of business logic

reddit.com
u/Motor_Ordinary336 — 5 days ago
▲ 0 r/django

switching from flask to django is nightmare for me,i cant return simple hello

in flask its so easy/here before anything i import so many py file that i dont even understand

reddit.com
u/Advanced_Cry_6016 — 4 days ago
▲ 1 r/django

Stripe integration help

Hey everyone,

I am trying to integrate stripe into my SaaS, it's barely going on, but I noticed some points I'd be glad if someone could clarify them...

  1. Why can't stripe just provide me a payment receipt through the API, Why must I go through the hellish cycle of hosted_invoice_url then download receipt?

  2. Should I or Should I not keep a record of transactions in my DB ?

  3. Is there any more recent git repo like T3 (Theo) Stripe recommendations?

Thanks everyone.

reddit.com
u/Hushm — 4 days ago
▲ 3 r/django

GenAI development in Django

Django app adding GenAI development features. Using Celery for background LLM calls but tasks hang, retries are expensive, and users poll for results.

Should GenAI development tasks be in Celery, separate queue, or sync with streaming? Also how do you handle user cancellation, partial results, and cost tracking per user?

For Django devs in production with GenAI development, what’s your task architecture? Any open source examples? Don’t want to rebuild this twice. On AWS with RDS and Redis.

reddit.com
u/Dangerous_Block_2494 — 4 days ago
▲ 13 r/django+1 crossposts

I built a framework on top of FastAPI because I got tired of making the same 12 decisions every project

Every FastAPI project I started felt identical. Pick an async ORM, wire migrations, build an admin panel, standardize serialization, write the glue. Same decisions, different project.

Yes, boilerplates exist. But a boilerplate is something you fork and maintain forever, the assembly decisions just move into your codebase. Every new model, you're back to writing the same wiring.

So I built Aksara. It sits on top of FastAPI, you keep the full ecosystem and performance and handles the repetitive assembly. Define a model once and get:

  • Full REST API
  • Admin dashboard
  • Studio UI at /studio/ui to inspect your backend visually
  • AI Console — ask your live backend questions in plain English
  • MCP tool catalog at /ai/tools/mcp — Claude, Cursor, any MCP client can call your API directly

The piece I'm proudest of is field-level AI metadata. ai_sensitive=True removes a field from AI context and the MCP schema entirely. ai_agent_writable=False lets agents read but not modify. Write it once on the model, propagates everywhere.

Five commands from zero to running:

bash

pip install aksara-framework
aksara startproject myapp && cd myapp
aksara dbsetup
aksara migrate
aksara dev

It's pre-1.0, backed by 6378 tests, and honest about its rough edges.

GitHub: https://github.com/nagarjuna-tella/Aksara Docs: https://nagarjuna-tella.github.io/Aksara/

Happy to answer questions or take criticism, built this nights and weekends and genuinely want to know what's wrong with it.

u/LegendBuster — 6 days ago
▲ 0 r/django+2 crossposts

Token usage

I am stuck at the level where it’s hard to control the number of tokens while team is trying to use it effectively, one day it is good other day it eats up so many tokens for no reason but tries to include more files than it should, any basic idea how to segregate the work like feature or folder or related files only etc will be cool??

reddit.com
u/Commercial_Try_2538 — 5 days ago
▲ 0 r/django

I built a minimalist, Games Catalog. Looking for gamer & dev feedback!

Hey everyone! I've been working on a side project for the past few months and finally launched it — GameVault. I am student of university of Moldova, I'm studying to be a programmer and I wanted to get some practice and do something really interesting and useful for others. For my project I used python with django framework, "meilisearch" search engine and as data base - postgres. It's a game catalog with price comparison across different stores (Steam, GOG, Humble Store, Fanatical and more). You can browse games, filter by genre/platform/store, and see where to buy them at the best price. The project is in its early stages, and I want to enter into agreements with other stores so that I can find better prices.

Still early days — the catalog only has around 8000 games right now. Would love to hear any feedback or suggestions!

You can check out the live project here: Game Vault Dev

reddit.com
u/Itachi_22 — 6 days ago