Error when using django.template - django

I'm a beginner in django and I got a lot of errors when using template module from django.
The following works from the python shell:
from django import template
t = template.Template('My name is {{ name }}.')
When i use this code , i get the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/django/template/base.py", line 123, in __init__
if settings.TEMPLATE_DEBUG and origin is None:
File "/usr/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/usr/lib/python2.7/site-packages/django/conf/__init__.py", line 46, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting TEMPLATE_DEBUG,but
settings are not configured. You must either define the environment variable
DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Dose anyone have an idea about this error?

You can't access and run django projects from python shell. Django doesn't know what project you want to work on.
You have to do one of these things:
1. python manage.py shell
2. Set DJANGO_SETTINGS_MODULE environment variable in your OS to mysite.settings
3. Use setup_environ in the python interpreter:
from django.core.management import setup_environ
from mysite import settings
setup_environ(settings)
The first one is easiest and best method. Run your code in the django shell.

If you want to use the template system without the django shell, you can do:
from django.conf import settings
settings.configure()
and after this your code
t = template.Template('My name is {{ name }}.')

I also had the same problem.
The main point is that in the django book 2, this piece of code is not supposed for users to put into a Python IDLE started from your python.exe ( presumably in C:\Program Files\Python33 on Windows).
Rather, it is just showing how the piece of code will look like. The solution is simply run 'cmd' and change the directory to your 'mysite', and run
python manage.py shell
which ensure that the 'mysite.settings.py' is used.

Of course the #Sudipta's answer works correctly but (just for the future) for the explanation you can also visit the "Creating Template Objects" -> "A special Python prompt" section in Django book

To fix this issue, you need to run it in python manage.py shell instead of just python.
Reason: Well, many parts of Django rely on settings and you won't be able to use them until it knows which settings file to use. When you run it on python manage.py shell, Django knows which settings file to use and does the job for you.

The error message states that you need to set the DJANGO_SETTINGS_MODULE variable.
Running export DJANGO_SETTINGS_MODULE=mysite.settings, worked for me.

Related

Getting no module named _internals error while using Bloomberg API

I am currently using Python 2.7 and my OS is Windows 7. While attempting to use the Bloomberg API I am getting this error:
Traceback (most recent call last):
File "datagrab.py", line 1, in <module>
import blpapi, time, json
File "C:\Python27\lib\blpapi\__init__.py", line 5, in <module>
from .internals import CorrelationId
File "C:\Python27\lib\blpapi\internals.py", line 50, in <module>
_internals = swig_import_helper()
File "C:\Python27\lib\blpapi\internals.py", line 42, in swig_import_helper
import _internals
ImportError: No module named _internals
I have set my path variable to point to blpapi3_64.dll and also updated my bloomberg terminal. I have also moved the local blpapi API to a different directory but still the problem exists.
I am kind of new to this API in general. So can someone please guide me?
Thank you in advance!
From your question is sounds like maybe you have tried this, but just outlining one possible solution from the README in the Python Supported Release release available here.
Note that many Python installations add the current directory to the
module search path. If the Python interpreter is invoked from the
installer directory, such a configuration will attempt to use the
(incomplete) local blpapi directory as a module. If the above
import line fails with the message Import Error: No module named
_internals, move to a different directory before invoking python.
I know this question is a bit stale, but in case people end up here like me. Do you have the C++ version of blpapi? it is a requirement for the python api as mentioned here: https://www.bloomberg.com/professional/support/api-library/
so download the C++ zip installer, extract somewhere, and then add it as an environment variable so that the python api can find it:
Environment variable name: BLPAPI_ROOT
Value: C:\blp\blpapi_cpp_3.8.18.1 (THIS IS WHERE MINE IS INSTALLED, YOUR VALUE HERE MAY BE DIFFERENT)
Hope that helps!

Problems Running django-autocomplete-light test_application

So I have a virtualenv with the following installed modules:
Django (1.7.7)
django-autocomplete-light (2.1.0rc3, /Users/username/.virtualenvs/testaclite/src/autocomplete-light)
django-autoslug (1.7.2)
django-cities-light (3.1.2)
pip (6.0.8)
setuptools (12.0.5)
six (1.9.0)
South (1.0.2)
Unidecode (0.4.17)
Using the following instructions from the README.rst file that comes with the test project for django-autocomplete-light, I then go to the folder /Users/username/.virtualenvs/testaclite/src/autocomplete-light/test_project
I then execute ./manage.py runserver and get the following result:
Traceback (most recent call last):
File "./manage.py", line 8, in <module>
from django.core.management import execute_from_command_line
ImportError: No module named django.core.management
What's going on here? How can I debug this and move forward?
This specific problem was due to an oversight on my part. I did not have my python virtual environment activated. Therefore, python was not being loaded at that moment.
Hopefully, others will benefit from this and not make the same mistake I did.
That being said, the test_project still doesn't fully work. It is full of page not found errors. Maybe it will be repaired / updated soon.
The README has just been fixed, sorry about that.
There was two mistakes in the README:
https://github.com/yourlabs/django-autocomplete-light/commit/d23d2ce0aaf1b657e95486e47a2fe1b10242e257
https://github.com/yourlabs/django-autocomplete-light/commit/5d36be09f0fa3055fc785f2c4d048f927eb57792
I hope everything is working now, feel free to ping us with your question URL on #yourlabs on IRC or on the mailing list.

Django App Engine can't find antlr3 module

I'm trying to set up a Django app to run on GAE, and am using the on_production_server test to choose between dev vs. production settings in settings.py.
However, when I run
python manage.py runserver
I get:
Traceback (most recent call last):
File "manage.py", line 11, in <module>
import settings
File "/home/guillaume/myproject/settings.py", line 10, in <module>
from djangoappengine.utils import on_production_server, have_appserver
File "/home/guillaume/myproject/djangoappengine/utils.py", line 18, in <module>
'Error was: %s' % e)
Exception: Could not get appid. Is your app.yaml file missing?
Error was: No module named antlr3
I tried adding the following to settings.py:
import sys
sys.path.append('/usr/local/google_appengine/lib/')
And this line to the very end of .profile:
PATH="$PATH:/usr/local/google_appengine/"
But neither gets rid of the error. I'm really new to working with paths so I'm kind of fumbling around blindly here. Can anyone help?
Python2.5v or 2.7v?
And what about GAE SDK version?
Did you try this?
Saw this question while having the same problem. Solved it by installing antlr 3.1.1 python runtime from Here.

pycharm - how to "run" a project with add_to_builtins?

i am using pycharm with django. When i do the runserver command, my project starts up and everything is fine.
if i use the pycharm run command - that green arrow at the top - then i get problems.
The problems are:
runnerw.exe C:\development\python\python.exe manage.py runserver 127.0.0.1:8000
Traceback (most recent call last):
File "manage.py", line 11, in
import settings
File "C:\development\PycharmProjects\dumpstown\settings.py", line 185, in
add_to_builtins('gravatar.templatetags.gravatar')
File "C:\development\python\lib\site-packages\django\template\base.py", line 1017, in add_to_builtins
builtins.append(import_library(module))
File "C:\development\python\lib\site-packages\django\template\base.py", line 963, in import_library
raise InvalidTemplateLibrary("ImportError raised loading %s: %s" % (taglib_module, e))
django.template.base.InvalidTemplateLibrary: ImportError raised loading
gravatar.templatetags.gravatar: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
Process finished with exit code 1
And stem from my use of add_to_builtins here: (this is in the settings.py file)
#gravatar stuff here.
add_to_builtins('gravatar.templatetags.gravatar')
I know this is the problem, because if i remove this line in the settings.py file? everything works fine.
Is there a way to remedy this problem for pycharm?
You need to set your Django settings module in Settings | Django Support | Settings
http://www.jetbrains.com/pycharm/webhelp/django-support.html
UPDATED
The problem with django-gravatar is that it's templatetags import django.contrib.auth.models.User which relies on settings module while setting module is loaded in Django by DJANGO_SETTINGS_MODULE environment variable, which is set internally by execute_manager function call in manage.py, which is executed AFTER import of settings. So when you use undocumented add_to_builtins feature just in settings.py at that point you have no DJANGO_SETTINGS_MODULE env variable set. So that is not a problem of PyCharm, but a problem of unset environment variable and usage of undocumented Django feature add_to_builtin.
When I ran the same project from Unix console I get the same error.
Probably you have DJANGO_SETTINGS_MODULE set in your environment if it works from console.
So to make it work in PyCharm you need to set up the variable in Django run configuration.
You can read here about that (see Environment variable section).
As i answered here: https://stackoverflow.com/a/11299516/1061426
pycharm is broken and doesn't work with add_to_builtins. The two obvious solutions are:
don't use pycharm, use some free django plugins for eclipse, or old school text editing?
use pycharm, just don't use add_to_builtins. This is the route i've gone down - it is annoying fixing all the template's to import a module, but it was a lot simpler in my case than the hassle of porting across to a new IDE.

Django manage.py syncdb can't find my settings file on CentOS

I'm deploying my django application onto a CentOS 5.5 server, with django-1.1.4 over python-2.6.5.
I have multiple settings files inside the myapp/settings/ folder.
I would like to run the syncdb; here's what I do (with myapp inside myproject folder):
$> cd /var/www/apps/myproject
$> export PYTHONPATH=/var/www/apps/myproject
$> export DJANGO_SETTINGS_MODULE=myapp.settings.my_serverconfig
$> python26 myapp/manage.py syncdb
Django then issues an error like this :
Error: Can't find the file 'settings.py' in the directory containing 'myapp/manage.py'. It appears you've customized things.
You'll have to run django-admin.py, passing it your settings module.
(If the file settings.py does indeed exist, it's causing an ImportError somehow.)
Traceback (most recent call last):
File "emon/manage.py", line 17, in <module>
execute_manager(settings)
File "/usr/lib/python2.6/site-packages/django/core/management/__init__.py", line 360, in execute_manager
setup_environ(settings_mod)
File "/usr/lib/python2.6/site-packages/django/core/management/__init__.py", line 343, in setup_environ
project_module = import_module(project_name)
File "/usr/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
ImportError: No module named my_serverconfig
In the myapp.wsgi file, os.path is appended with myproject path, and the os.environ['DJANGO_SETTINGS_MODULE'] is set also. Apache (through mod_wsgi) can start the app with no such error.
Finally, this works under Windows, where I run python-2.6.6 with django-1.1.1.
$> d:
$> cd d:\Code\myproject
$> export PYTHONPATH=d:\Code\myproject
$> export DJANGO_SETTINGS_MODULE=myapp.settings.dev_settings
$> python.exe myapp/manage.py syncdb
I know the versions are not the same, but I'm not sure that the minor differences may cause all my woe. Moreover I don't seem to find the exact same python version for Windows.
Any thoughts? Thanks a lot for reading.
O.
EDIT: added the manage.py content
#!/usr/bin/env python
from django.core.management import execute_manager
import os
if __name__ == "__main__":
settings = None
try:
if os.environ.has_key('LOCAL_SERVER_SETTINGS'):
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings.%s' % os.environ['LOCAL_SERVER_SETTINGS']
if os.environ.has_key('DJANGO_SETTINGS_MODULE'):
settings = __import__(os.environ['DJANGO_SETTINGS_MODULE'])
if settings is None:
import settings
execute_manager(settings)
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
import traceback
traceback.print_exc()
sys.exit(1)
EDIT : more on what happens in the myapppackage
I patch some django functions/classes from within the myapp.__init__ module. I was thinking the import django part in this module was causing a circular reference. The code is executed when I load myapp.settings.[any_config] and could have caused the crash. But then, how come the correct settings module is loaded with no error by WSGI, and that it works fine also on Windows? More : after commenting out the said code parts, the ImportError is still there.
If you move your settings file, you need to modify manage.py to tell it where to find it. The default is for it to be in the same directory as manage.py, but if you move into another python module(folder with __init__.py) then you need to update the reference in manage.py.
Look in manage.py where it imports your settings module, and import settings.dev_settings in your case instead. Look for 2 important lines
imp.find_module('settings') # Assumed to be in the same directory.
...
import settings
Change these to reference where you moved the settings file to(assuming you moved to settings.dev_settings):
imp.find_module('settings.dev_settings') # Assumed to be in the same directory.
...
from settings import dev_settings as settings
You can also use the command line option --settings to specify which settings file to use.