Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Django Session-based Auth for Single Page Apps
This article looks at how to add session-based authentication to a Single-Page Application (SPA) powered by Django and React. -
Wagtail modeladmin and a dynamic panels list
Wagtail has the modeladmin module in contrib which allows you to edit any Django model through the Wagtail admin interface. Unfortunately it's not very flexible, the code calls the get_edit_handler method on the admin class and the panels property of the model can only be a list. In one project I have a base model that many other models are derived from and wanted to build the panels dynamically. The code below shows how I did it. I chose to break the Wagtail convention and defined the admin fields on the admin class, but I get the additional fields from the model itself. It's somewhat messy, but it's my mess. Raw from wagtail.admin.edit_handlers import FieldPanel from wagtail.admin.edit_handlers import MultiFieldPanel from wagtail.admin.edit_handlers import ObjectList from wagtail.contrib.modeladmin.options import ModelAdmin class DynamicPanelMixin: def get_edit_handler(self, instance, request): return ObjectList(self._get_panels(instance)) def _get_panels(self, instance): return [ *self._get_head_panels(instance), MultiFieldPanel( self._get_multi_panels(instance), heading="Collapsed", classname="collapsible collapsed", ), ] def _get_head_panels(self, instance): panels = [ FieldPanel("foo"), ] return panels + getattr(instance, "head_panels", []) def _get_multi_panels(self, instance): panels = [ FieldPanel("bar"), ] return panels + getattr(instance, "multi_panels", []) # class MyModelAdmin(DynamicPanelMixin, ModelAdmin): # pass -
Introducing django-version-checks
It can be tricky to ensure all the environments that your project runs on use the same versions of Python, PostgreSQL, and other external dependencies. Often development, CI, and cloud environments have different configuration systems, making them hard to keep in sync. And coordinating between all your team members to upgrade their local environments can be complicated, as upgrade emails or instant messages get forgotten if they are away on holiday, working on other projects, etc. And using the wrong versions of external dependencies can lead to hard-to-debug errors, wasting time to find such a simple fix. I’ve solved this problem several times on different projects over the years with custom Django system checks. These can tell you early in Django’s startup process the environment has the incorrect versions. Today I’ve released a package containing configurable versions of such checks, django-version-checks. You activate the checks by specifying the allowed versions in PEP 440 specifiers, the same format that pip uses.s For example, imagine you are using the cutting-edge versions of Python and MariaDB. To ensure all environments use these versions, or compatible bug fix releases, you can install django-version-checks and add this to your settings file: VERSION_CHECKS = { "mysql": … -
Django News - Issue 53 - Dec 11th 2020
News 2021 DSF Board Election Results Thank you to our outgoing DSF Board Members: Frank Wiles (President), James Bennett (Secretary), and Sayantika Banik. We appreciate your years of service to the community. The 2021 returning Board of Directors are Anna Makarudze (Vice President/President-elect), William Vincent (Treasurer), Kátia Nakamura, and Aaron Bassett. New board members are Žan Anderle, Mfon Eti-mfon, and Chaim Kirby. djangoproject.com Wagtail 3rd Party Packages A new dedicated home for Wagtail 3rd party packages. Learn more in the official blog post documenting the move. wagtail.io Python 3.9.1 is now available, together with 3.10.0a3 and 3.8.7rc1 Python 3.9.1 is the first version of Python to support macOS 11 Big Sur natively on Apple Silicon. blogspot.com Python Software Foundation News: Announcing the PSF Diversity and Inclusion Work Group blogspot.com Events PyCascades Grant application opens! If you would like to attend the conference but do not have the funds to purchase a ticket, the application deadline is December 19, 2020 (AoE). pycascades.com Articles Exhaustiveness Checking with Mypy by Haki Benita Haki Benita walks us through exhaustiveness checking with mypy. hakibenita.com How To Set Up Tailwind CSS In Django On Heroku A step-by-step guide to configuring Tailwind on a Heroku-hosted Django app. … -
Introducing django-linear-migrations
If you’ve used Django migrations for a while, you may be familiar with this message: $ python manage.py migrate CommandError: Conflicting migrations detected; multiple leaf nodes in the migration graph: (0002_longer_titles, 0002_author_nicknames). To fix them run 'python manage.py makemigrations --merge' This appears when the migration history for one of your apps branched to have two “leaf nodes”, that is, two final migrations. The simplest example has our first initial migration, then two conflicting second migrations: +--> 0002_author_nicknames / 0001_initial +--| \ +--> 0002_longer_titles This happens quite naturally when developing two features for same app, both with migrations. The solution Django suggests is to create a merge migration with makemigrations --merge. This creates another migration in our history that depends on the last two: +--> 0002_author_nicknames +-+ / \ 0001_initial +--| |--> 0003_merge \ / +--> 0002_longer_titles +----+ This merge migration tells Django “it’s fine to run both branches of migrations and end up here”. This is a simple solution, and avoids modification of the exisiting migrations. But it has a number of drawbacks. First, it’s a fix after the fact. You need to encounter the “Conflicting migrations detected” error before you step in and create the merge migration. This is … -
Customer Feedback - Building SaaS #82
In this episode, I worked on feedback from my primary customer. We fixed a couple of issues that she reported, then moved on to more of the onboarding flow. Before getting to the code, we chatted about ways to learn to code. I linked to a popular book, Automate the Boring Stuff with Python, and some good web tutorials for learning Django. The first bit of customer feedback that I worked on was to add a back link from a course details to get a user back to the grade level that holds the course. -
Jazzband - Matthias Kestenholz
Matthias’s Personal SiteJazzband on GitHubfeincms may still be relevantOfficial Django MerchandiseFeinheitMatthias on Githubfeincms3Official Django merchandiseSupport the ShowThis podcast is a labor of love and does not have any ads or sponsors. To support the show, consider purchasing or recommending a book from LearnDjango.com or signing up for the free weekly Django News newsletter. -
Maps with Django (part 1): GeoDjango, SpatiaLite and Leaflet
A quickstart guide to create a web map with the Python-based web framework Django using its module GeoDjango, the SQLite database with its spatial extension SpaliaLite and Leaflet, a JavaScript library for interactive maps. -
Exhaustiveness Checking with Mypy
Mypy is an optional static type checker for Python. It's been around since 2012 and is gaining traction even since. One of the main benefits of using a type checker is getting errors at "compile time" rather than at run time. Exhaustiveness checking is a common feature of type checkers, and a very useful one! In this article I'm going to show you how you can get mypy to perform exhaustiveness checking! Playing cards are also useful for explaining enumeration types...Photo by Daniel Rykhev Table of Contents Exhaustiveness Checking Enumeration types Type Narrowing in Mypy The Future Bonus: Exhaustiveness Checking in Django Exhaustiveness Checking Say you have a system to manage orders. To represent the status of an order, you have the following enum: import enum class OrderStatus(enum.Enum): Ready = 'ready' Shipped = 'shipped' You also have the following code to process an Order: def handle_order(status: OrderStatus) -> None: if status is OrderStatus.Ready: print('ship order') elif status is OrderStatus.Shipped: print('charge order') When the order is ready, you ship it; and when it's shipped, you charge it. A few months go by and your system becomes big. So big in fact, that you can no longer ship orders immediately, and you … -
A Vue.js workflow for Django
Pairing JavaScript tooling like Vue CLI and create-react-app with traditional frameworks like Django is notoriously hard. There isn't a "right way" to do this stuff, but thanks to Vue.js configurability you can at least choose where to put the resulting bundle. In the following notes I present a Vue.js workflow for Django which I found out working well for most use cases. Configuring Vue.js Suppose you have a Django app named billing, and you want to make the frontend of this app a single-page. You also want to serve this single-page from within Django's umbrella to use Django built-in authentication. First off, we generate a Vue project inside the app with Vue CLI, let's say in repo-root/billing/billing_spa Then, we set up vue.config.js, in the same Vue project folder, with the following configuration: const path = require("path"); const outputDir = path.resolve(__dirname, "../static", "billing"); module.exports = { publicPath: process.env.VUE_APP_STATIC_URL, outputDir, indexPath: path.resolve( outputDir, "../../templates/", "billing", "index.html" ) }; With this configuration we say to Vue: put static assets inside billing/static/billing put the index.html inside billing/templates/billing Django is highly configurable in regard to static files and template structure, but this setup respects Django expectations on where to find static files and templates. Your … -
How To Set Up Tailwind CSS In Django On Heroku
How can you set up Tailwind CSS for your Django app on Heroku? In this article, we’ll see how I did exactly that recently. I have a side project that uses Tailwind CSS. To get started quickly, I used the version from a Content Delivery Network (CDN) as Tailwind describes in the documentation. This worked fine initially while I got my project started, but the CDN version is huge (around 3MB). -
Django News - 🎂 Django News Newsletter turns one-year-old! - Dec 4th 2020
Introduction Django News Newsletter feedback This newsletter turns one year old this week. We (Jeff & Will) would like feedback on what you like and what could be improved for year #2. Please take a moment to respond on either the Django Forum or the Google Form. djangoproject.com News Django bugfix release: 3.1.4 The 🥧 release is out with 7 different bugfixes. djangoproject.com Pip 20.3 Release (heads-up for potential disruption) The pip we have been warning you about for six months is out and you will more than likely run into a few issues. python.org Help share the future of Django Girls Django Girls is looking for advisory board members for 2021. djangogirls.org Rebuilding the PSF - Q4 2020 Fundraiser The Python Software Foundation is running its Q4 fundraiser and is raising money to offset any potential 2021 revenue shortfalls. python.org Events Announcing PyCon US 2021 PyCon US goes virtual again for 2021. blogspot.com Articles Don't Panic: Kubernetes and Docker tl;dr Docker will still run in your Kubernetes cluster. kubernetes.io Django Best Practices: Referencing the User Model There are 3 different ways to access the built-in User model. This post covers each method with recommendations on the best approach. learndjango.com … -
Finishing Onboarding - Building SaaS #81
In this episode, I completed the last form that completes the last step on my Django app’s onboarding process. We built up the view, wrote the tests, and worked through the templates changes. I started with a discussion of what the onboarding flow does and what was left. I needed to make a form that creates a task for a course. For the first chunk of code, we added some tests to cover all the scenarios that are important for the view. -
Django: Change or translate the app name in the admin menu
Let’s say I have a Django app users. The admin menu shows this as category Users. That’s ok, but if the website users speak another language I want this name translated. Also I’m not necessarily using Users as name in the admin menu as section name, but can use something more descriptive. Website Users, as example. -
Finding Performance Issues In Python Web Apps with Sentry
Introduction Earlier, we have seen couple of articles here on finding performance issues1 and how to go about optimizing them2. In this article, lets see how to use Sentry Performance to find bottlenecks in Python web applications. The Pitfalls A common pitfall while identifying performance issues is to do profiling in development environment. Performance in development environment will be quite different from production environment due to difference in system requirements, database size, network latency etc. In some cases, performance issues could be happening only for certain users and in specific scenarios. Replicating production performance on development machine will be costly. To avoid these, we can use APM tool to monitor performance in production. Sentry Performance Sentry is widely used Open source error tracking tool. Recently, it has introduced Performance to track performance also. Sentry doesn't need any agent running on the host machine to track performance. Enabling performance monitoring is just a single line change in Sentry3 setup. import sentry_sdk sentry_sdk.init( dsn="dummy_dsn", # Trace half the requests traces_sample_rate=0.5, ) Tracing performance will have additional overhead4 on the web application response time. Depending on the traffic, server capacity, acceptable overhead, we can decide what percentage of the requests we need to … -
Exhaustiveness Checking with Mypy
Mypy is an optional static type checker for Python. It's been around since 2012 and is gaining traction even since. One of the main benefits of using a type checker is getting errors at "compile time" rather than at run time. Exhaustiveness checking is a common feature of type checkers, and a very useful one! In this article I'm going to show you how you can get mypy to perform exhaustiveness checking! Playing cards are also useful for explaining enumeration types...Photo by Daniel Rykhev Table of Contents Exhaustiveness Checking Enumeration types Type Narrowing in Mypy The Future Bonus: Exhaustiveness Checking in Django Exhaustiveness Checking Say you have a system to manage orders. To represent the status of an order, you have the following enum: import enum class OrderStatus(enum.Enum): Ready = 'ready' Shipped = 'shipped' You also have the following code to process an Order: def handle_order(status: OrderStatus) -> None: if status is OrderStatus.Ready: print('ship order') elif status is OrderStatus.Shipped: print('charge order') When the order is ready, you ship it; and when it's shipped, you charge it. A few months go by and your system becomes big. So big in fact, that you can no longer ship orders immediately, and you … -
How to create a celery task that fills out fields using Django
Hi everyone! It’s been way too long, I know. In this oportunity, I wanted to talk about asynchronicity in Django, but first, lets set up the stage: Imagine you are working in a library and you have to develop an app that allows users to register new books using a barcode scanner. The system has to read the ISBN code and use an external resource to fill in the information (title, pages, authors, etc. -
How to create a celery task that fills out fields using Django
Hi everyone! It’s been way too long, I know. In this oportunity, I wanted to talk about asynchronicity in Django, but first, lets set up the stage: Imagine you are working in a library and you have to develop an app that allows users to register new books using a barcode scanner. The system has to read the ISBN code and use an external resource to fill in the information (title, pages, authors, etc.). You don’t need the complete book information to continue, so the external resource can’t hold the request. How can you process the external request asynchronously? 🤔 For that, we need Celery. What is Celery? Celery is a “distributed task queue”. Fron their website: > Celery is a simple, flexible, and reliable distributed system to process vast amounts of messages, while providing operations with the tools required to maintain such a system. So Celery can get messages from external processes via a broker (like Redis), and process them. The best thing is: Django can connect to Celery very easily, and Celery can access Django models without any problem. Sweet! Lets code! Let’s assume our project structure is the following: - app/ - manage.py - app/ - __init__.py … -
Django: Remove default entries from admin menu
The Django administration site comes with a couple of default entries, depending on which apps and middleware is installed. -
How To Use Linode's Object Storage For Staticfiles
Recently Linode has released an alternative to AWS's S3 object storage service, called Object Storage. It uses a similar S3 architecture to AWS's offering, albeit with a much more simplified ... -
Cyber Monday discount for Speed Up Your Django Tests
Earlier this week I tweeted about my two part offer on my book Speed Up Your Django Tests for this year’s Cyber Monday. Firstly, I’m offering a 50% discount on the book during the day. This will last whilst it’s the 30th November “Anywhere on Earth” (AoE), so as long as there’s one time zone where it’s Monday the 30th November, you can get that discount. The deal will stack with the regional discount that offers a 50% discount for those living outside the GDP top 50. If you live in such a country, email me to get a total of 75% off the list price. Secondly, to promote the deal, I’m giving away a free copy of the book to someone who retweets that tweet. I’ll do the draw at 09:00 UTC on Monday and announce it in the comments on Twitter. Buy it on Gumroad! If you’re looking for other deals on Python and Django learning materials, check out Trey Hunner’s post that compiles many offers available. I’m a subcriber to his Python Morsels and can attest to their quality for teaching you the breadth of features in Python. -
Django News - Final week of DSF Nominations - Nov 27th 2020
News 2021 DSF Board Nominations Nominations are open until November 30th for next year's Django Software Foundation board. djangoproject.com Events Pyjamas 2020 - December 5th, 2020 24 hours streaming of talks about Python and connecting with Python communities around the world that you can access at home. pyjamas.live Articles Migrating to a Custom User Model mid-project in Django A nice summary of the steps needed to migrate to a custom user model mid-project. rasulkireev.com The trouble with transaction.atomic by David Seddon Does Django's transaction.atomic trip you up? Us too. seddonym.me Django Best Practices: Models How to properly define and structure your Django models. learndjango.com Unravelling `not` in Python Brett Cannon deep dives into how the not operator works in Python. snarky.ca Django: Testing for Missing Migrations A short pytest test for missing migrations. Probably useful in every Django project. birdhouse.org Evolution of a Django Repository pattern An 18-step walkthrough of a sample Django repository. lukeplant.me.uk PostgreSQL Benchmarks: Apple ARM M1 MacBook Pro 2020 If you are curious how PostgreSQL performs on Apple Silicon chips then here you go. crunchydata.com The hidden Django anti-pattern preventing your prod rollback Hopefully, you won't need to rollback your migrations in production, but if you … -
Episode 10 - User Auth
On this episode, we’re going to look at working with users in a Django project. We’ll see Django’s tools for identifying users and checking what those users are permitted to do on your website. Listen at djangoriffs.com. Last Episode On the last episode, I explained the structure of Django application. We also talked why this structure is significant and how Django apps benefit the Django ecosystem as a tool for sharing code. -
User Auth
Full show notes are available at https://www.mattlayman.com/django-riffs/10. -
Django: disable inline option to add new referenced objects
The Django Web Framework makes it quite easy to add new referenced objects in the admin menu.