Django community: RSS
This page, updated regularly, aggregates Community blog posts from the Django community.
-
Create a Dark Mode hook in React.js
I love dark mode. It's definit... -
Backporting a Django ORM Feature with Database Instrumentation
Last week I covered Django’s database instrumentation, and making a wrapper that’s always installed. Here’s a different use case that I encountered last year on a project. I was helping optimize query patterns for a model - let’s call it Book. An import function used a loop to import new model instances based on a unique title field: for title in titles: Book.objects.get_or_create(title=title, defaults=...) This function took several seconds as it inserted several hundred records, required for the project to work. This was particularly noticeable at the start of tests. (Surprise, this is also a test optimization story!) We can speed up such an import with the QuerySet.bulk_create() method, passing ignore_conflicts=True. This method inserts a list of instances into the database in as few queries as possible (as little as one). The ignore_conflicts=True option skips any instance that conflicts with a unique or primary key constraint: Book.objects.bulk_create( [Book(title=title, ...) for title in titles], ignore_conflicts=True, ) This is a great solution, but unfortunately it wasn’t available. The client’s project was on Django 2.0 at the time and the ignore_conflicts argument to bulk_create() was only added in 2.2. Upgrading Django would be a rather large yak shave. Instead, I decided to backport … -
Django, Docker, and PostgreSQL Tutorial
In this tutorial we will create a new Django project using Docker and PostgreSQL. Django ships with built-in SQLite support but even for local development you are better off using … -
Django-allauth Tutorial
Django comes with a robust built-in authentication system for users but it does not provide support for third-party (social) authentication via services like Github, Gmail, or Facebook. Fortunately, the excellent … -
Django Rest Framework Tutorial: Todo API
[Django Rest Framework](http://www.django-rest-framework.org/) is a powerful library that sits on top of existing Django projects to add robust web APIs. If you have an existing Django project with only models … -
Official Django REST Framework Tutorial - A Beginners Guide
This is a beginner-friendly guide to the official Django Rest Framework [tutorial](http://www.django-rest-framework.org/tutorial/1-serialization/). If you have struggled to complete the official tutorial on your own, consider this guide a good place … -
How to Modernize a Django Index Definition with Zero Downtime
If you’ve read the Django documentation for Model.Meta.index_together recently, you may have noticed this note: Use the indexes option instead. The newer indexes option provides more functionality than index_together. index_together may be deprecated in the future. Django historically provided index control for a single field with Field(db_index=True), and for multiple fields in Meta.index_together. These are good for specifying indexes for one or more fields, but they don’t give you access to the full power of database indexes. The Meta.indexes option was added in Django 1.11 (2017) to allow use of more index features through the Index() class. Initially Index() added support for indexes with descending ordering. It now supports db_tablespace to control storage, opclasses to use PostgreSQL’s various operator classes for indexes, and condition to create partial indexes that don’t contain every row. “Upgrading” So, how do you “upgrade” from Field(db_index=True) or Meta.index_together to Meta.indexes? Well first, this isn’t necessary. Neither feature is actually deprecated, and they’re not likely to be either. If you have an old project using either Field(db_index=True) or Meta.index_together, you’re best leaving it in place and using indexes for new indexes. But this change is a good example of how to make a “zero downtime” migration, … -
How to manage logs with Django, Gunicorn and NGINX
So you want to run a Django app using NGINX and Gunicorn. Did you notice that all three of these tools have logging options? You can configure Django logging, Gunicorn logging, and NGINX logging. You just want to see what's happening in your Django app so that you can fix … -
Cool! I'm going to use it as a base for the article `Create and Deploy Django Server to the GKE`.
Cool! I'm going to use it as a base for the article `Create and Deploy Django Server to the GKE`.Haha. -
Django News - Django Turns 15 and New Releases! - Jul 24th 2020
News Django's 15th Birthday Somehow we missed this last week, but July 17th, 2005 was the public introduction of Django. Here is co-creator Simon Willison's initial blog post. As well as a 2015 talk on Django origins. simonwillison.net Django 3.1 Release Candidate This is the final chance to try 3.1 features before the release on August 3rd. djangoproject.com Python 3.8.5 and 3.9.0b5 released Python 3.8.5 released as a security hotfix. 3.9.0b5, the last beta before 3.9.0, also available blogspot.com Wagtail 2.9.3 and 2.7.4 released Wagtail 2.9.3 and 2.7.4 were released to prevent an HTML injection through form field. github.com Articles XSS Exploitation in Django Applications Anthony Shaw covers various ways to exploit the Django templating engine in a modern web application. github.io Disable Instrumentation Packages during Tests by Adam Johnson Performance tips around instrumentation like django-debug-toolbar and others that can be disabled for tests. adamj.eu Update Django template fragment caches in the background Nicolas Kuttler refactors some code that uses Django's template fragment caching to use low-level cache API. kuttler.eu What is Django (Python)? A beginner-friendly overview of Django. learndjango.com My GPG setup for developing and more If you aren't digitally signing your Git commits then this article is for … -
Is Django too slow?
Does Django have "bad performance"? The framework is now is 15 years old. Is it out of date? I mean, look at these benchmarks: NodeJS/Express is consistently getting better numbers than Django. If you are learning Django in 2020 then you might be worried that you're wasting time with … -
How to make your Django project easy to move and share
You need your Django project to be portable. It should be quick and easy to start it up on a new laptop. If it isn't portable, then your project is trapped on your machine. If it gets deleted or corrupted, then you've lost all your work! This issue comes up … -
Speaking online at EuroPython 2020
An article about my first participation as a speaker at an online conference: EuroPython 2020. -
Upcoming Courses | August 2020
After the smashing success of the Django Crash Course Live, we're running two live, online courses in August. Django Best Practices the Two Scoops Way August 14th, 2020 | 9AM-4PM PST / 4PM - 11PM UTC We're offering a live, online class called Django Best Practices the Two Scoops Way. This is a live interactive class conducted via Zoom conferencing software. Daniel is going to dive deep into Django and Python. He's going to turn on the firehose of knowledge. Best of all, this is a a live event. That means attendees can ask questions, and are encouraged to do so. Material covered includes everything from code architecture to model design to API development to bottleneck analysis to user accessibility and much more. This is not a beginner tutorial, it is meant for developers who have begun to create real projects with Django. Details: Event starts at 9AM PST (4PM UTC) and ends seven (7) hours later There will be an hour long break for lunch and short breaks every hour. Class prerequisites: Knowledge of the Python programming language Django experience beyond basic tutorials A device capable of running the Zoom meeting software. Internet fast enough to join online meetings … -
Handle Default Values - Building SaaS #65
In this episode, I updated a model to handle the default duration of new tasks. This default needed to come from the Course model instead of the CourseTask model so we had to determine how best to set that data in various forms. I also fixed some drop down selection bugs that populated a form with the wrong data. We made sure that all the code was well tested. I created a new default_task_duration field to the Course model. -
How to Make Always-Installed Django Database Instrumentation
Since version 2.0, Django has provided a hook for installing database instrumentation wrapper functions. These functions are like middleware for database queries, allowing you to inspect and rewrite SQL before it is sent to the database. There are many use cases, for example: Blocking database queries in certain blocks of code, as in the feature documentation. Tracking all queries, as in Scout APM’s python agent. Rewriting queries to add extra SQL features, as used in Django-MySQL’s query hints extensions. For this post, let’s use an example wrapper function that logs a warning for slow queries. We can implement it like this: import logging import time logger = logging.getLogger(__name__) THRESHOLD_SECONDS = 1.0 def slow_query_warner(execute, sql, params, many, context): start = time.perf_counter() result = execute(sql, params, many, context) duration = time.perf_counter() - start if duration > THRESHOLD_SECONDS: logger.warning("Slow query, took %.2f seconds: %s", duration, sql) return result Then for any block of code for which we want to log about slow queries, we can use: with connection.execute_wrapper(warn_about_slow_queries): ... A small limitation of the API is that it is only available as a context manager. This means having a wrapper function that’s installed for every single query is a little bit of a … -
EuroPython 2020
EuroPython is the official European conference for the Python programming language. -
NameError: name 'os' is not defined
If you've started a new Django 3.1+ project and are using older tutorials or guides, it's likely to come across the following error on your command line: ``` NameError: name … -
Caution About Faking Django Migrations
I ran into a problem recently when trying to reconfigure my Django project’s database. I had a DateTimeField on my model that I was updating to have null=True… -
Caution About Faking Django Migrations
I ran into a problem recently when trying to reconfigure my Django project’s database. I had a DateTimeField on my model that I was updating to have null=True and blank=True. There were no rows in this table. I was able to make the migrations, but then ran into this error when running python manage.py migrate. TypeError: expected string or bytes-like object What is This TypeError? Honestly, after my research, I’m not totally sure. I believe Django was trying to put a NULL value in that DateTime table column, but since the migration hadn’t been run, NULL values were still not allowed. I found something that made my error message go away… but also introduced a bug. Django’s Migrations Table Django’s migrations actually create a table in your database where database updates are tracked. Here’s a look at that table from one of my newer projects: postgres=# \d django_migrations Table "public.django_migrations" Column | Type | Collation | Nullable | Default ---------+--------------------------+-----------+----------+----------------------------------------------- id | integer | | not null | nextval('django_migrations_id_seq'::regclass) app | character varying(255) | | not null | name | character varying(255) | | not null | applied | timestamp with time zone | | not null | Indexes: "django_migrations_pkey" … -
The Hello World of Machine Learning
Machine learning is simply a c... -
Episode 7 - Models and Managers and Querysets, Oh My!
On this episode, we will explore more about models and how to interact with data in your database. Listen at djangoriffs.com. Last Episode On the last episode, we discussed the basics of setting up a database and creating a model to store data. Working With Models To create new rows in our new database tables, we can use a model’s save method. When you save a model instance, Django will send a message to the database that effectively says “add this new data to this database table. -
How to Use Django's Parallel Testing on macOS With Python 3.8+
This post is an adapted extract from my book Speed Up Your Django Tests, available now. Django’s test command takes the --parallel flag to activate parallel testing. Unfortunately, this has never worked on Windows, and with Python 3.8 it has stopped working on macOS. Django uses the “fork” method in multiprocessing to start the new test processes. Windows does not support “fork”, and whilst macOS does, Python 3.8 changed its default to “spawn”. If the start method is not “fork” when you use the --parallel flag, Django silently switches back to serial testing. The “spawn” method works quite differently to “fork”, requiring a lot of initialization in the new test processes, so the current test framework is incompatible. This is a known issue, Ticket #31169, and it is being worked on by Ahmad A. Hussein as part of Django’s Google Summer of Code 2020. Hopefully we will merge the fix in Django 3.2. For the time being, there’s a workaround for macOS. Alternatively, you can switch to pytest, since its parallelization plugin, pytest-xdist, works on all platforms. On macOS on Python 3.8+, you can work around the lack of “spawn” support by reverting the multiprocessing start method to “fork”. You … -
Models and Managers and Querysets, Oh My!
Full show notes are available at https://www.mattlayman.com/django-riffs/7. -
What is Django (Python)?
[Django](https://djangoproject.com) is an open-source web framework written in the [Python](https://www.python.org) programming language. Named after the jazz guitarist [Django Reinhardt](https://en.wikipedia.org/wiki/Django_Reinhardt), it is used by some of the largest websites in the …