Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Individual member of the Django Software Foundation
Last Saturday, somewhen late at night when we came back home from our trip to the city, I received an unexpected mail. I was nominated, seconded and approved to be an Individual Member of the Django Software Foundation. This came completely unexpected and honestly caught me a bit off guard. I let it sink in a bit and accepted the invitation on Sunday, with a nice glass of scotch next to me. I have been using Django since 0.96-svn or so and I have been using it to ship production software for a decade. (Yes, I was actually crazy enough to bet on a pre 1.0 release framework instead of TurboGears which was a bit more established, had a nicer ORM and some really nice JavaScript integration.) During all those years I experienced a warm, welcoming and inclusive community that is also able to talk tech. This is a very nice combination. I have seen communities which are also welcoming and inclusive but lacked the technical capabilities to drive a project forward. And I have seen technical capable communities I would not want to spent five minutes with in a room full of liquor. Django was and still is the … -
Managing state in Django models
A Django model often will contain some form of state. And there will most likely be events which modify the state. While those two things are not always called like this, the concept still exists. More often than not you will find a view controller assigning the new state to an instance of a model when certain conditions are met. In some cases you will see the event code being abstracted to make it easier to test, maybe in a separate function or class, maybe to a model method. And more often than you should you will see this messing up the state of an instance forcing someone to wake up at 2am to connect to the database - or Django admin if setup - and set a valid state. Thankfully the chance for the last thing to happen can be greatly reduced. Over the years I found that not everyone is familiar with the concept of a finite-state machine (which would help addressing this problem). I have also met people who had in depth knowledge of state machines in all their forms and would have been able to implement one as a stand-alone system, but had trouble integrating one … -
Adding two factor authentication to Django admin
As my dissatisfaction with WordPress grew, I did the only Reasonable Thing(tm) and decided to roll out my own CMS again. Which means I do not only have the joy of building a tool exactly fitting my needs, but I also have to build some of the functionality I would expect every production-ready system to provide. Account security in Django's contrib.auth and contrib.admin package did not change a lot over the last decade, but in 2020 I expect some basic functionality from every system, like two factor authentication. As 2FA is missing in Djangos admin package, what is the Reasonable Decision(tm)? To add it myself, of course. You might see a trend of "reasonable yak shaving" here. (A small side note if you are working on a SaaS or web app right now: Account security is not a "premium feature" or a feature your users should have to pay for. It is basic functionality you should always provide to anyone, no matter if they are free or paid users, no matter which plan. And now back to our scheduled program!) This article assumes you have some familiarity with Python and Django; at least enough to create a new application, inherit … -
Thoughts on „Surviving Django“
Daniele, the author of psycopg2, wrote an interesting post about Django and its migration system. Having used Django for well over a decade and having worked on projects either handed to me or greenfield at different scales I cannot agree with his arguments as they are stated. The migration and ORM system does solve a far larger problem than allowing web apps to switch between databases. Djangos migration system is primarily a developer tool. A rather excellent one I cannot praise enough. It abstracts and standardises the way database migrations are handled. Remember following a document outlining the order of 15 migrations to apply when doing a deploy? Remember trying to add a 16th? I surely prefer running makemigrations. Is it perfect? No. Can a talented DBA get far more out of a database? Absolutely. Is any of that more relevant than safeguards and ease of use for 90% of the apps out there? Definitely not. Now to the really good part - you can have the best of both worlds! Migrations can run Python and SQL, while still giving you some of the safeguards and making it comfortable to use. They will not get in your way, but spare … -
Deep dive: Django Q and SQS
When working on a Django application the de facto recommendation for a task queue is Celery. I believe this is a good recommendation. It is kind of like buying IBM - “no one was ever fired for buying IBM”. I started using Django Q more recently and it is doing a great job. One system I built using it processes roughly 400k tasks per day. Surely not the largest system and surely not the most impressive number, but decent enough to say that Django Q is a solid choice. But as with many smaller projects there are sometimes a few gotchas you are running into. This becomes painfully obvious when setting up an app using SQS. Let me walk you through the steps I took to make Django Q play nicely with our AWS setup at Grove Collaborative. Redis is great, but… First of all you have to configure Django Q to use SQS. You do this by adding the Q_CLUSTER dictionary to your settings.py with the sqs key. If you are familiar with AWS and boto3 you might know that you can either provide the AWS region when initialising a new connection or you can have a standard config … -
Deploying Django at small scale
It feels like common knowledge and an accepted fact that you want to run PostgreSQL in production. And have some sort of load balancer to be able to scale your application server horizontally. Throw in Redis for caching and you have the most generic web application stack I can come up with. At scale this makes a ton of sense. It is a battle tested stack, that will most likely not fail you and if it does, there are tons of resources on how to fix it. Those are a lot of moving parts you want to keep updated and maintained, so let us talk about simplifying this stack a bit for small scale deployments. There are lots of resources out there explaining the setup I mentioned above. Those resources are valuable and will guide you through production setups you will see at many places. But what when you are just starting and want to get your first application online? Things can be a lot easier. I recently started moving my blog and photo sharing site to their own, small virtual server. I just blogged about the reason for doing this, so I will not go into detail. Both sites … -
Security 101: Securing file downloads
One of the most common way to handle user uploaded content is persisting the data to disk, or uploading it to an object store like AWS S3. Serving the content back to the user (or others) often is handled by returning the URL to the file. What is oftentimes missing is proper authentication and authorization, as engineers seem to believe no one will leak URLs, run enumeration attacks or simply try random strings. This is not just a data breach waiting to happen, it is one happening way too often. In this post we will look at three options how this can be solved. The examples which you can find in the demo repository are written in Python, using Django. All three should work just fine in basically any modern language and framework used for web development, and with most web servers and reverse proxies such as Nginx. I am using Caddy, as the configuration is concise and simple to follow. For all examples you can upload a file via Django Admin and browse and download the files by visiting /. All examples only check if the user is authenticated. In a real system you will most likely want to … -
Django News - Django security releases issued: 4.1.7, 4.0.10, and 3.2.18 - Feb 17th 2023
News Django security releases issued: 4.1.7, 4.0.10, and 3.2.18 This release fixes a potential denial-of-service vulnerability in file uploads. As always, updating to the latest version of Django is one of the best security measures you can take. djangoproject.com Release 2.0 · django-crispy-forms/django-crispy-forms PSA: django-crispy-forms 2.0 has been released and has a few major changes, which will require some extra time when you upgrade. Their guide can walk you through what is needed or you can pin to django-crispy-forms<2 for a while until you have time to migrate. github.com Dependency graph supports the Python PEP 621 standard | GitHub Changelog GitHub dependency graph now supports parsing Python dependencies for pyproject.toml files that follow the PEP 621 standard. github.blog Sponsored Link Apply Now: Backend Tech Lead for B2B SaaS Startup- Remote Available! Looking for an opportunity to build, lead, architect, and grow — both your career and a great product? Supplios builds supply-chain software for leading manufacturers and is looking for an experienced Python / Django developer to join the team in Copenhagen, Denmark or remote. supplios.com Articles Python/Django AsyncIO Tutorial with Examples An overview of asynchronous coding and how to apply it to Django. djangostars.com An introduction to Django Simple … -
Weeknotes (2023 week 7)
Weeknotes (2023 week 7) iOS and Kiosk mode I did some research on easy ways to put an iPad into Kiosk mode because I want to build a surveying app for an exposition. The web platform is perfect for this especially given the budget constraints… I thought What is iOS kiosk mode and how do I enable it? was a great overview over the available options for using iPads in Kiosk mode. I definitely don’t want to build an app myself even though this would be relatively straightforward e.g. with React Native1. The MDN Foxes example worked nicely apart from the fact that the bar containing the clock and indicators is still shown. This is probably an acceptable trade off, but we’ll see. Bitbucket to GitHub migration I have finally managed to bump against the GitHub API’s rate limit. I have transferred more than 300 private Git repositories from Bitbucket to GitHub. Most repositories aren’t used actively anymore, so it’s not really about GitHub vs. Bitbucket. The goal was simply to have one less tool to worry about. Downloading the list of all repositores in a workspace was surprisingly annoying and I spent too much time bumping my head against … -
django-upgrade release with Django 4.2 fixers
I just released django-upgrade 1.13.0. The headline features are some new fixers targetting Django 4.2, which is currently in alpha. Let’s walk through these new fixers. For more detail on any of them, see the Django 4.2 README section. New headers argument in tests Recent-ish Django versions have added easier mechanisms for reading and writing HTTP headers: Django 2.2 added request.headers. Django 3.2 added response.headers. One place that was still lacking was the test client, where you needed to set headers via their WSGI names: response = self.client.get("/", HTTP_ACCEPT="text/plain") In Ticket #34074 I proposed a new headers argument for the test client and request factory classes. David Wobrock picked up the ticket in October. After a few rounds of review from myself and others, it was merged in November. So from Django 4.2, you can use: self.client.get("/", headers={"accept": "text/plain"}) Much more consistent. After the PR was merged to Django, David got to work on a adding a corresponding fixer to django-upgrade. I just got around to reviewing, fixing, and merging the PR. Thanks David! So now django-upgrade can rewrite client calls using headers: -response = self.client.get("/", HTTP_ACCEPT="text/plain") +response = self.client.get("/", headers={"accept": "text/plain"}) …and instantiations of Client and RequestFactory: from django.test … -
Django 4.2 - Mariusz Felisiak
Mariusz Felisiak Mariusz on Mastodon Django 4.2 release notes - UNDER DEVELOPMENTStandout Features in Django 4.2 DSF calls for applicants for a Django FellowLearnDjango: How to Install Django Support the ShowThis podcast does not have any ads or sponsors. To support the show, please consider purchasing a book, signing up for Button, or reading the Django News newsletter. -
Serving Static Files from Flask with WhiteNoise and Amazon CloudFront
This tutorial shows how to manage static files with Flask, WhiteNoise, and Amazon CloudFront. -
Mercurial Mirror For Django 4.2 Branch
Slightly late, but here’s the 4.2 mirror. As usual, read-only, and aimed at production (aka “using django on servers “), not development (aka “commit”). -
Backend Development 101 with Django REST Framework
If you’re familiar with Python, you’ve most certainly heard of Django, but may not know what it is used for and why people like it so much. We will first run through a ‘backend development 101’ crash-course, then talk about Django’s take on backend development and what Django REST Framework provides on top of it. Finally we will add a feature to an example Django app and do some live coding. -
An introduction to Django Simple History
Wouldn’t it be useful if we could document changes in our life and revisit them later at will? It would allow us to better analyze situations, remember what we were thinking, or help us remember how we got to our current state. Although no such tool currently exists for changes in life, one such tool does exist in Django. It is called django-simple-history. Django-simple-history stores Django model state on every create, update, or delete database operation; it can even revert back to old versions of a model, record which user changed a model, interact with multiple databases, and more. Rather than making code changes, django-simple-history gives us the ability to view and perform many of the changes via the admin interface. Let’s imagine we are creating a simple Polling application and our models.py file looks like this: from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') published = models.BooleanField(default="False") def __str__(self): return self.question How do we get django-simple-history to work on our application? Install django-simple-history: pip install django-simple-history In the settings.py file, Add simple_history to INSTALLED_APPS: INSTALLED_APPS = [ # ... 'simple_history', ] The historical models can track which user made each change. To automatically populate … -
Single-pages without the single-page with django2-tables, django-filter, and htmx
Introduction I've been meaning to use htmx since it came out, but I've never had time, nor the occasion. Now the opportunity finally came to refactor an old Django which uses the Datatable jQuery plugin. I wanted to try something fresh, and htmx seemed the way to go, paired with a couple of great libraries: django2-tables and django-filter. Let's see how they play well together! Please, take this post as personal notes, don't expect a step-by-step tutorial :-) The theory htmx is a JavaScript library for building dynamic user interfaces which lets you enrich HTML elements with "magic" attributes. With htmx, any actionable HTML element can make XHR requests. The magic comes from two htmx attributes: hx-get hx-target hx-get basically says: when the user clicks this element, make a GET request to the given URL, then swap the content of hx-target with the partial response. (POST requests are also supported). The basic principle behind htmx used in the context of server-side web frameworks is the following: if the frontend request comes from htmx, we return a partial HTML fragment instead of the whole document. In Django, this translates to: if the request comes from htmx, we return a partial template … -
Running your Django project with __main__.py
I don’t like Django’s manage.py. My gripes against it are: The plethora of files that clutter the root directory of our repos annoys me. manage.py is just one more in a long line of those. In my opinion, there are more “Pythonic” ways to execute code. In a previous post, I talked about how you can move the code into your project and use packaging tools to create a manage.py on your PATH during installation. In this post, we’ll look at another approach using __main__.py What is __main__.py (and __main__)? The Python docs do a good job of explaining this topic, so I’ll give you the tl;dr here. __main__.py provides a command line interface to a Python package. It can be executed with python -m mypackage. Here are some common ones you may have seen in the wild: python -m pip python -m venv python -m json.tool You may also be surprised to learn that python -m django can be used in place of the django-admin command. 🤯 The “magic” here is that each one of those packages has a __main__.py which defines what it should do when run from the command line. In each of these, you’ll see a … -
Using pyproject.toml in your (Django) project
Back in 2018, I wrote about using setup.py in your Django/Python project. Five years later, setup.py is being phased out in favor of pyproject.toml. I'm a big fan of this change. With setup.py you could really go off the rails making everything dynamic or even executing malicious code during the installation process. In contrast, pyproject.toml moves the ecosystem towards a configuration file that can be parsed without executing arbitrary code. You can read more about the rationale behind pyproject.toml in PEP-517, PEP-518, PEP-621, and PEP-660. Creating your pyproject.toml file If you're using poetry, pdm, or any of the other newer Python build systems, you're already using pyproject.toml. How about folks that are using plain old pip or pip-tools? You can still take advantage of this new file format and ditch setup.py and/or setup.cfg as well. Most third-party tooling supports configuration via the tool section defined in PEP-518. To start, define the build system for your project. To avoid introducing new tools, we're going to use good ol' setuptools: [build-system] requires = ["setuptools>=61.0"] build-backend = "setuptools.build_meta" Next, define your project and its dependencies: [project] name = "myproject" version = "1.0" dependencies = [ "dj-database-url", "django==3.2.*", "gunicorn", "psycopg2", "whitenoise", ] [project.optional-dependencies] dev … -
Django Dev Made Easy: How to Run Multiple Processes Simultaneously
As a Django developer, I have to run multiple processes while developing, such as the Django server, a JavaScript compiler, and Celery. Launching these processes separately can be time-consuming and tedious. Just try opening three terminal windows, and you'll understand what I mean. Finally, I found a solution … Read now -
Django News - Django Fellow Call for Applicants - Feb 10th 2023
News DSF calls for applicants for a Django Fellow After five years as part of the Django Fellowship program, Carlton Gibson is stepping down. There is a new Fellow position available. Please consider applying. djangoproject.com Python 3.11.2 Python 3.11.2 is the newest major release of the Python programming language, and it contains many new features and optimizations. python.org Python 3.11.2, 3.10.10, and 3.12.0 alpha 5 These releases include bugfixes, security releases, and even a new alpha release. blogspot.com Sponsored Link SaaS Pegasus Django-powered SaaS boilerplate for your project. Get a head start and launch faster than you dreamed possible. saaspegasus.com Articles Standout features in Django 4.2 Django Fellow Mariusz Felisiak walks us through some of the more notable features coming in Django 4.2 in early April 2023. fly.io A New Mentorship Program An overview of Caktus Group's Mentorship program. caktusgroup.com What Django Deployment is Really About A high-level look at four overall areas that make Django deployment somewhat challenging. walters.click pre-commit: How to create hooks for unsupported tools Adam Johnson shows us how to use pre-commit for unsupported tools like stylelint and jpegoptim. adamj.eu Events DjangoCon Europe - Call for Proposals Full information is now available on talks at DjangoCon … -
Weeknotes (2023 week 6)
Weeknotes (2023 week 6) Rust I made some progress learning Rust. I don’t have to look up each character and function and am slowly getting a feel for the language, unwrapping and the borrow checker, so that’s nice. I don’t have a use for it for now, but we’ll see. feincms3-data and data cycles I added support for loading data with cyclic dependencies to feincms3-data. This is useful e.g. when having Django models where you have a ForeignKey("self") and you want to use feincms3-data to insert a new copy of some object and its dependencies. Editing trees in the Django administration interface I’m back to one of my favorite (not) activities which is making tree-shaped data editable in the Django administration panel. FeinCMS and later django-mptt augments the changelist with some drag drop behavior. There’s no undo functionality though so making errors is potentially really bad. feincms3 uses a separate page for moving nodes around. Now I’m working on a Preact-based project which also doesn’t use drag drop but which also allows inserting nodes, not just moving nodes around. I doubt I can make it reusable enough to make it useful for feincms3 but we’ll see. -
Documenting Python Code and Projects
This article looks at why you should document your Python code and how to generate project documentation with Sphinx and OpenAPI. -
Deploying a Django App to Google App Engine
This tutorial looks at how to deploy a Django application to Google App Engine. -
Weeknotes (2023 week 5)
Weeknotes (2023 week 5) A long time has passed since I tried writing week notes. Oh well, here we go again. No committment here, just hope. Podcasts Really got into listening to podcasts in the last few weeks. That’s new for me, I never enjoyed listening to people talk when I could also listen to music. So, that’s interesting. Podcasts I like a lot: The Ezra Klein Show, Django Chat and some others where I haven’t yet listened enough to list them here. Advent of Code I knew that Advent of Code existed quite long already but I never dug into it. I participated in the 2022 Advent of Code and enjoyed it a lot. I have long been unsecure regarding my programming skills since I do not have a formal CS background so it felt really good to be able to solve many problems with only a little help. Definitely not all of them though. It definitely was fun and I’m still working through other years a bit. Python is the most fun, JavaScript is sometimes nice. Rust gives me a hard time (or I’m giving myself a hard time) but the upside is that solving even easy puzzles … -
Django News - Django security release for 4.1.6, 4.0.9, and 3.2.17 - Feb 3rd 2023
News Django security releases issued: 4.1.6, 4.0.9, and 3.2.17 The new security release fixes a potential denial-of-service attack. djangoproject.com DjangoCon US 2023 Confirmed It will take place in Durham, North Carolina, at the Durham Convention Center on October 16-20, 2023. More details to come. djangocon.us Articles Python’s “Disappointing” Superpowers Luke Plan's long essay on does Python have Superpowers. lukeplant.me.uk The Django Developer's Guide to Vite An easy way to add JavaScript to your Django projects via Vite, which bills itself as next generation frontend tooling. ctrlzblog.com Django: migrations by choice How to update choice lists in Django models without rolling a migration every time. dev.to Forum django-crispy-forms 2.0a1 - Show & Tell The alpha release for django-crispy-forms is out. This is a widely used package and the maintainers are looking for people to test it out and provide any feedback. djangoproject.com Tutorials Official Django REST Framework Tutorial - A Beginners Guide A 4.1 update to this lengthy beginner-friendly guide to the official Django REST Framework tutorial. Also comes with GitHub repo of the final code. learndjango.com LearnDjango - How to Install Django A beginner-friendly guide to properly installing Django 4.1. It covers the command line, installing Python 3.11, virtual environments, …