In django, how do I call the subcommand 'syncdb' from the initialization script?

All Django management commands can be accessed programmatically:

from django.core.management import call_command
call_command('syncdb', interactive=True)

Ideally you'd use a pre-init signal on runserver to activate this, but such a signal doesn't exist. So, actually, the way I'd handle this if I were you would be to create a custom management command, like runserver_newdb, and execute this inside it:

from django.core.management import call_command
call_command('syncdb', interactive=True)
call_command('runserver')

See the documentation for more information on writing custom management commands.


As suggested by "Where to put Django startup code?", you can use middleware for your startup code. The Django docs are here.

For example (untested):

startup.py:

from django.core.exceptions import MiddlewareNotUsed
from django.conf import settings
from django.core.management import call_command

class StartupMiddleware(object):
    def __init__(self):
        # The following db settings name is django 1.2.  django < 1.2 will use settings.DATABASE_NAME
        if settings.DATABASES['default']['NAME'] == ':memory:':
            call_command('syncdb', interactive=False)

        raise MiddlewareNotUsed('Startup complete')

and in your settings.py:

 MIDDLEWARE_CLASSES = (
     'your_project.middleware.startup.StartupMiddleware',

     # Existing middleware classes here
 )

Update

I added a script called run.sh in the project's root directory. This worked for me with an SQLite database:

#!/usr/bin/python
from django.core.management import call_command
call_command('syncdb')
call_command('runserver')

Original Answer

I am not sure I understand what you mean by "scripting the syncdb command". You usually execute python manage.py syncdb from the command line. This is usually done after adding new models. In case you want to you easily accomplish this using a simple shell script. I don't see any reason to place (or invoke) syncdb from within settings.py.

Could you add more details to your question? Add context and explain what exactly are you trying to get done?