Django: adding code execution on your app syncdb, or how to use Django Signals.

Hi there and let's talk about app initialization in Django. There are some cases when you want to initialize a Django app with creating some default values in database. In my case it was necessity to create default album in database to post user photos to. Sometimes you could just use get_or_create for those purposes. But it will be a good example if we will need something more complex in our app initialization; for e.g. generating thumbnails for photos or cleaning unused temporary files etc. So let's get started:

Good place to put your initialization scripts is your app's file. You can examine Djangoproject wiki for more info. Anyway here is my code for making this:

  1. from django.db.models.signals import post_syncdb
  2. import models
  3. from models import Album
  5. def create_first_album(sender, **kwargs):
  6.     """
  7.    Create your album sequence to create default album to post photos to
  8.    checks for existence of this album and creates one if none exists.
  9.    """
  10.     obj, created = Album.objects.get_or_create(title="User's Posted"
  11.     if created:
  12.         print("Created album 'User's Posted'.")
  13.     else:
  14.         print("NOT CRATED album 'User's Posted'.")
  15.     pass
  17. post_syncdb.connect(create_first_album, sender=models)

It is made using Django Signals documentation example. This code creates album 'Users Photos' upon first running os 'syncdb' bu my apps user. It's quite simple but shows the idea.

Main idea here that you need to add code to file of your app. It will stick to signal you've chosen (post_syncdb in our case) and execute on it's call. 
Than you will write your function to execute (def create_first_album in our case) and say when to execute this function. We sticked it to post_syncdb signal.

This way cou can handle more handy signals like using pre_init signal to execute some code not only at syncdb but at every app's startup or even add some code to template upon rendering. Read Django docs Signals to know more.


Popular posts from this blog

Python converting PDF to Image

How to disable/enable an element with jQuery or Javascript

Django: Resetting Passwords (with internal tools)