Unable to import Django models in python script - django

My code is here.
I have tried different approach from stackoverflow and non of them worked.
import os
import sys
from django.conf import settings
sys.path.append('/var/www/iaas/horizon')
sys.path.append('/var/www/iaas/horizon/openstack_dashboard')
os.environ['DJANGO_SETTINGS_MODULE'] = 'openstack_dashboard.settings'
from bill.models import MonthlyBills
from django.contrib.auth import models
If I run python daemonize.py, here is the error message I get.
I am confused because I have already included my django project path in my sys.path
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'openstack_dashboard.settings' (Is it on sys.path?): cannot import name connection
What I am trying to achieve is to create a python-daemon, I need to have an access in my django models.
I hope someone who could point me where I am mistaking here.

You have to set up os.environ['DJANGO_SETTINGS_MODULE'] before you import settings.
The process of importing django.conf.settings will look to see if the DJANGO_SETTINGS_MODULE environment variable is set before determining white settings to load.
import os
import sys
sys.path.append('/var/www/iaas/horizon')
sys.path.append('/var/www/iaas/horizon/openstack_dashboard')
os.environ['DJANGO_SETTINGS_MODULE'] = 'openstack_dashboard.settings'
from django.conf import settings

Related

I start a project to know more about google sign in and only add my app to my projects settings.py.Then i try to migrate, throws an error like

from django.utils import importlib
ImportError: cannot import name 'importlib' from 'django.utils'

py2exe compiled .exe won't start

I compiled my prototype Application with py2exe to check its function as an exe, and run into 0 errors until I go to start it. Nothing happens. A process starts with my app name, it thinks for a few seconds, then nothing. No log file is generated. The app works great when run in python environment, but not in the compiled exe. I've given my setup code below. Any ideas? :
from distutils.core import setup
import py2exe, sys, os
import matplotlib
import FileDialog
import dateutil
sys.argv.append('py2exe')
setup( windows=['ATLAS.pyw'], data_files=matplotlib.get_py2exe_datafiles(),
options = {"py2exe": {
"includes": "decimal, datetime",
"packages": ["FileDialog", "dateutil"],
'bundle_files': 2,
'compressed': True}
},
zipfile = None
)
Hooks utilized in the Application:
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.backend_bases import key_press_handler
from pandas.sandbox.qtpandas import DataFrameWidget
from matplotlib.widgets import LassoSelector
from tkFileDialog import askopenfilename
from matplotlib.figure import Figure
import matplotlib.image as mpimg
from PySide import QtGui, QtCore
from matplotlib.path import Path
import pandas.io.sql as psql
from numpy import nonzero
import tkMessageBox as mb
from pylab import *
import pyodbc
import sys
import ttk
SOLVED:
So, using quick fingers (and compiling it with PyInstaller with the --debug option) I screen-capped the quickly-closing console window that contained the Traceback:
WindowsError: [Error 3] The system cannot find the path specified: 'C:\\path\\dateutil\\zoneinfo/*.*'
The zoneinfo file was being saved in pytz instead of dateutil. A quick rename solved the problem.
Only issue though, if you want to compile with -F or --onefile it will not work due to the initial improper naming convention. Not quite sure how to fix that though.

django import client

i am trying to import the client in django for testing. but when i do, i get this wierd error:
ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
from django.utils import unittest
from django.utils import simplejson as json
from django.test.client import Client
this is how i imported the client so that i could use it for testing. can someone explain this to me please.
Try this:
import os
import sys
sys.path.append('/home/username/www/site_folder')
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'
from django.utils import unittest
from django.utils import simplejson as json
from django.test.client import Client
But replace project with folder name, where your settings.py is
The Client is looking for the settings.py. You could simply load the client by typing this in your project folder:
python manage.py shell
In Pycharm which I use, after following this Running Django tests in PyCharm
my problem was solved.
It's in the file > settings > Django Support, and then select the right settings.

Django orm and path import

Here is my file tree :
--script
..........script.py
-- emails
.........__init__.py
.........models.py
settings.py
_init_.py
manage.py
and my code in script.py
import email, getpass, imaplib, os
import datetime
import unicodedata
import time
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "../settings")
import sys
cmd_folder = os.path.realpath("../")
sys.path.append(cmd_folder)
from emails.models import Email
but i have this error :
TypeError: relative imports require the 'package' argument
How to resolve it please ?
Regards
Try something like:
os.path.realpath(os.path.dirname(os.path.realpath(__file__)) + '/..')
The solution thanks to #django
../ is incorrect for module path so :
import sys
cmd_folder = os.path.realpath(os.path.dirname(os.path.realpath(__file__)) + '/../..')
sys.path.append(cmd_folder)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Sumomo.settings")
from Sumomo.emails.models import Email
(sumomo is the name of my project)

Could not import/No module named Django Error with Apache

I had a small proof of concept set up on a development server on a local machine. I'm now trying to move it over to django on a production server, which I'm using webfaction for. However, now that I'm switched over to apache from the built in django server I get the following:
ViewDoesNotExist: Could not import orgDisplay.views. Error was: No module named orgDisplay.views
But when check my orgDisplay apps folder there is a view.py in it. What am I doing wrong? I've tried adding the following to my settings.py by suggestion of the django IRC room.
import sys
sys.path.append(r"/home/user/webapps/django_project/myproject/orgDisplay")
which is the path to my app.
any ideas on how to even begin to trouble shoot this?
Thanks in advance.
I assume you're using mod_wsgi (which is recommended by Django authors), not mod_python. This is the way you should use your sys.path:
django.wsgi:
import os, sys
sys.path.append(r"/home/user/webapps/django_project/myproject/")
os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
sys.stdout = sys.stderr # Prevent crashes upon print
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
urls.py:
from django.conf.urls.defaults import *
urlpatterns = (
("", include("orgDisplay.urls")),
# ...
)
orgDisplay/urls.py:
import views
urlpatterns = (
(r'^some_view/$', views.some_view), # It is actually orgDisplay.views.some_view
# many more records ...
)
It is a bad idea to add project dir itself to path since you're be getting name conflicts between multiple projects.
I think you're appending the wrong directory to sys.path. I think Python is looking in the .../myproject/orgDisplay folder for the orgDisplay package. Try removing the orgDisplay from your string, like this:
import sys
sys.path.append(r"/home/user/webapps/django_project/myproject")
The other option would be to simply add myproject (or whatever your project is actually called) in the import statement.
# instead of "from orgDisplay import views"
from myproject.orgDisplay import views
Also, make sure to restart Apache after every edit.
looking at manage.py, it does it like so:
import sys
from os.path import abspath, dirname, join
from django.core.management import setup_environ
# setup the environment before we start accessing things in the settings.
setup_environ(settings_mod)
sys.path.insert(0, join(PINAX_ROOT, "apps"))
sys.path.insert(0, join(PROJECT_ROOT, "apps"))
Provided your WSGI file is in your project directory, a slightly more flexible way is this:
import os, sys
sys.path.append(os.path.dirname(__file__))
This will enable you to change your project location later without having to modify your WSGI file.