Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Django: write a custom URL path converter to match given strings
Here’s a little tip based on some work that I did recently. The project has a URL pattern where the first part of the URL matches the current role the user is viewing the site as. Let’s say the roles are “chef”, “gourmand”, and “foodie”—example URLs might look like this: /chef/dashboard/ /gourmand/dashboard/ /foodie/dashboard/ /chef/dish/1/ /gourmand/dish/1/ /foodie/dish/1/ Most views can be accessed under all roles, with restrictions applied within the view code where appropriate. To match the role parts of the URL, you could define each URL pattern individually: from django.urls import path from example import views urlpatterns = [ path("chef/dashboard/", views.dashboard), path("gourmand/dashboard/", views.dashboard), path("foodie/dashboard/", views.dashboard), path("chef/dish/<int:id>/", views.dish), # ... ] However, that gets tiresome quickly and doesn’t really scale to larger numbers of roles or views. Also, it slows down URL resolution, as Django has to check each pattern in turn. Some scalable alternatives would be: Using Django’s str path converter, as in: path("<str:role>/dashboard/", views.dashboard) However, this matches arbitrary strings, requiring extra validation in the view and care to avoid capturing other URLs. Reaching for re_path() to define the URL as a regular expression, like: re_path(r"^(chef|gourmand|foodie)/dashboard/$", views.dashboard) But regular expression syntax is more complicated, especially for matching parameters. Rather than … -
Django: split ModelAdmin.get_queryset() by view
Within Django’s popular admin site, you can override ModelAdmin.get_queryset() to customize the queryset used by the admin views. It’s often used for performance optimizations, such as adding a select_related() call to batch-fetch related objects: from django.contrib import admin from example.models import Book @admin.register(Book) class BookAdmin(admin.ModelAdmin): def get_queryset(self, request): return super().get_queryset(request).select_related("author") However, one thing this approach lacks is granularity—the queryset returned by get_queryset() is used for all admin views, such as the change list, change form, and any custom views that you might add. That can mean that adding an optimization in get_queryset() for one view can impose a performance cost on other views that don’t need it. For example, the above select_related() call might optimize showing author details shown on the change list view, but other pages that don’t show the author will still incur the cost of the join. There isn’t an easy way to customize the queryset for individual views without overriding a lot of their code. However, the queryset() method is passed the current request object as context, which allows you to differentiate between views based on request.resolver_match. I think the most robust way to check the current admin view from there is with the __name__ attribute … -
Our tools are still not designed for the AI future
First a disclaimer on this one: I am making the assumption that the AI trend is here to stay in some form and an economic crash/bubble doesn't make the usage of them untenable, also I have yet experiment with every tool out there! With that said, a brief personal history of my usage of LLM's and the current wave of AI. I tried out ChatGPT when it was first released and was fairly impressed by the results, but the cruical missing step for me was the lack of browser integration, searching Google was still much quicker from a new tab page and the results from ChatGPT felt isolated, there was too much friction in my workflow for it be usable. I tried out a different product (I forget the name), which allowed me to search from a new tab page and I got AI results and normal search results in one go. This was better, but it still didn't stick, and so I kept experimenting with the tools on an ad-hoc basis, solving small challenges, but it not being a daily driver. In this I experimented with local LLMs and Zed's AI integration. This changed earlier this year where I … -
User Timezones in Django
When you create a local website, the local time usually matches your country’s timezone, and all visitors see times in that timezone. That’s not a big issue if your country has only one timezone and your audience is local. But when building a social platform like pybazaar.com, users are international and need to see times in their timezones. In this article, I’ll show you how to handle that in Django. Time Zone Database Since version 4.0, Django has used the zoneinfo library for managing timezones, and it used pytz up to version 3.2. Both rely on the IANA Time Zone Database (tzdata). IANA is the same organization that manages the DNS root zone, IP addresses, and other global internet resources. Install tzdata in your virtual environment as usual: (venv)$ pip install --upgrade tzdata Timezone Changes Timezone information changes several times a year due to: Daylight Saving Time (DST) adjustments Political and border changes Shifts in standard time offset Daylight Saving Time (DST) was first introduced in 1914 in Canada and later standardized in the U.S. in 1966. When dealing with historic dates before 1966—or future dates with uncertain timezone rules—precise time calculations can be unreliable. # Before U.S. DST standardization: … -
Django News - DjangoCon US 2025 Talks Announced - Jul 25th 2025
News Announcing our DjangoCon US 2025 Talks! The official DjangoCon US 2025 talk lineup has been unveiled, featuring expert sessions on Django deployments, ORM alternatives, search, AI integration, CMS, migrations, performance, and community practices. djangocon.us Python 3.14 release candidate 1 is go! This is the first release candidate of Python 3.14. blogspot.com PSF Board Election Nominations Opening July 29th PSF opens 2025 Board Election nominations from July 29 to August 12 UTC, providing a timeline, resources, and guidance for prospective candidates. blogspot.com Updates to Django Today 'Updates to Django' is presented by Pradhvan from the Djangonaut Space! 🚀 Last week we had 14 pull requests merged into Django by 8 different contributors including 2 first-time contributors! Congratulations to LauHerregodts and Ishita Jain for having their first commits merged into Django, welcome on board! 🎉 This week's Django highlights 🌟 Deprecated most positional args to django.core.mail, adding deprecation warnings for non-keyword arguments in email functions, with removal planned for Django 7.0. Added support for GeometryType database function, bringing new GIS functionality for spatial queries with cross-database compatibility including Oracle. Updated migration command to record applied/unapplied migration statuses recursively, fixing how Django handles double-squashed migrations to ensure proper status tracking. That's all … -
Deploying a Django App to Sevalla
This tutorial looks at how to deploy a Django application to Sevalla. -
Latest feature of Comfort Monitor Live released!
Yesterday I finally finished and released the latest feature of Comfort Monitor Live, which allows users to design custom layouts for the comfort monitor. This has been build has been a long slog of over 6 months slowly working on it every Wednesday evening for a couple of hours. AI has helped to an extent in building this feature, but mostly it was still me slowly building and debugging issues as they came up. Being a chrome extension, means a lot of Javascript and I the UI has been NextJS. Both of these have made me realise the beauty and speed Django brings to a project for CRUD operations against a datastore and a structure for quickly creating a UI that can store that data. This was also one of those features which resulted in a rebuild of the core logic to be better and scalable for future use, especially the next feature which will allow the user to implement some rules around how the comfort monitor runs during an event. It's going to be another big lift when I do build it, but for now, with this shipped it's going to allow me to focus more on some Django … -
Django: iterate through all registered URL patterns
I’ve found it useful, on occasion, to iterate through all registered URL patterns in a Django project. Sometimes this has been for checking URL layouts or auditing which views are registered. In this post, we’ll look at a pattern for doing that, along with an example use case. Get all URL patterns with a recursive generator The below snippet contains a generator function that traverses Django’s URLResolver structure, which is the parsed representation of your URLconf. It extracts all URLPattern objects, which represent individual URL patterns from path() or re_path() calls, and returns them along with their containing namespace. It handles nested URL resolvers from include() calls by calling itself recursively. from typing import Iterator, Optional from django.urls import URLPattern, URLResolver, get_resolver def all_url_patterns( url_patterns: Optional[list] = None, namespace: str = "" ) -> Iterator[tuple[URLPattern, str]]: """ Yield tuples of (URLPattern, namespace) for all URLPattern objects in the given Django URLconf, or the default one if none is provided. """ if url_patterns is None: url_patterns = get_resolver().url_patterns for pattern in url_patterns: if isinstance(pattern, URLPattern): yield pattern, namespace elif isinstance(pattern, URLResolver): if pattern.namespace: if namespace: namespace = f"{namespace}:{pattern.namespace}" else: namespace = pattern.namespace yield from all_url_patterns(pattern.url_patterns, namespace) else: raise TypeError(f"Unexpected pattern type: … -
Django News - 🎂 Django Turns 20! - Jul 18th 2025
News 🎂 Happy 20th birthday Django! On July 13th 2005, Jacob Kaplan-Moss made the first commit to the public repository that would become Django. Twenty years and 400+ releases later, here we are – Happy 20th birthday Django! 🎉 djangoproject.com 📻 W2D Django 20th Celebration Continues 🎂 Nearing one week in, two operators of the W2D special event station honoring Django's 20th birthday have made over 400 contacts with 22 geopolitical entities on 4 continents. github.com Prohibiting inbox.ru email domain registrations A recent spam campaign against PyPI has prompted an administrative action, preventing using the inbox.ru email domain. This includes new registrations as well as adding as additional addresses. pypi.org Affirm Your PSF Membership Voting Status If you are a voting member of the Python Software Foundation and you plan on voting this year, here are the details you need to know for how to vote. If you voted in 2024, you are still eligible to vote in 2025; however, we recommend double-checking your status to ensure accuracy. blogspot.com Updates to Django Today 'Updates to Django' is presented by Pradhvan from the Djangonaut Space! 🚀 Last week we had 7 pull requests merged into Django by 7 different contributors including … -
Why Django's DATETIME_FORMAT ignores you
When you start a new Django project, you get a handful of default settings for localization and timezones: settings.py USE_I18N = True LANGUAGE_CODE = "en-us" USE_TZ = True TIME_ZONE = "UTC" I’ve written before about the default timezone being a silly choice for sites with a global user base, both on the backend and the frontend. But today, I want to talk about internationalization (I18N) and language settings. For my sites, LANGUAGE_CODE = "en-us" is perfectly fine; all my admin users speak English, and we prefer American spelling over the British variant. But there are some weird things going on in Django that I want to address. The USE_I18N puzzle Here’s the first weird thing. The default settings have USE_I18N = True, which enables Django’s internationalization features. The default LANGUAGES setting also includes a massive list of every language under the sun. You’d think this means the Django Admin would automatically switch languages. If I set my browser’s preferred language to Dutch, shouldn’t the Admin follow suit? Nope. It remains stubbornly English. It turns out you need to add this to your middleware for the translation to actually happen: settings.py MIDDLEWARE = [ # ... "django.middleware.locale.LocaleMiddleware", ] Only after adding … -
Django at 20: a personal journey through 16 years
Django turned 20 a few days ago, which is a remarkable milestone for any software project. I’ve been along for most of that ride, starting my Django journey in September 2009. That’s almost 16 years ago! It’s been fascinating to watch both Django and my use of it evolve over time. From server-rendered pages to APIs and back When I started with Django in 2009, it was a different world. Everything was server-rendered, with a bit of jQuery sprinkled in. I wrote my very first Django article in November 2009 about dynamically adding fields to models. This was quickly followed by articles on what I didn’t like about Python and Django and how to use Jinja2 templates in Django, which solved some of my pain points. In 2012, my focus shifted dramatically. I went from full-time web developer to full-time iOS developer. Django didn’t disappear from my life though, it just changed roles. Instead of building full websites, I was creating REST APIs to power mobile apps, which is when I discovered Django REST Framework. Fast forward to 2023, and I’ve come full circle, returning to full-time web development. These days, I mostly use SvelteKit on the frontend with Django … -
How to Get Foreign Keys Horribly Wrong
Constraints keep the integrity of your system and prevent you from shooting yourself in the foot. Foreign keys are a special type of constraint because, unlike unique, check, and primary keys, they span more than one relation. This makes foreign keys harder to enforce and harder to get right. In this article, I demonstrate common pitfalls, potential optimizations, and implicit behavior related to foreign keys. Table of Contents Naive Implementation Enhanced Implementation Replacing unique_together Identifying Duplicate Indexes Identifying Blocking Migrations Safely Migrating Foreign Key Reversible Migration Operations Concurrent Index Operations Indexes on Foreign Keys Partial Foreign Key Indexes Using Built-in Concurrent Index Operations Order Migration Operations Locking Across Relations Permissive No Key Locks The Final Model Takeaways The Mandatory AI Angle Watch 📺 This article is inspired by a talk I gave at DjangoCon EU. Watch it here. Naive Implementation Imagine a simple application to manage a product catalog: Generated using dbdiagram.io The first table, or model, in the catalog is the Category model: class Category(models.Model): id: int = models.BigAutoField(primary_key=True) name: str = models.CharField(max_length=50) Categories can be "household items", "fruit", "apparel", and so on. Next, a model to store products: class Product(models.Model): class Meta: unique_together = ( ('category', 'category_sort_order'), ) … -
Happy Birthday to Django!
Over the weekend Django celebrated being 20 years since the first public commit. This is an incredible achievement for a community led project. Django is behind some tiny projects to those that scale globally and personally my career wouldn't be where is it without Django. Most of my career existed with only a vague awareness of the community, but since getting involved on Discord and beyond has been great for my soul and enjoy those that share the passion of seeing Django succeed. So as we celebrate 20 year's would be to get involved if you use Django, go to an event, donate to the DSF or join us in the community (online and in person). If you work for a company that use's Django lobby them to donate as well! I am excited for the next decade of slow but sure progress and the community being healthier than ever before. -
Django News - Django's Ecosystem - Jul 11th 2025
News Django’s Ecosystem The official Django website has added a new page called “Django’s Ecosystem” with a list of resources and 3rd party packages. djangoproject.com Python Release Python 3.14.0b4 It's the final 3.14 beta! Beta release previews are intended to give the wider community the opportunity to test new features and bug fixes and to prepare their projects to support the new feature release. python.org Updates to Django Today 'Updates to Django' is presented by Pradhvan from the Djangonaut Space!🚀 Last week we had 5 pull requests merged into Django by 5 different contributors - including 2 first-time contributors! Congratulations to Roelzkie and matthews-noriker for having their first commits merged into Django - welcome on board! 🎉 This week's Django highlights 🌟 Improved staticfiles manifest reproducibility, fixing nondeterministic file ordering for consistent deployments. Enhanced composite primary key infrastructure, fixing __in tuple lookups on database backends lacking native tuple comparison support. That's all for this week in Django development! 🐍 🦄 Django Newsletter Wagtail CMS 10 Underrated Django Packages 10 underrated Django packages according to the annual Django Developers Survey. wagtail.org Sponsored Link 1 Scout Monitoring: Logs, Traces, Error (coming soon). Made for devs who own products, not just tickets. scoutapm.com … -
What if Django was written in a new language..
So this is a bit of a follow on from Day 277 and taking the premise of the idea presented with it and pushing it further. What if we, as a community decided to (re-)write Django in another language? It's not as wild as you might think, Lily Foote is currently tackling an implementation of the Django template language in Rust and someone else suggested that URL resolving might benefit from a similar treatment. However that is not the goal of this push forward, but it is again Django as design pattern or set of API's. If we wanted to allow someone to migrate Django (or even part of it) to a new language, some comphrensive API documentation outside the codebase and inside the codebase would be a good start. And as I write this I realise that we do have this, it's the amazing test suite that helps to make Django stable (that's all 17898 tests and counting), but even then a test suite is never the whole story. Today was more of a pondering thought and not a complete one at that, but more of a thought experiment and a consideration (to myself more than anyone) of what … -
Python Leiden meetup: Handling crash reports with Bugsink - Klaas van Schelven
(One of my summaries of the fourth Python meetup in Leiden, NL). Bugsink is a tool/website for collecting error messages from (for instance) your websites. You get an email or other notification and you can visit the error page. You'll see the exact error and a traceback and the environment variables and the library versions. But... isn't that just like sentry? Yes. Mostly. But... why bugsink? It is self-hostable. Originally, 20 years ago, sentry was also self-hostable, but it isn't anymore. There's a bit of workflow, too. You can mark issues as "fixed in the next release". Bugsink will then ignore new occurrences of the error until it notices you made a release. It is not just in the same market as sentry, it is even sentry-compatible. If you already have sentry set up, moving to bugsink only means changing the SENTRY_DSN setting. The API is the same. Self-hosting? You can run a docker. He showed that pip install bugsink also works. It is just a plain regular django site with migrate and runserver. A single instance can easily handle 1.5 million errors per day. Some generic tricks (whether sentry or bugsink): Just use your error tracker in development, too! … -
Python Leiden meetup: Deploying python apps with django-simple-deploy - Michiel Beijen
(One of my summaries of the fourth Python meetup in Leiden, NL). Michiel discovered django simple deploy via the django podcast. Deploying? Previously, heroku was often used as an example in books, but they ditched their free tier and are pretty expensive now. So most examples nowadays just show you how to run django locally. Deploying is harder. There are several hosting parties that provide relatively easy django hosting like heroku. https://fly.io, https://platform.sh and https://heroku.com . "Easy" is relative, as he ran into some problems with platform.sh and he didn't have an ssh connection to fix it. And yesterday they nuked his account so he couldn't re-try it for today's demo. Since recently there is also a generic "vps" plugin: just running on some random virtual server with ssh access that you can rent virtually anywhere. https://github.com/django-simple-deploy/dsd-vps . "Random" should be debian-like, btw. He demoed it on a digitalocean VM (="droplet"). With some environment variables he got it working within 15 minutes and some manual fixes. The longest wait was the "apt-get upgrade" call. The VPS version of simple deploy has its drawbacks. It needs a root password, for instance, and at the moment it doesn't accept ssh key authentication. … -
Django-Tailwind Just Got Better with a Unified Dev Command and daisyUI
I created Django-Tailwind back in 2019, at a time when most Djangonauts hadn’t even heard of Tailwind CSS. Since then, the package has grown in popularity, and although I’ve taken some longer breaks from maintaining it, I’ve always returned with renewed energy. That’s happened again recently—after the grueling task of … Read now -
Handling static and media files in your Django app running on Coolify
In a previous article, I detailed my journey of hosting Django sites with Coolify, covering everything from the Dockerfile and database setup to environment variables and server configuration. It was a comprehensive guide to get a Django application up and running. However, I deliberately left out one tricky topic: handling static and media files. This aspect of deployment can be complex and certainly deserves its own article. If your application only serves static files - the CSS, JavaScript, and images that are part of your core application - the solution is thankfully really simple: use WhiteNoise. It is, by far, the easiest way to serve static files directly from your Django application in production without needing a separate web server just for them. However, if you’re also dealing with user-uploaded media files then you have to deal with two challenges: where to store the files and how to serve them. Let’s assume you have a standard configuration in your settings.py: STATIC_ROOT = BASE_DIR / "static_root" STATIC_URL = "/static/" MEDIA_ROOT = BASE_DIR / "media_root" MEDIA_URL = "/media/" The primary problem is that media files uploaded by users will be saved inside the Docker container. Because Coolify creates a fresh container from … -
Using Google Consent Mode v2 on a Django Website
A decade ago, adding website analytics was simple: you’d just paste a JavaScript snippet from Google Analytics, and that was it. But things changed. As people became more concerned about their privacy, countries introduced strict privacy laws—like GDPR in the European Union, PIPEDA in Canada, and APPI in Japan. These laws gave users more control over their data and placed new responsibilities on us developers. One of those responsibilities is showing Cookie Consent banners and respecting users’ choices before loading any tracking scripts. Today, if you want to add Google Analytics to your website, it’s not just about copying a script. You need to understand Google Tag Manager (GTM)—a tool that lets you manage what scripts run on your site and when, using a web-based dashboard. When you add Google Analytics as a Google tag through GTM, it doesn’t automatically start collecting data. It waits for a signal called Consent Mode, which tells Google whether the user has accepted or denied tracking. This signal must be sent from your website to GTM as an event. That’s where your Cookie Consent widget comes in. For Django websites, I created Django GDPR Cookie Consent, which lets you manage user consent and send … -
Weeknotes (2025 week 27)
Weeknotes (2025 week 27) I have again missed a few weeks, so the releases section will be longer than usual since it covers six weeks. django-prose-editor I have totally restructured the documentation to make it clearer. The configuration chapter is shorter and more focussed, and the custom extensions chapter actually shows all required parts now. The most visible change is probably the refactored menu system. Extensions now have an addMenuItems method where they can add their own buttons to the menu bar. I wanted to do this for a long time but have only just this week found a way to achieve this which I actually like. I’ve reported a bug to Tiptap where a .can() chain always succeeded even though the actual operation could fail (#6306). Finally, I have also switched from esbuild to rslib; I’m a heavy user of rspack anyway and am more at home with its configuration. django-content-editor The 7.4 release mostly contains minor changes, one new feature is the content_editor.admin.RefinedModelAdmin class. It includes tweaks to Django’s standard behavior such as supporting a Ctrl-S shortcut for the “Save and continue editing” functionality and an additional warning when people want to delete inlines and instead delete the … -
Django News - Django 2024 Annual Impact Report and Django 5.2.4 - Jul 4th 2025
News Django 5.2.4 bugfix release Django 5.2.4 fixes regressions in media type preference, JSON null serialization, and composite primary key lookups to improve framework robustness. djangoproject.com Django Joins curl in Pushing Back on AI Slop Security Report... Django updates its security guidelines to mandate verified AI-assisted vulnerability reports, reducing fabricated submissions and ensuring human oversight in vulnerability triage. socket.dev W2D Special Event Station announcement Amateur radio operators or those interested who also use Django - special event callsign W2D has been reserved to celebrate Django's 20th birthday. github.com Django Software Foundation Django's 2024 Annual Impact Report Django Software Foundation's annual impact report details community milestones, funding initiatives, and strategic support to drive continued growth and innovation in Django development. djangoproject.com Django's Ecosystem The Django project now has an ecosystem page featuring third-party apps and add-ons. djangoproject.com Updates to Django Today 'Updates to Django' is presented by Pradhvan from the Djangonaut Space!🚀 Last week we had 8 pull requests merged into Django by 7 different contributors. This week's Django highlights 🦄 Content Security Policy lands in Django core: built-in CSP middleware and nonce support finally arrives, closing the ticket #15727. Shoutout to Rob Hudson for finally bringing CSP to Django core. … -
Rate Limiting for Django Websites
Sometimes, certain pages of a Django website might receive unwanted traffic from crawlers or malicious bots. These traffic spikes consume server resources and can make the website unusable for legitimate users. In this article, I will explore Nginx’s rate-limiting capabilities to prevent such performance issues. What is rate limiting, and why use it? A typical Django website is deployed using a Gunicorn (or Uvicorn for ASGI) application server, with an Nginx web server in front of it. When a request comes to Nginx, it goes through various checks, gets filtered by domain, protocol, and path, and is finally passed to Gunicorn. Gunicorn then runs Django, which parses the URL and returns a response from the appropriate view. Nginx rate limiting allows you to limit how often certain pages (based on URL paths) or all Django endpoints can be accessed. It prevents quick reloading or scripted attacks that flood your site with requests. This is especially useful for pages with forms, faceted list views, REST APIs, or GraphQL endpoints. A typical rate-limiting configuration in Nginx defines a zone with a specific memory size (in megabytes), a rate (requests per second or per minute), and one or more locations that apply that … -
Hosting your Django sites with Coolify
I currently run four Django apps in production, with staging and production environments for each. For years, I’ve managed this on a single server with a stack that has served me well, but has grown increasingly complex: A Hetzner VPS running Debian 12 Nginx as a reverse proxy Gunicorn processes managed by systemd More systemd services for background task runners A custom deploy service that listens for GitHub webhooks to pull and restart the right app A custom backup script that archives configs and databases and ships them offsite to rsync.net. I’ve written about this setup in detail, both in “Setting up a Debian 11 server for SvelteKit and Django” and more recently in “Automatically deploy your site when you push the main branch”. While not rocket science, it’s a non-trivial setup. Each new app requires a checklist of configuration steps, and it’s easy to miss one. Worse, my deploy script involves a brief moment of downtime as Gunicorn restarts. It’s only a second or two, but it’s not ideal. I’m more of a developer than an operations person, and building a zero-downtime, rolling deploy script myself feels like a step too far. On the other end of the spectrum, … -
I am back
Well it's been more than a few weeks since I last managed to get some words out the door or even have the headspace for writing. This was mostly down to the new startup picking up steam and client work taking up time, but also a wedding, holiday's and other priorities coming in for me to deal with! All that to say, I'm back for a little while at least, summer is fast approaching which means holiday's again. I'll keep today short as I don't have a particular topic fully developed in mind, but few things I have in my head recently are: AI has finally clicked in my head especially with Agentic stuff coming through. This is what I expected a few years back when ChatGPT was released. The true skill these days seems to be ticket writing (although AI developing PRD documents is something I need to try out). Also using git worktrees to allow multiple agents working on my projects at the same time and creating my own custom AI agents.. I have been enjoying, with the help of AI, the python attrs and cattrs library to validate data going to and from Stripe. I'm excited by …