4

I have a django application that is working fine. I want to be able to leverage the model to access the database from another (standalone) python app. Here is what I have (that doesn't work.)

import sys
import os

sys.path.append(os.path.abspath("/home/pi/garageMonitor/django/garageMonitor"))
os.environ['DJANGO_SETTINGS_MODULE'] = 'garageMonitor.settings'
import models
    config = models.SystemConfiguration.objects.filter(idSystemConfiguration=1)
    config = config[0]
    for x in config.__dict__:
      print x

Here is the error I get:

  File "/home/pi/garageMonitor/django/lib/webWatcher.py", line 14, in <module>
    import models
  File "/home/pi/garageMonitor/django/garageMonitor/models.py", line 11, in <module>
    class DoorClosing(models.Model):
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 131, in __new__
    'app.' % (new_class.__name__, model_module.__name__)
django.core.exceptions.ImproperlyConfigured: Unable to detect the app label for model "DoorClosing

DoorClosing is a class in my models.py file. Similar code works within the django framework. What am I missing?

jordanthompson
  • 888
  • 1
  • 12
  • 29

2 Answers2

7

run

django.setup()

before importing your models

import django
import sys
import os

sys.path.append(os.path.abspath("/home/pi/garageMonitor/django/garageMonitor"))
os.environ['DJANGO_SETTINGS_MODULE'] = 'garageMonitor.settings'
django.setup()
import models
    config = models.SystemConfiguration.objects.filter(idSystemConfiguration=1)
    config = config[0]
    for x in config.__dict__:
      print x

see https://docs.djangoproject.com/en/1.9/ref/applications/#initialization-process

maazza
  • 7,016
  • 15
  • 63
  • 96
3

Please refer to this post for working version for this problem in latest Django version. see https://stackoverflow.com/a/46050808/1698030

Quoting the solution here:

import os
from django.conf import settings
from django.apps import apps

conf = {
    'INSTALLED_APPS': [
        'Demo'
    ],
    'DATABASES': {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join('.', 'db.sqlite3'),
        }
    }
}

settings.configure(**conf)
apps.populate(settings.INSTALLED_APPS)

Put your app name and any other apps you have on your project under 'INSTALLED_APPS'