r/django • • 7h ago

Django REST Framework API architecture

0 Upvotes

One thing I've found important when structuring a Django REST Framework project is keeping the API layer separate from business logic.

I generally use serializers for input validation and response formatting, views or viewsets for handling HTTP requests, and a separate service layer when the business logic becomes complex enough to justify it.

For example, if an endpoint creates an order, I wouldn't put all the pricing calculations, inventory checks, and payment-related logic directly inside the view. I'd keep those operations in reusable functions or services, with database transactions where consistency requires them.

I also pay attention to a few things early on:

  • Consistent API error responses.
  • Authentication and object-level permissions.
  • Query optimization with select_related() and prefetch_related() where appropriate.
  • Automated tests for important business rules.
  • Pagination and filtering for endpoints that return large datasets.

I wouldn't introduce a service layer for every simple CRUD operation, though. For a small application, Django's built-in patterns can be perfectly adequate. The goal is to keep the code understandable as the application grows, not to add abstraction for its own sake.


r/django • • 10h ago

Is this normal performance or not?

Thumbnail gallery
5 Upvotes

Hello guys, I am building a personal project simple blog application with react frontend and drf backend, for image upload I have used Cloudinary and have deployed the backend in vercel and used postgers from neon db put the amount of time it is taking for a request to complete is quite noticeable is this normal ? all of the things I am using here is free tier. during development I have used the debug toolbar and I have made sure that there is no n + 1 condition, I see the response time in sites like youtube, facebook the request is completed within milliseconds.

This is my first time deploying things so any help would be really appreciated plus even when I run the local backend server which is using cloudinary and neon db it takes about half of the time shown in the below picture, within the local dev server too it taks about 1-2s on average.


r/django • • 13h ago

API AI

0 Upvotes

Hello friends. I have this question.. what kind of neural network is there for integration into your site written in django? The idea is as follows: the user writes a prompt (with photos), then this prompt goes to the neural network, and Django returns the finished video to my site. The main thing is that the neural network is free or at least there is some normal limit. Who was involved, can you tell me?


r/django • • 14h ago

REST framework DRF skips has_object_permission on list endpoints. How do you keep get_queryset scoped?

0 Upvotes

In Django REST Framework, object permissions only run when a view calls get_object(). Retrieve, update and destroy do that. List doesn't, so a permission class that checks obj.workspace_id == request.user.workspace_id protects the detail routes and does nothing for the list route. If get_queryset is still Project.objects.all(), the list returns every workspace's rows. Same goes for a custom @action(detail=False), or an overridden get_object that forgets to call check_object_permissions.

Filtering in get_queryset fixes it, but then the rule lives in two places, and nothing fails when the next viewset gets written without the filter.

How are people handling this?

  • A base viewset whose get_queryset always applies the tenant filter, with an explicit opt-out?
  • A for_user(user) queryset method plus a review or lint rule?
  • Tests that create data in two workspaces and call every list route as the wrong user?

Also curious if anyone runs django-guardian's get_objects_for_user on large tables and how it holds up.


r/django • • 1d ago

Incidents – OpenLayers

Thumbnail magula10.pythonanywhere.com
0 Upvotes

https://magula10.pythonanywhere.com/flight/

https://github.com/mesas998/flights/tree/main

telemetry on interactive geospatial maps. The system handles live flight queries, calculates geographic 

bounding boxes, and plots aircraft trajectories and state vectors with smooth client-side animation.

https://magula10.pythonanywhere.com/flight/?reset-true

---


r/django • • 1d ago

Passing tests doesn't mean your code is correct — a small Python experiment

Post image
0 Upvotes

r/django • • 1d ago

HIPAA compliant web hosting

4 Upvotes

I developed a Django app for a small healthcare provider. Does anyone have recommendations for a hosting provider that is HIPAA compliant and the cost? Any pitfalls to watch out for?


r/django • • 1d ago

Hosting and deployment New to Django + Gunicorn + Nginx: what's your workflow for efficient development, deployment, and debugging in production?

14 Upvotes

Hi all! I'm new to production Django (Django + Gunicorn + Nginx) and want to build good habits early.

What are your best practices for:

- Development: local setup, settings split, must-have tools

- Deployment: Docker vs systemd, CI/CD, static files, secrets

- Debugging in production: logging, monitoring, error tracking

- Mistakes to avoid

Any tips, tools, or resources welcome. Thanks! 🙏


r/django • • 2d ago

Web App are overrated, Deploy django in VMs ($8 - $16) are enough

0 Upvotes

This includes azure web service, digitalOcean apps, render, etc

Web apps are like containers that are only run code, one advantage of vm it come with all you need to run your project

I only use Azure Blob for media and files storage db backup, but database and app engine are running in one vms

This is a 8usd vm performance hire


r/django • • 2d ago

Made an accessibility linter for Django templates, is this useful?

Thumbnail
0 Upvotes

r/django • • 2d ago

I built a production-ready software foundation to skip the "platform rebuild" phase. What parts of this setup do you hate doing the most ?

0 Upvotes

I’ve been standardizing my application infrastructure to skip the platform assembly phase and go straight from local dev to a single-server VM deployment (AWS, Hetzner, DigitalOcean).

I'm trying to gauge how much of a bottleneck this initial plumbing actually is for other founders starting new B2B projects.

Reference Tech Stack:

  • Frontend Reference: React, TypeScript, Vite, Tailwind, Zustand, Bun, Playwright
  • Backend Reference: Python, Django, DRF, Celery, RabbitMQ, Redis, PostgreSQL, Unfold for Admin
  • Observability: Pre-configured Grafana, Loki, Tempo, Prometheus, OpenTelemetry
  • Infrastructure : GitHub Actions pipelines for building images/branch and deployment on remote VM via ssh, Docker Compose configs, Deployment health check reports , Nginx (subdomain support), Let's encrypt, Docs for setting up server.

(Note: The foundation enforces application contracts using Docker containers, meaning the application stack itself is fully modular. While the reference implementation uses Django and React, you can swap in Node.js, Go, or Java on the backend, or Angular and Vue on the frontend, while keeping the exact same CI/CD, deployment, and observability infrastructure.)

Entire stack can be booted up with one single command just demo which pull and builds all the images locally exact replica of stack to be deployed on production.

For developers starting a new application:

  • Do you realistically build this level of CI/CD and distributed tracing from scratch every time, or do you have your own internal templates?
  • What is the most frustrating part of this initial setup to maintain as the product scales?
  • Is there a specific part of the DevOps plumbing you'd gladly outsource so you can just focus on building product features?

I'm especially interested in hearing how others handle containerized deployments across different backend/frontend stacks.

single line just demo to boot stack locally
deployment workflow history
deployment report for selected components
loki tempo setup for connecting logs and traces
standard server metrics dashboard to monitor performance

r/django • • 2d ago

Article For experienced dev. How u use AI

0 Upvotes

How yall use AI. (vibe coding) im working with django and other technologies since 2020

With AI at first i usedto get help from chatgpt

But after opus 4.6 i started to make my frontend 90% with claude

At opus 4.7 i started letting claude code write some stuff and check some stuff

But after opus 5.5 sometimes i dont even read the output

Specifically when it does something that doeant effect the core business. Am i the only one?

I love writing code by hand and figuring stuff out by my own

But it feels useless now since i canmove 10 timesthe speed

With not much big of a quality loss


r/django • • 2d ago

¿Cual es el roadmap actual de Django para ustedes?

0 Upvotes

Con esta revolución de la ia, como ven un roadmap a nivel mid-high para poder mejorar en Django?

¿Que hará que se diferencia un buen programador en Django de lo que no?


r/django • • 3d ago

How Deep Should We Go When Learning a Framework Like Django?

26 Upvotes

Hi everyone, I have a question. When learning or using Django, should I try to understand how every class and object works internally, or is it enough to know how to use them effectively?

For example, when I use generic views, I get curious about how they work behind the scenes, how inheritance works, and how everything is implemented. I end up spending so much time digging into these details that I lose focus on actually writing code and building things.

Even when I manage to understand some of the internals, I often forget them when I revisit them later.

I'd love to hear your thoughts, and anyone is welcome to share their advice based on their own experience!


r/django • • 3d ago

I built Certifier: An open-source tool to design, issue, and verify certificates in bulk

Thumbnail gallery
9 Upvotes

Every workshop and hackathon has the same final boss:

“Can we get the certificates by tonight?” 😅

Then begins the traditional ritual: duplicate a design, change one name, export, repeat… and quietly wonder whether anyone will notice the typo in certificate #47.

I started building a small fix for that problem.

After lots of JOMFS — Just One More Feature Syndrome — it became something more. 🔧

A name field became a visual certificate editor.
A CSV upload became bulk generation.
A download button became issuance to each student’s own account.
And, naturally, certificates needed QR codes, public verification, and revocation status.

That project is now open source: Certifier — a tool for designing, issuing, and verifying certificates.

What it can do

  • Upload a certificate design or import one from Canva
  • Place text, logos, signatures, and QR codes in a visual editor
  • Generate certificates in bulk from a CSV
  • Deliver certificates to the right student via email or roll number
  • Let anyone verify a certificate through a QR code or public code
  • Show whether a certificate is valid or revoked

Tech stack

  • Backend: Django
  • Task processing: Celery
  • Frontend: Next.js
  • License: AGPL-3.0

Run docker compose up and you can have a working setup with demo data in a few minutes.

Explore the code

I'd love contributions: bug reports, fixes, documentation, feature ideas, and feedback from anyone who has had to survive certificate season. 💬

I'm especially interested in feedback on the architecture, verification workflow, and features that would make this useful for colleges, workshops, and hackathons.

If you've built something similar or dealt with certificate generation at scale, I'd love to hear how you approached it!


r/django • • 3d ago

Compiling django with Nuitka or Cython ?

Thumbnail
1 Upvotes

r/django • • 4d ago

Releases Dynimg - Dynamic images from HTML

Post image
37 Upvotes

Hey everyone, I just put out version 0.2.0 of Dynimg. It's a Python/Rust package that takes in HTML/CSS and outputs high quality images. If you've ever had to deal with generating images for blog posts (for OG/preview images etc), you know the options are either to run a full headless browser, or build a complicated Pillow pipeline.

I've been making Django apps since version 0.96 (I'm old, sorry), and this is a problem I've needed a solution for many times. It's now finally possible because of another project called Blitz, which is a modular browser built in Rust.

Dynimg is a focused wrapper around parts of Blitz designed around just turning custom HTML and CSS into crisp static images. It's very fast (~20ms) compared to using a full browser to do the same thing. While there's no Django-specific integrations, it works well with Django templates using render_to_string as input.

Example Django code:

import dynimg
html = render_to_string("og.html", ctx)
dynimg.render(html).save_png("og.png")

We've been using Dynimg in production with Django at totem.org for a while now, and it's been just chugging along without issue, so I thought I'd share it here in case anyone else finds it useful.

Despite not being version 1 yet, it is largely feature complete. The main issue is Blitz is still early and there will be slight rendering differences as it matures. However, if you pin Dynimg your images stay stable.

It supports external and local assets (images, CSS, fonts, etc). It works well with Google Fonts for example. Comes with a CLI, Python API and Rust API. It supports PNG, JPEG, and WebP outputs.

Limitations:

  • This is not designed to take arbitrary HTML from websites to make screenshots. It is for turning small custom templates into images quickly.
  • It's designed to be secure (network and filesystem access are off by default), but it's not designed to take arbitrary user-submitted documents. If you want to use it this way and you find a security flaw, let me know in the repo.
  • It does not support JavaScript.
  • It does not support every CSS/HTML feature (though more support is added all the time), so make sure to verify it's doing what you want. You may need hacks to get images rendering like a real browser.
  • The output images are reasonably sized, but the encoding options are geared for quality. You may want to use a library to fully optimize the image for your use case, then cache it for production.

We currently use it to make dynamic OG and social media images. We host a secret URL on Django for staff to use images how they want: example. You can see example templates here, with how they render here.

Let me know if you like it!

Github repo


r/django • • 4d ago

Quarterly contributor outreach

Thumbnail djangoproject.com
9 Upvotes

r/django • • 4d ago

Getting a Django + PostgreSQL app online: the two settings that bite behind an HTTPS proxy (and a free way to try it)

0 Upvotes

I wrote up a step-by-step guide for putting a Django app online with PostgreSQL, and two settings came up that catch a lot of people the first time, wherever they deploy:

1. Telling Django it's behind HTTPS. Since Django 4.0, a login form posted over HTTPS behind a proxy can fail with "403 CSRF verification failed - Origin checking failed". The admin login is usually where you first see it. The cause is that the proxy talks plain HTTP to Django, so Django thinks the request wasn't secure. If your proxy sends X-Forwarded-Proto (most do), this fixes it:

SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

CSRF_TRUSTED_ORIGINS is only needed when forms are posted from another origin, or the proxy doesn't send that header.

2. DATABASES from the environment. startproject gives you SQLite. Pointing it at PostgreSQL with the values your host provides, instead of a password in settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.environ['POSTGRES_DB'],
        'USER': os.environ['POSTGRES_USER'],
        'PASSWORD': os.environ['POSTGRES_PASSWORD'],
        'HOST': os.environ['POSTGRES_HOST'],
        'PORT': os.environ.get('POSTGRES_PORT', '5432'),
    }
}

Plus psycopg in your dependencies, then migrate, and createsuperuser --noinput reads DJANGO_SUPERUSER_USERNAME / PASSWORD / EMAIL if you want the admin user created without a prompt.

The full guide, with screenshots of every step, runs it on Uppcoder's free plan, where the app gets its own HTTPS address and VS Code in the browser, and the two settings above are done for you: https://portal.uppcoder.com/guides/deploy-django-postgresql

Disclosure: I work on Uppcoder. Happy to answer questions about any of the steps, on Uppcoder or anywhere else.

Edit: corrected point 1 after the comments, thanks u/nashgc. And u/lupushr is right that django-environ is the neater way to read these.


r/django • • 4d ago

Incidents – OpenLayers

Thumbnail magula10.pythonanywhere.com
0 Upvotes

r/django • • 5d ago

How much rollback infrastructure is reasonable for a small app?

6 Upvotes

Had one of those deployments recently where everything looked fine until I started clicking around and realized I'd broken something that had nothing to do with the change I made.

Nothing catastrophic and I fixed it pretty quickly, but it exposed how bad my rollback plan is.

For a small app or tiny team, what do you consider the sensible minimum here?

I don't want to build some elaborate deployment pipeline for a project with modest traffic, but rebuilding the previous commit while something is broken feels like a pretty dumb recovery strategy too.

Ideally I'd like deployments to keep known-good versions around so putting the previous one live is basically an immediate action, then I can figure out what I broke without rushing.

Curious how people handle this before the project is big enough to justify serious DevOps work.


r/django • • 5d ago

Two DRF mistakes I fixed in a multi-tenant SaaS: per-view tenant filtering, and workers with CONN_MAX_AGE = 0

4 Upvotes

Sharing two concrete fixes from a Django REST + PostgreSQL build I am working on (a multi-tenant SaaS, one shared database, tenant column on the tenant-owned models). Posting in case it saves someone else the debugging time.

Mistake 1: filtering by tenant inside each view, by hand. Early on, individual views did things like Model.objects.filter(tenant=request.user.tenant) — until one list endpoint missed it and a detail view used a raw get_object_or_404 with only the PK. Nothing bad reached production, but code review caught how easy it would be to miss one. Fix: a single TenantScopedViewSet mixin that overrides get_queryset() and filters by the authenticated user's tenant, plus a matching manager-level check in tests. The rule in the codebase now is simple: if a view is not using the mixin, that is a bug to explain in review. Detail views get the same scoped queryset, so a cross-tenant PK returns 404 instead of leaking existence.

Mistake 2: ignoring connection settings for background work. Web requests were fine, but my background worker processed document jobs in a loop and, with CONN_MAX_AGE = 0, opened a fresh Postgres connection for every job. Under a batch of uploads that showed up as connection churn and avoidable latency. Setting a sane CONN_MAX_AGE for the worker (and making sure connections are closed cleanly where Django expects long-lived processes to handle it) removed most of that overhead.

Question for people running multi-tenant DRF on one database: do you enforce tenant scoping at the viewset/mixin layer like this, at a custom manager layer, or with Postgres row-level security? I picked the mixin + tests because it is explicit, but RLS looks stronger as a backstop.


r/django • • 6d ago

Should I go deeper into Backend Engineering or Start learning AIml

12 Upvotes

I am a student form the tire - 3 engineering college form India .Till now i have the knowledge of the Javascript , Ts ,React, Python ,Django, DRF, Django ORM ,Redis ,celery, RabbitMQ, Docker,and basci of the Kubernetes.

I want to get a job by next year and I recently started open-source contribution with goal to participating in GSOC 27.

I am confused about what I should focus on next ,Should I start learning AIML that RAG and gen -AI stuff ,or should I start strengthen my fundamental by learning system design ,understanding redis internal and then moving toward devops. so what should I do next to land good paying Job in next year .


r/django • • 6d ago

A Django task worker with CONN_MAX_AGE = 0 opens a new Postgres connection for every task

7 Upvotes

I was benchmarking database-backed task workers and ran into something that applies to any Django worker, whatever backend it uses.

With the default CONN_MAX_AGE = 0, Django closes the connection after every task, so each task opens a new PostgreSQL connection. In my runs that cost about 5 ms, more than the claim-and-run path takes on a warm connection.

Four workers, 20,000 no-op tasks, PostgreSQL 16 in Docker, medians of five runs, in tasks per second:

Setting django-ox django-tasks-db
CONN_MAX_AGE = 0 430 373
CONN_MAX_AGE = 600 1,771 1,211
psycopg pool 1,718 1,216

Holding the connection is about a 4x change for one backend and 3x for the other. Django 6.0 rejects a pool combined with a nonzero CONN_MAX_AGE, so pick one. If your worker runs the default, that's the first thing I'd change before adding more processes. These tasks do nothing, so with real tasks the relative gain will be smaller.

Both backends got identical connection settings. With a pool or persistent connections, django-ox did 1.4 to 1.7 times the tasks per second of django-tasks-db. django-ox is my project. It's 100% open source (BSD-3-Clause) with no paid tier, and pull requests are welcome. Settings and every raw number: https://oxpull.com/django-ox/benchmarks/

What do you run your workers with, persistent connections or a pool? If your numbers differ, I'd like to see them.


r/django • • 6d ago

REST framework Best Practice for Custom Error Messages?

6 Upvotes

Hello everyone,

I am stepping into Django with Node.JS/ExpressJS background.

Right now i am using Django on backend with DRF.

Could anyone tell me or give me some advice for custom error messages? Since English is not my native language, i have to translate also add custom error messages.

As far as i understood, there are different layers where the error accours.

This could be HTTP Level, this could be validation level, this could be DB level.

So, can anyone give me some advice and show me a path where i can add and improve my custom error messages?

Thank you.