Why does'nt this simple django code work? - django

Why doesn't this code work?
from django.template import Template,Context
t = Template('Hello , {{name}}')
for name in ('Jack' , 'Sara' , 'John'):
print t.render(Context({'name' : name}))

It does not work if you type this directly in a native Python interpreter session; in fact it raises an ImproperlyConfigured exception:
In [4]: t = Template('Hello , {{name}}')
ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (38, 0))
---------------------------------------------------------------------------
ImproperlyConfigured Traceback (most recent call last)
...
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.
On the other hand it does work if you run your shell session using django-admin.py or manage.py commands which correctly load the required settings.

Related

Missing environment variables in OpenShift

I am trying to set up a Python 2.7 project in Openshift. The goal is to use Tornado Websockets. I have tried a number of examples, but I keep getting stuck on a number of missing environment variables that are shown in the examples.
My current app.py:
import imp
import os
try:
zvirtenv = os.path.join(os.environ['OPENSHIFT_PYTHON_DIR'],
'virtenv', 'bin', 'activate_this.py')
execfile(zvirtenv, dict(__file__ = zvirtenv) )
except IOError:
pass
if __name__ == '__main__':
ip = os.environ['OPENSHIFT_PYTHON_IP']
port = int(os.environ['OPENSHIFT_PYTHON_PORT'])
app = imp.load_source('application', 'main.py')
app.application.listen(port , ip)
app.ioloop.IOLoop.instance().start()
My install requires:
install_requires=['tornado', 'requests', 'beautifulsoup4']
This results in the following error:
---> Running application from Python script (app.py) ...
Traceback (most recent call last):
File "app.py", line 14, in <module>
zvirtenv = os.path.join(os.environ['OPENSHIFT_PYTHON_DIR'],
File "/opt/app-root/lib64/python2.7/UserDict.py", line 40, in __getitem__
raise KeyError(key)
KeyError: 'OPENSHIFT_PYTHON_DIR'
Can anybody help me out?
You are looking for environment variables set when using OpenShift 2, but are using OpenShift 3. Under OpenShift 3 you do not need to activate the Python virtual environment, it is done for you. Your app.py should listen on all interfaces and on port 8080. That address doesn't change so long as using the default Python S2I builder, so environment variables not used to pass it in.

Error with GDAL

I have tried and run this script from Rutger Kassies.
import gdal
import matplotlib.pyplot as plt
ds = gdal.Open('HDF4_SDS:sample:"A2002037045000.L2_LAC.SAMPLE.hdf":01')
data = ds.ReadAsArray()
ds = None
fig, ax = plt.subplots(figsize=(6,6))
ax.imshow(data[0,:,:], cmap=plt.cm.Greys, vmin=1000, vmax=6000)
But then an error always occured:
Traceback (most recent call last):
File "D:\path\to\python\stackoverflow.py", line 5, in <module>
data = ds.ReadAsArray()
AttributeError: 'NoneType' object has no attribute 'ReadAsArray'
What's wrong with the script? Am I missing something? In installing GDAL I have followed this instruction http://pythongisandstuff.wordpress.com/2011/07/07/installing-gdal-and-ogr-for-python-on-windows/
Am using windows 7/32 bit/Python 2.7.
Thanks!
gdal.Open() is failing and returning 'None'. This produces the sometimes counterintuitive message "NoneType' object has no attribute ...". Quoting from Python: Attribute Error - 'NoneType' object has no attribute 'something', "NoneType means that instead of an instance of whatever Class or Object you think you're working with, you've actually got None. That usually means that an assignment or function call up above failed or returned an unexpected result."
Apparently GDAL is correctly installed. It could be that the file is not readable or that there is an issue with the HDF driver. Are you getting any error message like:
`HDF4_SDS:sample:"A2002037045000.L2_LAC.SAMPLE.hdf":01' does not
exist in the file system, and is not recognised as a supported dataset
name.
To get additional information you can try something like this instead of the gdal.Open() line in your script:
gdal.UseExceptions()
ds=None
try:
ds = gdal.Open('HDF4_SDS:sample:"A2002037045000.L2_LAC.SAMPLE.hdf":01')
except RuntimeError, err:
print "Exception: ", err
exit(1)
Also, there's an extra '}' at the end of the script.
By default, osgeo.gdal returns None on error, and does not normally raise informative exceptions. You can change this with gdal.UseExceptions().
Try something like this:
from osgeo import gdal
gdal.UseExceptions()
source_path = r'HDF4_SDS:sample:"D:\path\to\file\A2002037045000.L2_LAC.SAMPLE.hdf":01'
try:
ds = gdal.Open(source_path)
except RuntimeError as ex:
raise IOError(ex)
The last bit just re-raises the exception as an IOError rather than a RuntimeException.
The solution is to modify source_path to a working path to your data source, e.g., I see
IOError: `HDF4_SDS:sample:"A2002037045000.L2_LAC.SAMPLE.hdf":01' does not exist in the file system, and is not recognised as a supported dataset name.

Django v1.6 debug-toolbar Middleware Error No .rsplit()

I am trying to use django-debug-toolbar with my django application and it worked for django v1.5. However, I am trying to migrate the system to django v1.6 and it is generating the following error when I try to load any page.
python manage.py runserver
Validating models...
0 errors found
December 21, 2013 - 22:53:18
Django version 1.6.1, using settings 'MySite.settings'
Starting development server at http://XXX.XXX.XXX.XXX:XXXX/
Quit the server with CONTROL-C.
Internal Server Error: /
Traceback (most recent call last):
File "/home/user/django-env/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 90, in get_response
response = middleware_method(request)
File "/home/user/django-env/local/lib/python2.7/site-packages/debug_toolbar/middleware.py", line 45, in process_request
mod_path, func_name = func_path.rsplit('.', 1)
AttributeError: 'function' object has no attribute 'rsplit'
[21/Dec/2013 22:53:21] "GET / HTTP/1.1" 500 58172
The source has this note, but I'm not sure what they mean precisely (import_by_path):
def process_request(self, request):
# Decide whether the toolbar is active for this request.
func_path = dt_settings.CONFIG['SHOW_TOOLBAR_CALLBACK']
# Replace this with import_by_path in Django >= 1.6.
mod_path, func_name = func_path.rsplit('.', 1)
show_toolbar = getattr(import_module(mod_path), func_name)
if not show_toolbar(request):
return
Also, while we're at it. Any idea what this message means as well?
/home/user/django-env/local/lib/python2.7/site-packages/debug_toolbar/settings.py:68: DeprecationWarning: SHOW_TOOLBAR_CALLBACK is now a dotted path. Update your DEBUG_TOOLBAR_CONFIG setting.
"DEBUG_TOOLBAR_CONFIG setting.", DeprecationWarning)
My settings.py:
def custom_show_toolbar(request):
return True # Always show toolbar, for example purposes only.
DEBUG_TOOLBAR_CONFIG = {
'INTERCEPT_REDIRECTS': False,
'SHOW_TOOLBAR_CALLBACK': custom_show_toolbar,
'INSERT_BEFORE': 'div',
'ENABLE_STACKTRACES' : True,
}
The problem is described by the message you get (which should not be a deprecation warning, rather it should be a TypeError, that's probably a bug in debug_toolbar):
SHOW_TOOLBAR_CALLBACK is now a dotted path. Update your DEBUG_TOOLBAR_CONFIG setting
The SHOW_TOOLBAR_CALLBACK setting used to be a callable, but now it is a dotted path to a callable: a string. The code you quoted tries to rsplit the value of SHOW_TOOLBAR_CALLBACK, but because you can't rsplit a function object, you get an error.
To solve this, put your callback into another python file, for example your_site/toolbar_stuff.py, and adjust the setting to 'SHOW_TOOLBAR_CALLBACK': 'your_site.toolbar_stuff.custom_show_toolbar'. You can test if this works beforehand by trying in the shell:
from your_site.toolbar_stuff import custom_show_toolbar
If that works, your new setting should work, too.

cannot install django-filebrowser app

I did exactly as it says here: http://readthedocs.org/docs/django-filebrowser/en/latest/quickstart.html#quickstart (only used easy_install instead of pip)
it seems that I get an import error when trying to connect to admin interface:
Request Method: GET
Request URL: http://localhost:8000/admin/
Django Version: 1.3
Exception Type: ImportError
Exception Value:
No module named sites
Exception Location: c:\workspace\expedeat\..\expedeat\urls.py in <module>, line 5
Python Executable: c:\Tools\Python26\python.exe
Python Version: 2.6.4
the import the exception comes from is: from filebrowser.sites import site in urls.py
Also testing filebrowser fails with this message:
Creating test database for alias 'default'...
.......F......
======================================================================
FAIL: test_directory (filebrowser.tests.settings.SettingsTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "c:\Tools\Python26\lib\site-packages\django_filebrowser-3.3.0-py2.6.egg\filebrowser\tests\set
tings.py", line 29, in test_directory
self.assertEqual(os.path.exists(os.path.join(MEDIA_ROOT,DIRECTORY)), 1)
AssertionError: False != 1
----------------------------------------------------------------------
Ran 14 tests in 0.008s
FAILED (failures=1)
Destroying test database for alias 'default'...
I must be doing something wrong. Any help would be appreciated.
the sites.py module does not exist in version you are using, so the error message is correct.
the installation doc you are using is for version 3.4. The pip install is 3.3. The difference being in the urls.py
3.4
from filebrowser.sites import site
urlpatterns = patterns('',
url(r'^admin/filebrowser/', include(site.urls)),
)
3.3
urlpatterns = patterns('',
(r'^admin/filebrowser/', include('filebrowser.urls')),
)
The test fails because it's looking for a non-existing directory.
To find out what directory it's looking for, do the following:
% python ./manage.py shell
>>> from django.conf import settings
>>> import filebrowser.settings
>>> filebrowser.settings.MEDIA_ROOT
'/srv/repositories/project/media'
>>> filebrowser.settings.DIRECTORY
'uploads/'
Based on the output, you know what directory it's looking for, /srv/repositories/project/media/uploads in this example. Create the directory and you should be one step further on your way.
Using the "FILEBROWSER_" prefix, you can supply configuration for the filebrowser app.
I use the following in my settings.py :
FILEBROWSER_DIRECTORY = MEDIA_ROOT

Django loaddata settings error

When trying to use loaddata on my local machine (win/sqlite):
python django-admin.py loaddata dumpdata.json
I get the following error:
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE) ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
I am using djangoconfig app if that helps:
"""
Django-config settings loader.
"""
import os
CONFIG_IDENTIFIER = os.getenv("CONFIG_IDENTIFIER")
if CONFIG_IDENTIFIER is None:
CONFIG_IDENTIFIER = 'local'
# Import defaults
from config.base import *
# Import overrides
overrides = __import__(
"config." + CONFIG_IDENTIFIER,
globals(),
locals(),
["config"]
)
for attribute in dir(overrides):
if attribute.isupper():
globals()[attribute] = getattr(overrides, attribute)
projects>python manage.py loaddata dumpdata.json --settings=config.base
WARNING: Forced to run environment with LOCAL configuration.
Problem installing fixture 'dumpdata.json': Traceback
(most recent call last):
File "loaddata.py", line 174, in handle
obj.save(using=using)
...
File "C:\Python26\lib\site-packages\django\db\backends\sqlite3\base.py", line
234, in execute
return Database.Cursor.execute(self, query, params)
IntegrityError: columns app_label, model are not unique
Don't use django-admin.py for anything other than setting up an initial project. Once you have a project, use manage.py instead - it sets up the reference to your settings file.
syncdb will load content_types, you need to clear that table before loading data. Something like this:
c:\> sqlite3 classifier.db
sqlite> delete from django_content_type;
sqlite> ^Z
c:\> python django-admin.py loaddata dumpdata.json
Also, make sure you do not create a superuser, or any user, when you syncdb, as those are likely to also collide with your data fixture ...
There are two standard ways to provide your settings to Django.
Using set (or export on Unix) set DJANGO_SETTINGS_MODULE=mysite.settings
Alternatively as an option with django-admin.py --settings=mysite.settings
Django-config does things differently because it allows you to have multiple settings files. Django-config works with manage.py to specify which to use. You should use manage.py whenever possible; it sets up the environment. In your case try this where --settings points to the specific .py file you want to use from django-config's config folder.
django-admin.py loaddata dumpdata.json --settings=<config/settings.py>
Actually --settings wants python package syntax so maybe <mysite>.config.<your settings>.py