Django: Custom Middleware for Alerting High Database Querying

In this post I will show you how you can implement a custom middleware that you can use in your development environment to monitor queries to the database in your views when developing Django applications.

Let's begin by creating a middleware.py file (a nice convention) where we will place our new middleware. The middleware is relatively simple and small, this is how it looks like:

django

Custom Admin Action Buttons in Django

In this post I will explain how you can add custom action buttons in the admin detail view of objects in the Django admin.

This is the final result we want to achieve:

Custom Admin Buttons

These buttons can trigger custom actions that we want to perform on these objects.

django

Gracefully Exiting Python Context Managers on Ctrl+C

In this post I will show you how you can exit gracefully from within a context manager in your Python application.

Suppose that we provide a context manager that can be used as a session to perform certain tasks. When the context manager is closed, there is some cleanup work to be done. We want this to happen even when the user interrupts the program with Ctrl+C key.

This is how we can achieve that:

python

Python Log Messages With Dynamic Formatter Variables

In this post I will explain how it is possible to replace logger formatter variables with dynamic values. Take the following log message for example:

[2020-04-02 15:37:01] myapp INFO: Logged in successfully.

What if we wanted to add some additional data after the INFO part, but this data is dynamic, or is only available at runtime. Like a username or an app name for example.

Let's take a look at how to achieve this.

python

Django: ORing A List of Q Objects

Django allows using the OR bitwise operator | with Q objects for more complex lookups:

Q(question__startswith='Who') | Q(question__startswith='What')

However this requires explicitely typing each Q object. How can we apply this OR opperation to all the Q objects in a list?

In Python 3 we can do so like this:

from functools import reduce
from operator import __or__


qs = MyModel.objects.filter(reduce(__or__, filters))

Where filters is a list containing multiple Q objects like the ones shown in the first example.

django
Older Posts →