Reputation: 9672
I have test script:
#!/usr/bin/env python
# coding: utf-8
import os, sys, subprocess, time, re
from django.conf import settings
from django.apps import apps
import django
django.setup()
"""
http://stackoverflow.com/questions/24027901/dynamically-loading-django-apps-at-runtime
"""
MAIN_IMPORTS = """\
from django.test import TestCase
from model_mommy import mommy
"""
IMPORT_STATEMENT = """\
from clientsite.{app}.models import {models}
"""
TEST_BLOCK = """\
class {modelname}CreationTests(TestCase):
def setUp(self):
self.model = {modelname}
def test_create(self):
x = mommy.make(self.model)
x.save()
self.assertTrue(x.pk)
def test_factory_isinstance(self):
x = mommy.make(self.model)
self.assertTrue(isinstance(x, {modelname}))
"""
all_apps = apps.get_apps()
all_models = apps.get_models()
model_info = apps.all_models
I want to be able to use django.apps
within my script. The script is within an app like mysite/mommy_app/scripts/testtasm.py
I tried
cchilders:~/work_projects/mysite [ckc/fixture-replacements]$ ./manage.py mysite/mommy_models/scripts/testtasm.py
Unknown command: 'mysite/mommy_models/scripts/testtasm.py'
and failed.
django.setup()
also failed.
How can I use django features within a script without actually running runserver? Thank you.
Upvotes: 1
Views: 730
Reputation: 308769
You shouldn't use manage.py
to run your script, unless you have created a custom management command
You should run the script with
python mysite/mommy_models/scripts/testtasm.py
Or, if the script is executable
mysite/mommy_models/scripts/testtasm.py
In the script, before you call django.setup
, you must set the DJANGO_SETTINGS_MODULE
environment variable. You may also have to add your project directory to the Python path.
import os
import sys
# This should be the directory that contains the directory containing settings.py
sys.path.append('/path/to/mysite')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
django.setup()
# now you can import the settings and access them
from django.conf import settings
Upvotes: 1