DEV Community

Connor Bode
Connor Bode

Posted on

3 1

Perform an action every time Django starts

Recently, I was building django-single-instance-model. The package ensures that at all times there is exactly one instance of a model.

One of the tasks for building this package was ensuring that an instance of the model existed.

I wanted to run this code as early as possible, once the database connection had been made.

How did I do it?

In the __init__.py of the main app, I hooked into the connection_created signal. Here's how:

from django.dispatch import receiver
from django.db.backends.signals import connection_created


@receiver(connection_created)
def my_receiver(connection, **kwargs):
    with connection.cursor() as cursor:
            pass # your startup code here

Hope this helps you in the future! Follow me for more Django / Python tips!

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (1)

Collapse
 
guyeshet profile image
Guy Eshet

great tip, thanks!

Billboard image

Imagine monitoring that's actually built for developers

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay