Django Standalone Script

I am trying to access my Django application DBG (v1.10) from another python script and have some problems with this.

This is my file and folder structure:

store store __init.py__ settings.py urls.py wsgi.py store_app __init.py__ admin.py apps.py models.py ... db.sqlite3 manage.py other_script.py 

According to the Django documentation, my other_script.py looks like this:

 import django from django.conf import settings settings.configure(DEBUG=True) django.setup() from store.store_app.models import MyModel 

But it generates a runtime error:

 RunTimeError: Model class store.store_app.models.MyModel doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. 

I should note that my INSTALLED_APPS list contains store_app as its last element.

If instead I try to pass the configuration as follows:

 import django from django.conf import settings from store.store_app.apps import StoreAppConfig settings.configure(StoreAppConfig, DEBUG=True) django.setup() from store.store_app.models import MyModel 

I get:

 AttributeError: type object 'StoreAppConfig has no attribute 'LOGGING_CONFIG'. 

If I edit settings.py and add LOGGING_CONFIG=None , I get another error about another missing attribute, etc.

Any suggestions would be appreciated.

+10
python django
Sep 27 '16 at 11:19
source share
3 answers

try it

 import sys, os, django sys.path.append("/path/to/store") #here store is root folder(means parent). os.environ.setdefault("DJANGO_SETTINGS_MODULE", "store.settings") django.setup() from store_app.models import MyModel 

You can use this script anywhere in your system.

+16
Sep 27 '16 at 12:03
source share

This sounds like a great option for Django management teams. , which has an added bonus, you can run it according to the cron schedule, directly from the command line or from inside django. This gives the script full access to the same parameters and environment variables as your main project.

If you move this to the appropriate directory - use an example here, not a sentence, it should work.

 store management __init__.py commands __init__.py otherscript.py 
+8
Sep 27 '16 at 11:53 on
source share

try importing from store_app.models - since the surrounding store folder is not a python module and should not be used when importing.

 import django from django.conf import settings settings.configure(DEBUG=True) django.setup() from store_app.models import MyModel 

update: I just noticed that you put this script next to the project folder - you have to move it inside for this to work.

0
Sep 27 '16 at 11:30
source share



All Articles