snakesNbronies
snakesNbronies

Reputation: 3910

running python module from django shell (manage.py)

I'm try to populate data into my db and I'd like to use the django API to do so. I've written a python module that allows me to this very easily.

However, within the django shell (manage.py), it doesn't seem possible to run my "populate.py" file.

Is it possible to run my populate.py from the django shell? Or alternatively, should I instead be running a regular python terminal and importing the necessary django components? Either way, I would greatly appreciate some pointers.

Upvotes: 1

Views: 3775

Answers (3)

jimscafe
jimscafe

Reputation: 1091

Try django-extensions it has a runscript command you put in a scripts directory.

Oddly the command seems to be missing from the main documentation but if you google django-extensions runscript you will find examples and documentation.

Upvotes: 1

Peter Rowell
Peter Rowell

Reputation: 17713

Here is my standard wrapper for running django stuff from the command line. This is also useful if you have cron scripts you want to run.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, sys
# If this script lives in a child directory of the main project directory
# uncomment the following 2 lines:
#dir_parent = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
#sys.path.insert(0, dir_parent)

from django.core.management import setup_environ
import settings
setup_environ(settings)

from django.db import transaction

# import whatever you like from app.models or whatever
# do random stuff.

# If you are *changing* database records,
# wrap your database code either in:
@transaction.commit_manually
def foo():
   ... stuff
   transaction.commit()

# OR end you script with:
transaction.commit_unless_managed()

Update for comment:

The variable mentioned above is not file, it is __file__ (i.e. 2 underscores file and 2 more underscores). This is always set by the Python interpreter to the full path of the file it occurs in. As the comment says, if this script lives in a child directory of the main directory, the directory-of-the-directory of the filename gives you the directory name of the main project directory, and adding that to sys.path will make sure that all of your imports work correctly. If the script lives in the main directory and you execute it from there, then you don't need to do that.

Upvotes: 1

Claude Vedovini
Claude Vedovini

Reputation: 2481

You can also consider using the loaddata command or create your own command

Upvotes: 4

Related Questions