Trying to use django templates in stand-alone mode.
I get these exceptions (below).
New to python, wondering if anyone would be willing to help out.
Django is used for templating in a script which is not shown here.
However the exact same exceptions appear when launching it.
>>> from django.template import Template, Context
>>> from django.conf import settings
>>> settings.configure()
>>> t = Template('My name is {{ my_name }}.')
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/django/template/utils.py", line 86, in __getitem__
return self._engines[alias]
KeyError: 'django'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.4/dist-packages/django/template/base.py", line 182, in __init__
engine = Engine.get_default()
File "/usr/lib/python3.4/functools.py", line 472, in wrapper
result = user_function(*args, **kwds)
File "/usr/local/lib/python3.4/dist-packages/django/template/engine.py", line 88, in get_default
django_engines = [engine for engine in engines.all()
File "/usr/local/lib/python3.4/dist-packages/django/template/utils.py", line 110, in all
return [self[alias] for alias in self]
....
....
File "/usr/local/lib/python3.4/dist-packages/django/apps/registry.py", line 137, in get_app_configs
self.check_apps_ready()
File "/usr/local/lib/python3.4/dist-packages/django/apps/registry.py", line 124, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
My django version:
python3 -c "import django; print(django.get_version())" ---> 1.9.7
My python version:
Python 3.4.3
After calling settings.configure(), you must call django.setup().
import django
from django.conf import settings
settings.configure()
django.setup()
from django.template import Template, Context
t = Template('My name is {{ my_name }}.')
c=Context({'my_name': 'Mindaugas'})
t.render(c)
See the docs for more info.
Related
I am trying to get going with django, which so far I have found to be amazing other than repeated db issues.
My latest is following the Django by Example book and I have followed everything to the letter, yet when following some simple instructions to add some data via the python shell api I get the following:
>>> from django.contrib.auth.models import User
>>> from blog.models import Post
>>> user = User.objects.get(username='jamie')
>>> Post.objects.create(title='One More Post', slug='one-more-post', body='Post body', author='user')
Traceback (most recent call last):
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 69, in handle
self.run_shell(shell=options['interface'])
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 61, in run_shell
raise ImportError
ImportError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/query.py", line 346, in create
obj = self.model(**kwargs)
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/base.py", line 468, in __init__
setattr(self, field.name, rel_obj)
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/fields/related.py", line 629, in __set__
self.field.rel.to._meta.object_name,
ValueError: Cannot assign "'user'": "Post.author" must be a "User" instance.
This has happened while following multiple tutorials and I am stumped. I followed standard instructions and installed, pip, python and django via terminal. Also using a virtual env so not sure why this is happening.
Use this instead of your statement.
Use user variable instead of 'user' string.
Post.objects.create(title='One More Post', slug='one-more-post',
body='Post body', author=user)
I am new to django. Want to create tables in the Database of my project, so I searched the tutorial.
models.py:
from django.db import models
class Blah(models.Model):
first = models.IntegerField()
second = models.IntegerField()
Script to write data into db:
from django.conf import settings
settings.configure()
from core.models import Blah
b = Blah(first = 1, second = 2)
b.save()
When I am trying to launch the script with django 1.9, it gives me the error:
C:\Python27\Scripts\reports>to_db.py
Traceback (most recent call last):
File "C:\Python27\Scripts\reports\to_db.py", line 4, in <module>
from core.models import Blah
File "C:\Python27\Scripts\reports\core\models.py", line 5, in <module>
class Blah(models.Model):
File "C:\Python27\lib\site-packages\django\db\models\base.py", line 94, in __new__
app_config = apps.get_containing_app_config(module)
File "C:\Python27\lib\site-packages\django\apps\registry.py", line 239, in get_containing_app_config
self.check_apps_ready()
File "C:\Python27\lib\site-packages\django\apps\registry.py", line 124, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
I have already added the app to INSTALLED_APPS and I am able to do the exact same commands with "manage.py shell", but not with the script.
What am I missing here?
Thanks
If you do need to script against Django (and the ORM), you'll want to use the shell admin command, passing your script as input to it. Related question
Whenever I type this command in Python GUI:
from django.db import models
it gives me an error like this
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
from django.db import models
File "C:\Python27\lib\site-packages\django\db\models\__init__.py", line 5, in <module>
from django.db.models.query import Q
File "C:\Python27\lib\site-packages\django\db\models\query.py", line 17, in <module>
from django.db.models.deletion import Collector
File "C:\Python27\lib\site-packages\django\db\models\deletion.py", line 4, in <module>
from django.db.models import signals, sql
File "C:\Python27\lib\site-packages\django\db\models\sql\__init__.py", line 4, in <module>
from django.db.models.sql.subqueries import *
File "C:\Python27\lib\site-packages\django\db\models\sql\subqueries.py", line 12, in <module>
from django.db.models.sql.query import Query
File "C:\Python27\lib\site-packages\django\db\models\sql\query.py", line 22, in <module>
from django.db.models.sql import aggregates as base_aggregates_module
File "C:\Python27\lib\site-packages\django\db\models\sql\aggregates.py", line 9, in <module>
ordinal_aggregate_field = IntegerField()
File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 116, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 54, in __getattr__
self._setup(name)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 47, in _setup
% (desc, ENVIRONMENT_VARIABLE))
ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
What can it be the problem? I have django in directory C:\Python27\Lib\site-packages\django\db and in there i have a file called models.
This is the pic
Bizarre isn't it?
Not all of Django supports simply being loaded as a Python module, unfortunately; you need to use the means provided by Django itself to bootstrap the environment needed to load stuff like models.
One option is to use the Django shell but it's also possible to use a purely programmatic solution from your own code. See https://docs.djangoproject.com/en/dev/topics/settings/ for all the options.
Here's also an example by somebody else https://gist.github.com/jordanorelli/1025419 but I haven't verified if it's up to date.
The answer is in the error message:
You must either define the environment variable DJANGO_SETTINGS_MODULE or...
For this reason Django provides a shortcut to loading a python shell with Django settings configured:
https://docs.djangoproject.com/en/dev/ref/django-admin/#shell
I'm trying to queue up some build requests in a DB during a changegroup hook. The DB table is managed by a Django app. So, in the hook, I want to use the Django model to submit the build request. However, I'm unable to get my settings right to import the model successfully.
Based on this (https://docs.djangoproject.com/en/1.3/ref/django-admin/) info, all I need to do is add my django site to the sys path, and set the DJANGO_SETTINGS_MODULE. The django site lives in /opt/mysite, so - trying this from the python console:
>>> import sys
>>> import os
>>> sys.path.append('/opt')
>>> os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
>>> from mysite.myapp.models import Build
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/mysite/myapp/models.py", line 1, in <module>
from django.db import models
File "/usr/lib/pymodules/python2.7/django/db/__init__.py", line 78, in <module>
connection = connections[DEFAULT_DB_ALIAS]
File "/usr/lib/pymodules/python2.7/django/db/utils.py", line 93, in __getitem__
backend = load_backend(db['ENGINE'])
File "/usr/lib/pymodules/python2.7/django/db/utils.py", line 33, in load_backend
return import_module('.base', backend_name)
File "/usr/lib/pymodules/python2.7/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/usr/lib/pymodules/python2.7/django/db/backends/mysql/base.py", line 28, in <module>
from django.db import utils
ImportError: cannot import name utils
>>>
Second Attempt:
Based on this (http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/) I can use setup_environ(), when I try this in the python shell, it works:
>>> import sys
>>> sys.path.append('/opt')
>>> from django.core.management import setup_environ
>>> from mysite import settings
>>> setup_environ(settings)
'/opt/mysite'
>>> from mysite.myapp.models import Build
>>> Build.objects.all()
[<Build: #1 F nkj sdfsdfsdfs43qg test_branch>, <Build: #2 F nkj sdfsdfsdfs43qg test_branch>, <Build: #13 Q >, <Build: #14 Q nkj_bug243>, <Build: #11 F nkj 444hwe45hedrrt nkj_bug272>, <Build: #12 F nkj sdfsdfsdfs43qg test_branch>]
However, when I try this in my Mercurial hook, I get blasted with errors the minute I try to import my Build model:
#!/usr/bin/env python
import sys
path = '/opt'
if path not in sys.path:
sys.path.append(path)
from django.core.management import setup_environ
from mysite import settings
setup_environ(settings)
from mysite.myapp.models import Build
import datetime
... do stuff ...
When it gets to the 'from mysite.myapp.models import Build' line I get the following error output:
** unknown exception encountered, please report by visiting
** http://mercurial.selenic.com/wiki/BugTracker
** Python 2.7.2+ (default, Oct 4 2011, 20:06:09) [GCC 4.6.1]
** Mercurial Distributed SCM (version 1.9.1)
** Extensions loaded:
Traceback (most recent call last):
File "/usr/bin/hg", line 38, in <module>
mercurial.dispatch.run()
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 27, in run
sys.exit(dispatch(request(sys.argv[1:])))
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 64, in dispatch
return _runcatch(req)
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 87, in _runcatch
return _dispatch(req)
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 679, in _dispatch
cmdpats, cmdoptions)
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 454, in runcommand
ret = _runcommand(ui, options, cmd, d)
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 733, in _runcommand
return checkargs()
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 687, in checkargs
return cmdfunc()
File "/usr/lib/python2.7/dist-packages/mercurial/dispatch.py", line 676, in <lambda>
d = lambda: util.checksignature(func)(ui, *args, **cmdoptions)
File "/usr/lib/python2.7/dist-packages/mercurial/util.py", line 385, in check
return func(*args, **kwargs)
File "/usr/lib/python2.7/dist-packages/mercurial/commands.py", line 3884, in push
newbranch=opts.get('new_branch'))
File "/usr/lib/python2.7/dist-packages/mercurial/localrepo.py", line 1428, in push
lock=lock)
File "/usr/lib/python2.7/dist-packages/mercurial/localrepo.py", line 1849, in addchangegroup
source=srctype, url=url)
File "/usr/lib/python2.7/dist-packages/mercurial/localrepo.py", line 224, in hook
return hook.hook(self.ui, self, name, throw, **args)
File "/usr/lib/python2.7/dist-packages/mercurial/hook.py", line 160, in hook
mod = extensions.loadpath(path, 'hghook.%s' % hname)
File "/usr/lib/python2.7/dist-packages/mercurial/extensions.py", line 45, in loadpath
return imp.load_source(module_name, path)
File "/opt/unapse/belvedere/mercurial_hook.py", line 14, in <module>
from unapse.belvedere.models import Build
File "/usr/lib/python2.7/dist-packages/mercurial/demandimport.py", line 109, in _demandimport
mod = _origimport(name, globals, locals)
File "/opt/unapse/belvedere/models.py", line 1, in <module>
from django.db import models
File "/usr/lib/python2.7/dist-packages/mercurial/demandimport.py", line 109, in _demandimport
mod = _origimport(name, globals, locals)
File "/usr/lib/pymodules/python2.7/django/db/__init__.py", line 14, in <module>
if not settings.DATABASES:
File "/usr/lib/pymodules/python2.7/django/utils/functional.py", line 276, in __getattr__
self._setup()
File "/usr/lib/pymodules/python2.7/django/conf/__init__.py", line 42, in _setup
self._wrapped = Settings(settings_module)
File "/usr/lib/pymodules/python2.7/django/conf/__init__.py", line 139, in __init__
logging_config_func(self.LOGGING)
File "/usr/lib/python2.7/logging/config.py", line 776, in dictConfig
dictConfigClass(config).configure()
File "/usr/lib/python2.7/logging/config.py", line 575, in configure
'%r: %s' % (name, e))
ValueError: Unable to configure handler 'mail_admins': __import__() argument 1 must be string, not DictConfigurator
Any ideas as to what could be causing this problem?
The DictConfigurator error is a bug in python, hopefully fixed in the next 2.7 release (http://bugs.python.org/issue12718), something (probably mercurial) is overriding import and python's logging code fails in that case.
Until then here is what I did to fix it. Copy dictconfig.py from django/utils to somewhere in your python system path (I put it alongside my hook). Change the line
importer = __import__
to:
def importer(self, *args):
return __import(*args)__
And then in settings.py for your django project add to the end:
LOGGING_CONFIG = 'website.dictconfig.dictConfig'
Update website.dictconfig to whatever path you put the dictconfig file into so python can find it.
UPDATE: I think there is an even easier way. Add this to the top of your hook script, before importing anything else:
from mercurial import demandimport;
demandimport.disable()
This makes Mercurial revert the import override and seems to solve the problem cleanly.
If you're running with your environment in a virtualenv dir you'll need to add that to the site packages and I'd also suggest that you put the django dir at the front of sys.path instead of the end.
Here's the code we use to integrate our Django app into other python apps.
import os
import sys
# point this at the virtualenv dir that your django deployment runs out of
# you are using virtualenv. right?
DJANGO_ENV = '/home/core/python-envs/production'
# where your code lives (ie where settings.py is)
DJANGO_DIR = '/home/core/code/production'
# add our site packages
import site
site_packages = os.path.join(DJANGO_ENV, 'lib', 'python%s' % sys.version[:3], 'site-packages')
site.addsitedir(site_packages)
# put the main Django directory on first
sys.path.insert(0, DJANGO_DIR)
# setup the Django environment pointing to our settings
import settings
import django.core.management
django.core.management.setup_environ(settings)
# finally, import our objects
from yourapp.models import YourModel
One last thing to note is that when we import our code into some applications we've run into scoping issues and imports clashing. To get around it we wrap the work we want to do in a function so that it gets its own scope.
For example, instead of:
from yourapp.models import YourModel
objs = YourModel.objects.filter(something=True)
...
Do something like:
def do_work():
from yourapp.models import YourModel
objs = YourModel.objects.filter(something=True)
...
do_work()
I am trying to get started with using nosegae, however I run into the issue that I can't seem to get it to pass even the simplest of cases when using django.
when running without the --without-sandbox flag both the following tests fail
def test_import_django ():
import django
def test_import_django_http ():
import django.http
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\nose-1.1.2-py2.7.egg\nose\case.py", line 1
97, in runTest
self.test(*self.arg)
File "C:\Users\User\Desktop\TDD_GAE\myproj\tests.py", line 2, in test_import_d
jango
import django
File "C:\Python27\lib\site-packages\nosegae-0.1.9-py2.7.egg\nosegae.py", line
207, in find_module
return super(HookMixin, self).find_module(fullname, path)
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\de
v_appserver.py", line 1505, in Decorate
return func(self, *args, **kwargs)
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\de
v_appserver.py", line 1998, in find_module
search_path)
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\de
v_appserver.py", line 1505, in Decorate
return func(self, *args, **kwargs)
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\de
v_appserver.py", line 2119, in FindModuleRestricted
result = self.FindPathHook(submodule, submodule_fullname, path_entry)
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\de
v_appserver.py", line 2219, in FindPathHook
return self._imp.find_module(submodule, [path_entry])
Howevere if I do use --without-sandbox at least the first test passes
myproj.tests.test_import_django ... ok
myproj.tests.test_import_django_http ... ERROR
======================================================================
ERROR: myproj.tests.test_import_django_http
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\nose-1.1.2-py2.7.egg\nose\case.py", line 1
97, in runTest
self.test(*self.arg)
File "C:\Users\User\Desktop\TDD_GAE\myproj\tests.py", line 5, in test_import_d
jango_http
import django.http
File "C:\Program Files (x86)\Google\google_appengine\lib\django_1_2\django\htt
p\__init__.py", line 9, in <module>
from mod_python.util import parse_qsl
File "C:\Python27\lib\site-packages\nosegae-0.1.9-py2.7.egg\nosegae.py", line
199, in find_module
mod_path = self.find_mod_path(fullname)
File "C:\Python27\lib\site-packages\nosegae-0.1.9-py2.7.egg\nosegae.py", line
251, in find_mod_path
_sf, path, _desc= self._imp.find_module(top, None)
AttributeError: 'str' object has no attribute 'find_module'
Has anyone encountered and know how I can go about past this?
Edit
It seems that the issue is recursive imports
def test_import_pdb ():
import pdb
pdb.set_trace ()
part of the stack trace is
File "C:\Python27\lib\pdb.py", line 72, in __init__
import readline
notice that an import in __init__ of django.http is also part of the stack trace
Read https://docs.djangoproject.com/en/dev/topics/testing/ about Django testing.
As I know it's better to use unittest or doctest shipped with django as it have several improvements for django-specific testing like form field output testing and some database features. Hovewer it's not essential and if you want to continue using nose - think you missed django environment setup:
from django.test.utils import setup_test_environment
setup_test_environment()
This lines needed to run your tests outside of ./manage.py --test
UPD
Yeah my previous thought's were wrong. So I just digged into sources of nose and nose-gae, and what I think - check HardenedModulesHook definition in your nose version, cause in trunk of nose I've found following:
class HardenedModulesHook(object):
...
def __init__(self,
module_dict,
imp_module=imp,
os_module=os,
dummy_thread_module=dummy_thread,
pickle_module=pickle):
...
That gives following - when noseGAE plugin begin() method is executed -> there self._install_hook(dev_appserver.HardenedModulesHook) is called which declares mixed-hook class and creates it's instance like self.hook = Hook(sys.modules, self._path). <- There is HardenedModulesHook.__init__ called with second argument as mystic '_path' however in NOSE this argument should be 'imp' module by default -> That makes an exception you've got:
_sf, path, _desc= self._imp.find_module(top, None)
AttributeError: 'str' object has no attribute 'find_module'
So I think it might be a problem with nose-gae :(