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!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (1)

Collapse
 
guyeshet profile image
Guy Eshet

great tip, thanks!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay