How to write a stand-alone Python script working with Django modules? - django

In PyCharm, I created a blank new Django app. Having created some models and issued manage.py makemigrations and manage.py migrate, I tried to write a standalone script that would populate the database with initial data. In its imports I wrote:
from MyApp.models import Model1, Model2, …
Sadly, running this script in PyCharm throws an exception: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
I Googled this exception, and found an answer in SO https://stackoverflow.com/a/27455703/4385532 advising to put this in the top of my script:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
So I did. Sadly, this didn’t fix the issue. Now I am greeted with another exception:
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
What should I do?

Make sure you also do:
import django
django.setup()
To load your models.
Documentation: https://docs.djangoproject.com/en/1.10/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage

Related

Applying Django 1.6 project settings in PyDev

I have no problems running the python shell with the python manage.py -shell command in the terminal; I can import my modules and make queries on the database and so on. However, in PyDev, even though I can import modules, when I try to access the data stored in my SQLite database, I get this message:
ImproperlyConfigured: settings.DATABASES is improperly configured.
Please supply the ENGINE value.
Since my project's settings are ok (the site works fine locally), it must have to do with Pydev not applying the project configs. The sequence of starting up the Django/python shell is as follows:
from django.conf import settings; settings.configure()
from django.core import management
import XX.settings as settings
management.setup_environ(settings) # This throws an error as setup_environ
# setup_environ is deprecated in Django 1.6
The last 3 lines are hard-coded (and were, I gather, working pre-Django 1.6)
I thought doing something like:
from django.conf import settings as djangoSettings
from XX import settings
djangoSettings.configure(settings)
But then I get this error:
ImportError: Could not import settings ''XX.settings'' (Is it on
sys.path? Is there an import error in the settings file?): No module
named 'XX.settings'
And yes, the path is in sys.path.
Any help greatly appreciated.

ImportError when using Haystack 2.0.0 with Django 1.5 and Gunicorn WSGI

I use django-haystack 2.0.0 to index my site, and it has been working great until I upgraded to Django 1.5 and started using the WSGI interface. If I just use the django_gunicorn command it works great, but the Django documentation "highly recommends" I use the gunicorn command.
When I start my site with the gunicorn command, Haystack throws the following error on any page load:
ImportError: cannot import name signals
I have no problems importing signals from the Django or Python shells. I use virtualenv and install all packages locally inside that environment. My wsgi.py file looks just like the default one in the django admin, except that I add the local path to the python path as such:
path = os.sep.join(os.path.abspath(__file__).split(os.sep)[:-2])
if path not in sys.path:
sys.path.append(path)`
Any help you could provide would be very appreciated, thank you!
I don't use gunicorn, but I had the same problem when I used the HAYSTACK_SIGNAL_PROCESSOR setting to point to a custom class that I wrote. That class imported one of my models, which eventually propagated up the import chain, to import my settings module, thus causing a circular import.
When using a setting such as HAYSTACK_SIGNAL_PROCESSOR that points to a class, make sure that class standsalone, and doesn't import either directly or indirectly the Django settings file.

Can't use django management commands because of Import Errors when haystack tries to import multiligualmodel

I'm using django-haystack for searching on my site.
I'm also using django multilingual model for I18n.
I import MultilingualModel in search_indexes.py
I ca run all manangement commands as long as I don't have haystack in the INSTALLED_APPS.
When haystack is in the INSTALLED_APPS and try to run syncdb or migrate (and several other management commands) I'm always getting:
django.core.exceptions.ImproperlyConfigured: ImportError haystack: cannot import name MultilingualModel
This is likely related to the hacks done in haystack.autodiscover(). This behavior is documented here: http://docs.haystacksearch.org/dev/debugging.html#import-errors-on-start-up-mentioning-handle-registrations There is a long discussion in this ticket: https://github.com/toastdriven/django-haystack/issues/84
The long and short if it is that moving haystack.autodiscover() into your urls.py can sometimes resolve this issue. Setting HAYSTACK_ENABLE_REGISTRATIONS = False when running syncdb or migrate has resolved this for me using this snippet in my settings.py:
# FIXME: This is a complete hack to get around circular imports in
# django-haystack and other apps such as django-endless-pagination
SKIP_COMMANDS = ['syncdb', 'migrate', 'schemamigration', 'datamigration']
if any([command in sys.argv for command in SKIP_COMMANDS]):
HAYSTACK_ENABLE_REGISTRATIONS = False
search_indexes.py doesn't get processed unless haystack is in INSTALLED_APPS. The problem is with the import of MultilingualModel in general. Either it's not truly installed in your environment (attempt to import it from a vanilla python shell), or you have the import wrong (it's actually in another module, for example).
Once you can successfully import MultilingualModel from a python shell, you won't have any problems.

Configuration error in django

I am using django with mod_python (I know it is deprecated -- I am just doing this for an exercise), and am getting the following error --
"Could not import project.views. Error was: No module named app.models"
I am getting the 'No module named app.models" in several other places as well. My syncdb is working fine, and if I go into the manage.py shell I can import the models fine. Why is this occurring and what do I need to change? Thank you.
You should use absolute imports everywhere. If your project is structured like so:
/project/settings.py
/project/app/models.py
/project/app/views.py
In INSTALLED_APPS you would use project.app. In app you'd import your models into views: import project.app.models, etc. Alternately you can try adjusting your PYTHONPATH so your imports work. When you run ./manage.py you are in your project folder, and Python automatically adds it to the PYTHONPATH. This doesn't happen automatically in most deployment scenarios (mod_python or other wise).

Cannot import django.core

I am trying to setup django with fastcgi on apache. Django is installed and seems to be running correctly but I am having problems with setting up fastcgi.
I decided to test out my dispatch.fcgi script in the interactive python shell line by line and the following line:
from django.core.servers.fastcgi import runfastcgi
results in the following error:
ImportError: No module named core.servers.fastcgi
I can import django with no problem but import django.core gives yet another ImportError (No module named core).
How can I go about ensuring that I can import django.core. If I can import django then in must be on my path, and so why can I not import core?
You probably have a file/folder called django somewhere in your path, that isn't the actual path.
try this
import sys
sys.path
And then check everything in that output to see if there is a file/folder called django(.py) somewhere.
If so, change the path (sys.path = ['/path/to/directory/below/django/install'] + sys.path) or move/rename the file.
Probably you have django.py module in your working directory or in any other that is in python path.
For anyone having this problem and coming across this question like I did, it turns out that fastcgi support has been removed as of Django 1.9, thus you will get this import error if trying to import it. Refer Using Django with virtualenv, get error ImportError: No module named 'django.core.servers.fastcgi'