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 __init__.py file. You can examine Djangoproject wiki for more info. Anyway here is my code for making this:
Good place to put your initialization scripts is your app's __init__.py file. You can examine Djangoproject wiki for more info. Anyway here is my code for making this:
- from django.db.models.signals import post_syncdb
- import models
- from models import Album
- def create_first_album(sender, **kwargs):
- """
- Create your album sequence to create default album to post photos to
- checks for existence of this album and creates one if none exists.
- """
- obj, created = Album.objects.get_or_create(title="User's Posted",public=True)
- if created:
- print("Created album 'User's Posted'.")
- else:
- print("NOT CRATED album 'User's Posted'.")
- pass
- post_syncdb.connect(create_first_album, sender=models)
Main idea here that you need to add code to __init__.py 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.
Comments
Post a Comment