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!

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (1)

Collapse
 
guyeshet profile image
Guy Eshet

great tip, thanks!

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay