Django community: Community blog posts RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Weeknotes (2023 week 11 and 12)
Weeknotes (2023 week 11 and 12) Mail user agents being mail user agents django-authlib is my collection of utilities for implementing passwordless authentication, either using OAuth2 or by sending magic links by email. The latter functionality has existed for a long time in django-registration (which is great!) but I wanted a way to generate links without the need for a storage somewhere. Django has utilities for Cryptographic signing built-in as the django.core.signing module. I’m using this module to send a signed version of the email address to users, and when I’m able to successfully verify the email addresses signature I can be sure (enough) that those links have actually been generated by my code. The form of the generated verification URL is as follows: https://example.com/.../test@example.com:1pXJtx:aypKOlb5zaCg.../; the part before the first colon contains the data-to-be-verified, the short string between colons is the timestamp and the rest is the signature, everything generated by django.core.signing. So far so boring. But then mail user agents happened. Some MUAs insist to butcher the URL in various ways, e.g. by removing the signature or by making only the embedded email address clickable. This is “interesting” behavior and certainly unexpected. Last week I implemented a change where … -
Django: Avoid database queries in template context processors
Django’s template engine allows you to augment template contexts with context processors. These are functions that take the current request and return a dictionary to be merged into the context: from example.models import HotDog from example.models import HotDogState def hot_dog_stats(request): return { "hot_dogs_eaten": HotDog.objects.filter( state=HotDogState.EATEN, ).count(), } You enable context processors by pointing to them in the TEMPLATES setting: TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "OPTIONS": { "context_processors": [ ..., "example.context_processors.hot_dog_stats", ..., ], }, }, ] Django’s startproject template includes a few context processors, such as the one from django.contrib.auth that adds the user and perms variables. Context processors are convenient for adding extra “global variables” to templates. But because they run on every top-level template render, they need to be robust and performant. In particular, avoid running database queries within them. Database queries within a context processor can have at least two negative consequences: Performance impact If a context processor fetches data that is not used when rendering a page, the resources spent fetching the data will have been wasted. Since most sites contain different types of pages, pretty much any query run in a context processor will be wasted on some pages. For example, your Django Admin pages … -
Locomotive Engineer / New Model Field - Building SaaS with Python and Django #156
In this episode, I did another Exercism problem in Python that focused on Python packing and unpacking of arguments. Once the exercise was complete, I started on a new feature with the homeschool app. We added a new model field in preparation for the changes. After that, I removed django-stubs because it wasn’t a good fit for my project. -
Django Performance Optimization Tips
This article looks at where potential performance issues can occur in a Django application and how to address them in order to speed up your app. -
How to Automatically Switch to Rosetta With Fish and Direnv
I love my Apple silicon computer, but having to manually switch to Rosetta-enabled shells for my Intel-only projects was a bummer. -
Locking Down Your Users' Secrets: Django Sessions 101
Django is a powerful and popular web framework that makes it easy to build robust and secure web applications. One of the key features of Django is its ability to manage user sessions, which are essential for many web applications. However, you may be wondering if Django sessions are secure. In this article, we’ll explore the security of Django sessions and see how they can be made even more secure. -
Django News - DjangoCon US 2023 Preview - Mar 17th 2023
Sponsored Link Meet Wagtail, the #1 Django-powered CMS 100% open source. Powered by Python & Django. Built for editors and developers with excellent documentation. Trusted by Google, NASA and hundreds of thousands of organisations around the world. bit.ly Articles How virtual environments work A comprehensive look at how virtual environments work to help demystify them. snarky.ca Time Travel with django-simple-history A closer look at django-simple-history, a third-party Django package that provides model version control, including who made the change, when it was made, and the difference. mattlayman.com Marketing for Developers A reasonably comprehensive list of steps one can take for their projects to get more visibility. alldjango.com How migrate an existing Joomla CMS website to a Django Backend Migrating a Joomla based website to a Django Backend with 90 Gb worth of data. adonissimo.com Caching and Django Rest Framework How and when to cache a Django API, as well as advice for when NOT to. screamingatmyscreen.com Design Articles An end to typographic widows on the web Currently shipping in Chrome Canary, and thus soon to be in Blink-based browsers, including Edge, is a relatively new CSS declaration that promises to end typographic widows virtually. clagnut.com Sponsored Ad Upgrade Django Upgrade … -
Django: Parameterized tests for all model admin classes
Here’s an application of “test smarter, not harder”, as per Luke Plant’s post. I came up with this recently whilst working on my client Silvr’s project, and I’m pretty proud of it. It should apply to any project using Django’s admin. When you declare a Django ModelAdmin class, the built-in system checks ensure that various attributes are well-defined, using the right data types and values. But they can’t cover everything, because there is so much flexibility. So it’s possible to have, for example, a bad field name in search_fields. You can ensure that a ModelAdmin class works properly by writing tests to load its various views. But rather than write individual tests, you can “push down the loop”, and write parameterized tests that run on every ModelAdmin. The below code tests all model admins’ “changelist” and “add” pages. It’s all generic, so you should be able to copy-paste it into most Django projects without modification. from __future__ import annotations from collections.abc import Callable from http import HTTPStatus from typing import Any from django.contrib.admin.auth.models import User from django.contrib.admin.sites import AdminSite from django.contrib.admin.sites import all_sites from django.db.models import Model from django.test import TestCase from django.urls import reverse from parameterized import param from … -
Cater Waiter, Template Bugs, and Type Fixes - Building SaaS with Python and Django #155
In this episode, I did another Exercism problem in Python that dug into Python sets. Once the exercise was complete, we went back to the issue list. I debugged and fixed a template error, the spent time improving types with my Django app. -
DjangoCon US 2023 - Drew Winstel
Drew’s Personal Site@drewbrew on Mastodon and https://takahe.social/@drewDjangoCon US 2023 and on GitHubDjango Events Foundation North America (DEFNA)Drew’s 2018 DCUS talkDCUS call for volunteersSponsor DCUS 2023 https://thenounproject.com/icon/dumpster-fire-4367573/HSV.beer, on Instagram and on GitHubDrunk: How We Sipped, Danced, and Stumbled Our Way to CivilizationEast Coast GreenwayAmerican Tobacco Trail 14 miles paved, 22 total; directions from the hotel to the trailheadSupport 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. -
Caching and Django Rest Framework
One of my current projects involves an API. Not surprising in the year 2023. During business hours data is primarily read. Payloads are large and the underlying data model is as complex as it needs to be. Lots of data and a complex data model is usually a good way to make sure your API is slow. And this project was no exception. While there are many different ways how you can approach this, I opted for the one with the smallest change to the codebase possible and the least amount of change required in the existing infrastructure. Let us start with a small list of reasons why this approach made sense for this particular project. I would not advocate using it as a general design pattern every time you run into performance issues. Data is mostly refreshed during night time. There might be four or five manual edits during day time for every 100,000 entities stored. The project is still in its early MVP / prototyping phase. Not introducing additional service requirements simplifies deployment and workflows. The API is read only. Not introducing additional services and hunting data through different data stores also means debugging potential issues is simple. … -
Sync or Async? Unpacking the Mysteries of Django Signals
Django is a popular web framework for Python developers, known for its robustness, flexibility, and security. One of the features that make Django powerful is its signal system. Signals allow developers to trigger certain actions when specific events occur, such as when a model is saved or deleted. However, there is often confusion about whether Django signals are asynchronous or not. In this article, we will explore this question and discuss the tradeoffs associated with using Django signals. -
Time Travel with django-simple-history
If you’re interested in Django development, you might have come across the django-simple-history package. It’s a great tool that can help you keep track of changes made to your models over time. In this article, we’ll take a closer look at django-simple-history and how it can benefit your projects. What is django-simple-history? django-simple-history is a third-party Django package that provides version control for your models. It allows you to keep track of changes made to your models, including who made the change, when it was made, and what the change was. -
Learn Django or Ruby on Rails?
I got a question from a patron on Patreon. The question is a common one, so I thought I’d share it along with my response. Was there a reason why you picked the Django for your web development? Did you consider RoR? Does it matter which stack I use at the end of the day? My primary reason for getting into Django was twofold. First, I’ve been working with Python for a long time and have a lot of comfort with the language. -
Django News - Django Developers Survey 2022 Results - Mar 10th 2023
News Django Developers Survey 2022 Results The results of the 2022 Django Developers Survey are now live. Almost 5,000 Django users from 248 countries took the survey. djangoproject.com Python Insider: Python 3.12.0 alpha 6 released Python 3.12.0a6 is the sixth of seven planned alpha releases. Alpha releases are intended to make testing the current state of new features and bug fixes easier. Today is a good time to start testing your code with Python 3.12. blogspot.com Sponsored Link Get Expert Developer Support from the creators of Wagtail CMS Get support for your developers from our team of Wagtail experts: from reviewing your Wagtail set-up and planning complex features, to code reviews, pair programming and more. We offer a range of plans, special pricing for charities and universities, and profits are invested in Wagtail product development. bit.ly Articles Django: How to profile and improve startup time A post on several tools for profiling startup time and tactics for reducing it. adamj.eu More Batteries Please Django Fellow Carlton Gibson with some thoughts on how/why to bring more official batteries into Python. noumenal.es Testing multiple Python versions with nox and pyenv If you need to test your code against multiple versions of Python … -
Weeknotes (2023 week 10)
Weeknotes (2023 week 10) FeinCMS bugs FeinCMS is really stable (since there isn’t much going on) but this week a Django upgrade surfaced bugs in the datepublisher extension. The extension uses a granular_now utility to determine if a page should be shown or not; the time is rounded to a 5-minute boundary which makes some sorts of caching more effective. On one hand it’s a bit sad that activity on the project has practically ground to a halt, on the other hand it’s great that the project requires practically no changes when a new version of Django is released. Stability is awesome. 15 years of using GitHub I used Subversion and darcs for probably not much more than a year each before discovering Git probably some time in spring 2006. It was a very archaic version with a much worse CLI than today. Everything was archaic, not just the CLI itself but also the repository browsers and the various web UIs. But everything was also very interesting to me. I especially found the emphasis on clean data structures instead of code very inspiring. And here we are, basically all the tools have been rewritten but the commits from back then … -
Go live checklist for your Django project
Launching a website can be an exciting but nerve-wracking experience. With so many moving parts in the website development process, it’s easy to overlook small details that can significantly impact the user experience. To help you avoid potential issues, we’ve compiled a checklist of things to verify before your site goes live. Here it is an opinionated production checklist that is tailored to a high-traffic website (100k Requests per day and above). Django settings Django DEBUG = False Django SESSION_ENGINE = django.contrib.sessions.backends.cached_db or django.contrib.sessions.backends.signed_cookies Django ALLOWED_HOSTS is set to match your domain Django CACHES should use either memcached or redis backend Verify Django the value of settings.DEFAULT_FROM_EMAIL Static files are not served by Django Server configuration & checks Confirm that you have multiple instances of your web application. Verify the output of manage.py check --deploy directly on the production server Error and exception are logged into SENTRY UWSGI Harakiri timeout --harakiri=10 Check that logger.error(…) and logger.info(…) is sent to your logging pipeline Verify that your production dashboard has information about Load and balancer request per minute 2XX, 3XX, 4XX, 5XX AVG and p99 response time for your web application database CPU load and transaction per minute Confirm that you have … -
Django News - DjangoCon US 2023 CFP is open - Mar 3rd 2023
News DjangoCon US 2023 Call for Proposals (CFP) is open! Submit your proposal by May 15, 2023 and encourage your friends and colleagues to do the same. djangocon.us Sponsored Link Register for Python Web Conf Today! Join Djangonauts from around the world for the 5th annual Python Web Conference (March 13-17). Tickets include 5 days, 65+ live talks, expert-led tutorials, social events, an exclusive pass to all conference recordings for 90 days, cool swag and more. Don’t wait, buy your ticket today! pythonwebconf.com Articles Formatting Gone Wrong Using black to format your Python code is usually a good idea but can sometimes cause unexpected errors. A case study on when this happens in Django around API keys. revsys.com Python is two languages now, and that's actually great A look at how both untyped and typed Python are used these days. threeofwands.com Single host Django and Docker deployment A good starting point for a "minimum viable deployment strategy" with new Django projects. screamingatmyscreen.com Using pyproject.toml in your (Django) project How and why to use pyproject.toml in your Django projects instead of older options like setup.py. lincolnloop.com Django: How to profile and improve startup time Adam Johnson shows us to profile and … -
Weeknotes (2023 week 8 and 9)
Weeknotes (2023 week 8 and 9) Last week was a short work week. We spent a few nights in the mountains. Not much snow though. Enough for some skiing and sledging. This work week was … not normal. Many meetings, not enough time to work on projects. That shortens these week notes a lot. Django Software Foundation membership I found out through Tim that I have been approved as an individual member of the Django Software Foundation. I’m honored and hope that this will be another way where I can give something back. It also feels good to be seen. I didn’t even know that the Foundation’s meeting minutes were public. I still use RSS and can wholeheartedly recommend The Old Reader (no affiliation) and so I thought I’d try adding a RSS feed of meeting minutes to the website. The pull request is still being reviewed. at the time of writing. feincms3-forms documentation I worked on the feincms3-forms README a bit. The README hopefully clarifies the purpose and the components of the app a bit. This is an extremely flexible forms builder for the Django admin interface. Migrating from Bitbucket to GitHub I have been a long time Bitbucket … -
Django: How to profile and improve startup time
Your Django project’s startup time impacts how smooth it is to work with. Django has to restart your project every time you run a management command and when runserver reloads. This involves importing all your apps, and thus all the modules that they import. As you add more code and dependencies to your project, you may notice its startup time increasing. Development can slow down to a crawl; reports of 10 second startup times are, sadly, not unusual. In this post we’ll cover tools for profiling startup time, and tactics for reducing it. How to profile startup time Here are several tools for profiling startup time. -X importtime: Python’s import profiler Python 3.7 introduced the -X importtime option, a specialized profiler that times all imports. It prints a table to stderr, summarizing microsecond timing information for each imported module: $ python -X importtime -c 'import django' import time: self [us] | cumulative | imported package import time: 136 | 136 | _io import time: 20 | 20 | marshal import time: 256 | 256 | posix import time: 261 | 672 | _frozen_importlib_external ... import time: 499 | 6898 | subprocess import time: 309 | 309 | weakref import time: … -
Inventory Management / Custom 404 page / Go gqlgen - Building SaaS #154
In this episode, I did another Exercism problem in Python which focused on working with dictionaries. Once the exercise was complete, we worked on the homeschool app and created a custom 404 page so that Django would render something beyond a plain page. After working on Django, I did something totally different and worked on some Go code and used gqlgen to create a GraphQL service with generated code produced via a GraphQL schema. -
Dev Environments - Calvin Hendryx-Parker
Python Web Conference 2023 - early bird tickets get 15% off with sponsor code DjangoChat@PWC2023Calvin Hendryx-Parker on GitHubSix Feet UpApache Airflow and DAGsToo Big for DAG Factories?Choose Boring TechnologyskaffoldPyCon US 2022 Talk: Bootstrapping Your Local Python EnvironmentPyCon Italia 2023How 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. -
Deploying a Django App to Azure App Service
This tutorial looks at how to deploy a Django application to Azure App Service. -
Single host Django and Docker deployment
One of the best ways to deploy a Django project while maintaining some sanity is Docker. A single, beefy VM or bare metal host will likely bring you a long way when just starting a new project or while working on a side project that does not have to scale to infinity and beyond. Usually you build a Docker image, upload it to a container registry and deploy from the registry. This results in a few more moving parts than I am okay with for a quick side project or something small (like this blog). For this to work you either run a container registry yourself, or trust a third party with keeping your images secure and private. One requires trust in third parties, the other means more work and time for something you can spend on more fun things like your actual project. So let us skip this step. I am using this blog as an example. In the spirit of staying true to "tech quips" I will use an early, working iteration of the deployment script. I will add some notes at the bottom what you should consider doing and what I already changed. The Dockerfile itself is … -
Django News - Django 4.2 beta 1 released - Feb 24th 2023
News Django 4.2 beta 1 released Django 4.2 beta 1 is now available. It represents the second stage in the 4.2 release cycle and is an opportunity for you to try out the changes coming in Django 4.2. djangoproject.com Google Summer of Code: Django 2023 Django was once again selected for Google's Summer of Code this year. This program has directly led to real improvements in frameworks over the year. You can learn more about mentorship and applying (applications open until April 4) on the Django website. withgoogle.com Django Software Foundation DSF Board monthly meeting, February 8, 2023 Did you know the DSF Board minutes are public and hosted every month? Take a look to see what the Board is workingon. djangoproject.com Sponsored Link Register for Python Web Conf Today! Join Djangonauts from around the world for the 5th annual Python Web Conference (March 13-17). Tickets include 5 days, 65+ live talks, expert-led tutorials, social events, an exclusive pass to all conference recordings for 90 days, cool swag and more. Don’t wait, buy your ticket today! pythonwebconf.com Articles Hypermedia Systems Hypermedia Systems is an in-progress book that employs a more straightforward approach to building applications on the Web and beyond …