Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using django model outside of the django framework

Tags:

python

django

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?

like image 687
jordanthompson Avatar asked Dec 25 '22 11:12

jordanthompson


1 Answers

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

like image 100
maazza Avatar answered Dec 29 '22 00:12

maazza