r/django • • 7h ago

how do you handle seeding dev data that stays realistic as models change?

3 Upvotes

on a mid sized django project we keep breaking our fixtures every time a model changes, and half the team has stopped using them. i've seen factory_boy, custom management commands and loading a scrubbed prod dump. what actually held up for you over a year or two, and how do you keep it from rotting?


r/django • • 8h ago

Django security releases issued: 6.1.4, 6.0.11, and 5.2.20

Thumbnail djangoproject.com
26 Upvotes

r/django • • 21h ago

Hosting and deployment Lightweight Django monitoring without running Prometheus or Grafana

Post image
17 Upvotes

I've been building StatLite, an open-source monitoring dashboard for applications running on small servers and VPSs.

I just added native Django support using django-prometheus. Instead of running a separate Prometheus server, StatLite reads the metrics endpoint directly and stores the history in SQLite.

It tracks HTTP requests, errors, average latency (with a separate metrics listener), process CPU and restarts where available.

StatLite itself is a single Go binary using around 12 MiB of idle RAM.

There are two supported Django configurations: an inline metrics endpoint for basic HTTP monitoring, or a separate listener for latency monitoring as well.

I'd be interested in feedback from people running Django on small VPSs.


r/django • • 1d ago

Apps celery beat died after a deploy and nothing noticed it for 4 days

5 Upvotes

I'm running a small django app for the client. One VPS with docker compose gunicorn, a celery worker, celery beat, redis, postgres. Beat sends me the weekly invoice reminders and there's a night cron jobs that expires old trial accounts.

recently I changed the compose file to pin the redis version and redeployed but the beat container exited on start with a permission error on celerybeat-schedule because the volume got recreated owned by root also that one service had no restart policy (that's an old copy paste my fault). Worker and web running fine.

but then I found out on saturday when client asked why trial users from two weeks ago could still log in.

and the most annoying part is that my monitoring looked perfect the whole time. Dotcom Monitor logs in as a test user and loads the dashboard every few minutes which has been great for the web side but beat being dead doesn't change a single page. Sentry had nothing either since a task that never gets scheduled never throws.

I fixed the ownership put restart (unless-stopped) on everything and moved the schedule file to /tmp so it doesn't depend on the volume. What I still want is something that tells me when a periodic task hasn't run.

Options I'm thinking aboutis to setup a last_run row each task updates plus a small view that returns 500 when it's older than expected (then the outside check I already have can just watch that URL) also switching to django-celery-beat with the DatabaseScheduler or a healthchecks-style ping at the end of every task.

What are you doing for this? Is the last_run view reasonable or am I just reinventing something that already exists?


r/django • • 1d ago

Hosting and deployment Deploying Django on a small PaaS: migrations, collectstatic, gunicorn workers and Celery. What would you have done differently?

4 Upvotes

Disclosure: I work on Faable, a small PaaS (not linking it). Django is one of the stacks we detect and run without a Dockerfile, and a few of the defaults we picked are ones I keep second-guessing. I'd like to hear how people who run Django in production handle them.

1. Migrations don't run on deploy. We left migrate out of the release on purpose: you run it as a one-off task against the live environment when a release needs it. The cost is obvious. Sooner or later someone ships code that expects a column that isn't there yet. Do you run migrate in a release phase, in the container entrypoint, or by hand? And if it's automatic, do you keep migrations backwards-compatible (add first, remove one release later) or just accept a few seconds of errors?

2. collectstatic runs at build time, and a failure doesn't fail the build. If it breaks, the build carries on without staticfiles/ and logs it. We did that because a missing env var in settings would block an otherwise fine deploy. What you get instead is a site with no CSS and a green deploy, which is arguably worse. Would you rather the build failed?

3. One gunicorn worker on the smallest instance. At 512 MB, two workers of a Django app with a few heavy imports get OOM-killed, so if the start command asks for --workers 2 --threads 4 we run it as --workers 1 --threads 8 and say so in the log. Threads share memory, but you have to think about DB connections per thread and code that isn't thread-safe. Do you use gthread with Django in production, or go async/uvicorn, or just pay for the RAM and keep sync workers?

4. No Celery in the same app. A background worker is a second app from the same repo with its own start command, and periodic jobs are cron schedules that run a management command in a separate instance, even while the web app is asleep. For small projects that covers most of what people use Celery + Redis + beat for. Have you dropped Celery for cron + management commands (or django-q, Huey, the new tasks framework) on small projects, and where did that stop being enough?

I'm mostly interested in what bit you in production, not in which host is best.


r/django • • 1d ago

Welcome Our Executive Director

Thumbnail djangoproject.com
8 Upvotes

r/django • • 1d ago

Welcome Our Executive Director

Thumbnail djangoproject.com
28 Upvotes

r/django • • 1d ago

I built a linter that catches Django migrations that would lock your tables in production

6 Upvotes

I maintain django-safe-migrations, and 0.8.1 just came out. It reads your migration files without a database and flags operations like building an index without CONCURRENTLY on PostgreSQL or changing a column type in a way that rewrites the table. Each finding suggests a safer way to write the migration.

In CI, --diff checks just the migrations changed on your branch. A baseline file lets you accept existing findings. If you want to start with one rule, ENABLED_RULES lets you choose which checks run.

Install with pip install django-safe-migrations, add it to INSTALLED_APPS, then run python manage.py check_migrations.

https://github.com/YasserShkeir/django-safe-migrations

What migration has bitten you in production? I'm collecting patterns for new rules.


r/django • • 1d ago

Did anyone here attend interview recently?

4 Upvotes

Wanted to figure out how interviews might be. I am an experienced Django dev. Not sure leetcode is relevant anymore. Also not sure if Django concepts are focused on.

Any inputs would be great. Please share your thoughts.


r/django • • 1d ago

🚀 PSP (Python Scaffolding Projects) v0.11.0 Released!

Post image
0 Upvotes

r/django • • 2d ago

REST framework Cant capture 500 error from external api in try/except block

4 Upvotes

In my DRF app im trying to capture 500 errors from an external api we hit so i can log them appropriately. Pseudo code:

error_logger("test")
try:
    external_api_route.get()
except Exception:
    error_logger("could not connect to external api")

The first logger call logs the test message just fine, but i cant get the second to do any logging.

The actual error is a requests.exceptions.ConnectionError, but i used a broad Exception just to make sure i wasnt missing anything while debugging.

Originally the error was happening on startup (hence why i was able to see the ConnectionError), but i refactored the code so an external api error doesnt bring down my entire app. But since doing so im unable to see the stack trace in any of my logging.

Is something in DRF/django intercepting these 500 errors from the external api? And if so how can i intercept them back?


r/django • • 2d ago

REST framework django-smart-ratelimit 4.13 is out: async middleware fix, blocked clients get back in, thread-safe Memcached

3 Upvotes

django-smart-ratelimit 4.13 is out. It's my rate-limiting library for Django: a decorator, middleware or DRF throttle, with sliding/fixed window, token bucket or leaky bucket, on Redis, the database, Memcached, MongoDB or memory.

The 4.12.2 and 4.13 releases came out of a full audit. The fixes that matter most:

  • Async views under ASGI work with the middleware. It crashed every async view ('coroutine' object has no attribute 'status_code'). Per-user keys and user tiers on async views no longer raise SynchronousOnlyOperation.
  • Rejected requests no longer count. A client that kept retrying while blocked on a sliding window was never let back in. Now it gets back in when the window clears, as documented.
  • Correct Retry-After**.** On sliding windows and token buckets it could be too short or just wrong, so clients that waited were rejected again.
  • Memcached is thread-safe. It shared one socket between threads and lost counts under load. It now uses a connection pool.
  • Backends recover on their own. A Redis or MongoDB server that was down at startup stayed disabled until a restart; now it reconnects. The multi-backend no longer fails every call after one transient error.
  • Circuit breaker fixes. It could get stuck half-open, and @circuit_breaker on an async def never opened.
  • Documented settings that were ignored now work: RATELIMIT_ALGORITHM for the decorator, and RATELIMIT_BACKEND_CONFIG.
  • Security: a signed-in user could use the X-Tenant-ID header to spend another tenant's quota. The user's own tenant now comes first.
  • Ops: ratelimit_health now exits 1 when the backend is down, so Kubernetes probes can fail. Before, it always exited 0.

New:

  • hit() / ahit(): an atomic "count this request only if it fits" call for backend authors.
  • ratelimit_cleanup --events-days N deletes old logged events.
  • A check --deploy warning when X-Forwarded-For is trusted without a proxy setting.
  • MAX_POOL_SIZE for Memcached.
  • Django 6.1 and Python 3.15 support. Django 3.2+ and Python 3.9+ are still supported.

Upgrading: no public name was removed. Helpers nothing used now give a deprecation warning and go in 5.0. Two configurations change behaviour, both because they now do what the docs said: a bucket algorithm set globally in RATELIMIT_ALGORITHM, and RATELIMIT_BACKEND_CONFIG.

Thanks to the GitHub users who reported the async crash and the rejected-request counting.

pip install -U django-smart-ratelimit

Changelog: https://github.com/YasserShkeir/django-smart-ratelimit/blob/main/CHANGELOG.md Repo: https://github.com/YasserShkeir/django-smart-ratelimit


r/django • • 2d ago

Short lessons on what Django 6 adds: Tasks, template partials, fetch modes, CSP, Mailers

Thumbnail conceptual.fyi
19 Upvotes

This is for anyone with a working Django app who has read the 6 release notes and not used most of it yet. You still run Celery for one email job, your HTMX fragments live in a dozen tiny include files, and an N+1 query turned up in production again.

I built this. It's free, and it's organized short lessons with questions after each one. You can pick out any part as your goal, knowing that I make sure you are prepared to learn it. Sign in to save your progress (I'm working on the "learn anonymously" feature, let me know if you have suggestions on how to do that, I was thinking of saving to local storage in the browser)

It covers template partials for HTMX fragments, fetch modes, a nonce-based Content Security Policy and Mailers. The concepts you already know get skipped. No notifications, no streaks (no melodramatic green owls)

FAQ: for those wondering about the ~288 hours. That's if you don't know Programming/Python/SQL/etc... it will take you longer. I'll ask 5 questions to get you started learning something you don't know toward your goal.


r/django • • 3d ago

Apps I built a pytest plugin that checks Django views against Postgres row-level security (rlsparity 0.2.1, alpha)

1 Upvotes

If you use Postgres RLS behind your Django permission checks, there is a quiet failure mode: the view and the policy disagree, RLS hides it, and nobody notices until RLS is off (a script, a migration, a bad role). Then the view serves rows it should not.

rlsparity is a pytest plugin for that. For each (user, endpoint, row) you declare, it runs the view with RLS bypassed and checks whether the same user can see the row with RLS enforced. View returns it but the policy hides it: GAP, test fails. View is stricter than the policy: STRICTER, reported but not a failure.

0.2.1 can check detail, list and write endpoints, including DRF and paginated lists. It can also check a model on a non-default database alias. It prints any GRANTs the probe roles still need as SQL you can paste, writes a JSON report, and gives a clearer error when a table, privilege or role setup is wrong. Role setup is safe to share across parallel test workers.

Things it does not do: it only checks the cases you write, it does not parse policies or views, write checks replay a single statement, and with DRF it skips the real auth classes. It is an alpha, so expect API changes.

pip install rlsparity, repo and docs: https://github.com/driftwright/rlsparity

I am looking for feedback from people who actually run RLS with Django. What would make this useful for your setup?


r/django • • 3d ago

Events DSF Board Nominans are up!

Thumbnail forum.djangoproject.com
5 Upvotes

You don't have to be aDSF member to apply!


r/django • • 4d ago

My first Django project after 2 months of uni - 3Seven

Thumbnail gallery
1 Upvotes

Check my code on GitHub: github.com

I built this Django project and pushed it to GitHub!

https://github.com/mhayyat/3Seven


r/django • • 4d ago

The systemd settings I ended up with for Django + Celery + beat on one VPS (no Docker)

13 Upvotes

I run a Django + Channels app with two Celery workers and beat on one VPS, each as its own systemd service. It took me a while to get the unit files right, so here's what's in them in case it saves someone the trial and error.

For every process:

  • Restart=always with RestartSec=2s, plus RestartSteps=5 and RestartMaxDelaySec=60s. A crashed process comes back in 2 seconds, but if it keeps crashing the wait grows up to a minute, so it doesn't spin in a loop.
  • Its own Linux user per app, not root and not www-data shared with everything else.
  • EnvironmentFile pointing at a root-owned 0600 env file, so secrets aren't in the unit or the repo.
  • PYTHONUNBUFFERED=1, or your logs show up late in journalctl.
  • NoNewPrivileges=true and PrivateTmp=true. On the web process also ProtectSystem=strict and ProtectHome=true, with ReadWritePaths for the app folder.

For the web process:

  • uvicorn bound to 127.0.0.1, never 0.0.0.0. Caddy is the only thing that listens on 80 and 443.
  • --proxy-headers --forwarded-allow-ips=127.0.0.1, so Django sees the real client IP and scheme from the proxy.

For Celery:

  • TimeoutStopSec=90s on the workers (the web process gets 30s). systemd sends TERM, Celery finishes the task it's on, and it only gets killed if it's still going after 90 seconds. If your tasks run longer than that, raise it, or a deploy will cut them off.
  • A separate worker for slow jobs. Mine has one worker on the normal queues and one that only takes the AI queue, both with concurrency 2, so a slow AI call never blocks a quick task.
  • beat as its own service, with django_celery_beat's DatabaseScheduler. Only ever one beat, or every scheduled task runs twice.

For scale: web is around 320 MB, each worker around 280 MB and beat around 140 MB.

Full disclosure, these units come out of a deploy tool I'm building, so I've stared at them more than is healthy. Happy to paste a full unit file in the comments if anyone wants one.

What's in your unit files that you'd never run without?


r/django • • 7d ago

DCR: a wishlist idea has come to life

Post image
25 Upvotes

Recently I shared about new AI tools to build DCR panels (internal tools that live in your admin) as well as a wishlist for things that haven’t been built yet.

Now, a wishlist idea has been built entirely by a community member.

dj-file-browser-panel is a read-only browser for local files in Django admin.

https://djangocontrolroom.com/panels/dj-file-browser-panel

If you’re looking for something to build with Django, take a look at the other ideas on the wishlist.

https://djangocontrolroom.com/panels/wishlist


r/django • • 7d ago

Hosting and deployment when does celery actually need its own vm?

9 Upvotes

I'm trying to figure out when celery actually needs its own vm. Right now django postgres redis and two celery workers are on one 4 vcpu 8 gB box. Usually its fine but then someone uploads a csv with a million rows and the whole app slows down until celery finishes. First time it happened i almost resized the server but ten minutes later everything was normal again. I could move celery to another vps. Serverspace hetzner and others make that easy enough but then i have another server to maintain for a problem that happens a few times a week. Idk if i should wait until this becomes a daily problem or split it now before someone uploads an even worse file?


r/django • • 7d ago

Help me crosscheck chatgpt

Post image
0 Upvotes

Help me crosscheck chatgpt below is the code

function call_in_span(
    span: Sentry.Span | undefined,
    args: AjaxRequestHandlerOptions,
): JQuery.jqXHR<unknown> {
    // Remember the number of completed password changes when the
    // request was initiated. This allows us to detect race
    // situations where a password change occurred before we got a
    // response that failed due to the ongoing password change.
    const orig_password_changes = password_changes;


    // Wrap the error handlers to reload the page if we get a CSRF error
    // (What probably happened is that the user logged out in another tab).
    const orig_error =
        args.error ??
        (() => {
            // Ignore errors by default
        });
    args.error = function wrapped_error(xhr, error_type, xhn) {
        /* istanbul ignore if */
        if (span !== undefined) {
            Sentry.setHttpStatus(span, xhr.status);
            span.end();
        }
        if (reload_state.is_in_progress()) {
            // If we're in the process of reloading the browser,
            // there's no point in running the error handler,
            // because all of our state is about to be discarded
            // anyway.
            blueslip.log(`Ignoring ${args.type} ${args.url} error response while reloading`);
            return;
        }


        if (xhr.status === 401) {
            if (password_change_in_progress || orig_password_changes !== password_changes) {
                // The backend for handling password change API requests
                // will replace the user's session; this results in a
                // brief race where any API request will fail with a 401
                // error after the old session is deactivated but before
                // the new one has been propagated to the browser.  So we
                // skip our normal HTTP 401 error handling if we're in the
                // process of executing a password change.
                return;
            }


            if (page_params.page_type === "home" && page_params.is_spectator) {
                // In theory, the spectator implementation should be
                // designed to prevent accessing widgets that would
                // make network requests not available to spectators.
                //
                // In the case that we have a bug in that logic, we
                // prefer the user experience of offering the
                // login_to_access widget over reloading the page.
                spectators.login_to_access();
            } else if (page_params.page_type === "home") {
                // We got logged out somehow, perhaps from another window
                // changing the user's password, or a session timeout.  We
                // could display an error message, but jumping right to
                // the login page conveys the same information with a
                // smoother relogin experience.
                window.location.replace(page_params.login_page);
                return;
            }
        } else if (xhr.status === 403) {
            if (xhr.responseJSON === undefined) {
                blueslip.error("Unexpected 403 response from server", {
                    xhr: xhr.responseText,
                    args,
                });
            } else if (
                z.object({code: z.literal("CSRF_FAILED")}).safeParse(xhr.responseJSON).success &&
                reload_state.csrf_failed_handler !== undefined
            ) {
                reload_state.csrf_failed_handler();
            }
        }
        orig_error(xhr, error_type, xhn);
    };


    const orig_success =
        args.success ??
        (() => {
            // Do nothing by default
        });
    args.success = function wrapped_success(data, textStatus, jqXHR) {
        /* istanbul ignore if */
        if (span !== undefined) {
            Sentry.setHttpStatus(span, jqXHR.status);
            span.end();
        }
        if (reload_state.is_in_progress()) {
            // If we're in the process of reloading the browser,
            // there's no point in running the success handler,
            // because all of our state is about to be discarded
            // anyway.
            blueslip.log(`Ignoring ${args.type} ${args.url} response while reloading`);
            return;
        }


        orig_success(data, textStatus, jqXHR);
    };


    return $.ajax(args);
}

r/django • • 7d ago

Cree un sistema web en Django

0 Upvotes

Estoy desarrollando un sistema web en django ,que combina inteligencia Artificial predictiva con herramientas de acompañamiento académico para mantener a los estudiantes comprometidos y activos hasta la graduación.


r/django • • 8d ago

Yet another task backend

Thumbnail github.com
5 Upvotes

Howdy y'all, 🤠

If you're looking to switch to Django's task framework, now is as good a time as ever.

Jokes aside, though, as mentioned on the DjangoChat podcast, I mainly build a durable backend with very high I/O throughput. To send emails, dispatch webhooks or VoIP calls. Since then it has been deployed in a growing number of production projects. But I'd love to get more input from people tackling other use cases.

So please do share your experience. 💚

Cheers!
-Joe


r/django • • 8d ago

Apps My small Django job board now labels the jobs that are really AI training work

Post image
3 Upvotes

I run godothire.com, a small Django site that lists paid Godot jobs only.

Some "Godot developer" posts were really AI training work: you help train or test an AI model, not ship a game. Paid, so they stay. But applicants wanted to know before clicking, which is fair.

So each job now checks its title and description against a short list of phrases, and the list and job pages show an "AI training" badge when one matches. A model property and an if in the template, basically.

The tricky part was keeping normal game AI out of it. Every game has an AI. Most of them just walk into walls.

Anyone here done this kind of labelling with something smarter than a word list?

https://godothire.com/


r/django • • 8d ago

Django-related Deals for Black Friday

Thumbnail adamj.eu
0 Upvotes