Using Django Cache Middleware causes contrib.auth unit tests to fail - django

Problem: When I add UpdateCacheMiddleware and FetchFromCacheMiddleware to my Django project, I get unittest failures. This is regardless of the CACHE_BACKEND I use (right now I am using locmem://, but the errors are the same when I use file:///path_to_cache)
My Middleware:
MIDDLEWARE_CLASSES = (
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
)
All my test failures look like the one below: 'NoneType' object is unsubscriptable
======================================================================
Error: test_last_login (django.contrib.auth.tests.remote_user.RemoteUserTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Python26\lib\site-packages\django\contrib\auth\tests\remote_user.py",
line 87, in test_last_login
self.assertNotEqual(default_login, response.context['user'].last_login)
TypeError: 'NoneType' object is unsubscriptable
I must be missing something (or doing something wrong) as I have searched around the web for this issue, but no one seems to have encountered it.
Steps to Reproduce:
Start a new django project (django-admin.py startproject myproject) and configure settings.py
Add CACHE_BACKEND to settings.py and add the two Cache Middlewares from Django
Run python manage.py test
Notes: There is only one test failure when using dummy:// cache and it is documented at: http://code.djangoproject.com/ticket/11640

The solution to the failing tests is to set CACHE_MIDDLEWARE_SECONDS to 0 (e.g. set this to be 0 in your dev environment). This will allow the django.contrib tests to all pass.

Related

Setting up local django environment for multiple domains

I'm trying to set up a Django application that will accept multiple subdomain URLs. I'd like to test this locally. Since I can't nail this first step of passing in a url that has a subdomain, I can't get to the second part (figuring out if the URLconf I've set up for django-subdomains is working). The middleware checks for a subdomain, and chooses a URLconf file based on that subdomain.
I've set the following configs in /etc/hosts. When I've got the server running, and I hit these URLs, I go to the real test.com.
127.0.0.1 payments.test.com
127.0.0.1 rampup.test.com
(in case it matters) django-subdomains middleware settings from settings.py:
SUBDOMAIN_URLCONFS = {
'payments': 'main.urls',
'rampup': 'rampup.urls'
}
MIDDLEWARE_CLASSES = (
'subdomains.middleware.SubdomainURLRoutingMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
Try this:
0.0.0.0 payments.test.com
0.0.0.0 rampup.test.com

Interpreting Django Traceback

I'm getting the following message. I somewhat understand that my project server cannot find the templates. However, I have no idea exactly what it's complaining about the templates. Would be great to hear alternate explanations of what's happening.
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/1/
Django Version: 1.4
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
'django.contrib.admin')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Template Loader Error:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
/home/stanley/mytemplates/polls/detail.html, polls/poll_detail.html (File does not exist)
Using loader django.template.loaders.app_directories.Loader:
/usr/local/lib/python2.7/dist-packages/django/contrib/auth/templates/polls/detail.html, polls/poll_detail.html (File does not exist)
/usr/local/lib/python2.7/dist-packages/django/contrib/admin/templates/polls/detail.html, polls/poll_detail.html (File does not exist)
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
136. response = response.render()
File "/usr/local/lib/python2.7/dist-packages/django/template/response.py" in render
104. self._set_content(self.rendered_content)
File "/usr/local/lib/python2.7/dist-packages/django/template/response.py" in rendered_content
79. template = self.resolve_template(self.template_name)
File "/usr/local/lib/python2.7/dist-packages/django/template/response.py" in resolve_template
55. return loader.select_template(template)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py" in select_template
193. raise TemplateDoesNotExist(', '.join(not_found))
Exception Type: TemplateDoesNotExist at /polls/1/
Exception Value: polls/detail.html, polls/poll_detail.html
I'll try to answer this in a bit more depth, especially to react to your statement "I think i got the templates in the wrong place." This can be easily solved using the traceback you posted.
First thing it tells you is some stuff about your environment - you can simply ignore this. This is not usefull for a TemplateLoaderError. It can be important though if any of your apps requires a special version of Python or something the like.
Next thing to spot is what kind of error has ocurred, and this one is extremely helpfull for your special case:
Template Loader Error:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
/home/stanley/mytemplates/polls/detail.html, polls/poll_detail.html (File does not exist)
If you take a closer look at this one, it tells you exactly where Django tried to find the specified templates, and what happened while it was looking for them (File does not exist). This will help you to find a solution to check if you really got your templates in the wrong place (which will happen quite often, even to a bit more experienced Django developers).
The next part is the traceback. You can savely ignore it in your case, because there is no file involved that is located in your project folder. If it was, that would mean you possibly screwed up something in the named file, and Django even tells you in which line your code did (possibly) provoke the exception.
Last part is information about the exception that has been raised, in your case TemplateDoesNotExist. Django has some special exceptions that you can find here . Other than these Django raises the standard Python exceptions.
Hope i didn't tell you too much you allready knew.
Do you have something like this in your settings?
PROJECT_ROOT = path.dirname(path.abspath(__file__)) #gets directory settings is in
TEMPLATE_DIRS = (
PROJECT_ROOT+'/templates',
)
You might have specified some path in your TEMPLATE_DIRS tuple in settings.py file.Django searches the html templates only in those directories.So add the following path to your TEMPLATE_DIRS.
TEMPLATE_DIRS = ('/polls',)

Django middleware: Isn't a middleware module error

I am using the middleware provided in https://gist.github.com/426829 to do cross site scripting.
However, when I add the middleware to MIDDLEWARE_CLASSES, I get the error:
ImproperlyConfigured: isn't a middleware module.
My MIDDLEWARE_CLASSES looks like this:
MIDDLEWARE_CLASSES = ('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'TempMiddleware',)
I have not changed any code in the gist. process_request and process_response methods are there. I am on Ubuntu running the latest versions of Python and Django.
What's TempMiddleware? The name of the module, or the name of the class? As you can see with the other entries, you need the fully-qualified Python path of the actual class. If TempMiddleware is the name of the module, you need TempMiddleware.MyMiddlewareClass (and you should really follow PEP8 naming conventions) - and if it's the name of the class, you need my_module.TempMiddleware.
Edit:
TempMiddleware is not importable. It's the name of the class, you must put the entire import path.
E.g:
'django.contrib.auth.middleware.AuthenticationMiddleware'
and not
'AuthenticationMiddleware'
So if your class is in app_name/middleware.py, it should be
app_name.middlaware.TempMiddleware
It just mean that in your settings file, the variable MIDDLEWARE_CLASSES contains a list of modules in which one of the listed module is not a middleware.
Possible causes:
you added a middleware that doesn't declare middleware methods: fix that by removing the last middleware you added
you added a correct middleware but forget to put a coma at the end of the name, so strings are concatenated and it make django thinks 2 middlewares are in fact one: fix that by adding the missing coma

django_cms ImproperlyConfigured: Error importing middleware cms.middleware.media

I'm moving an application that uses django_cms from one server, where everything worked, to another and have spent the last 4 hours trying to find the cause of this error. A suggestions very welcome!
mod_wsgi (pid=21972): Exception occurred within WSGI script '/var/www/vhosts/compdoctest.com/django/compdoc/django.wsgi'.
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 230, in __call__
self.load_middleware()
File "/usr/lib/python2.5/site-packages/django/core/handlers/base.py", line 42, in load_middleware
raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e))
ImproperlyConfigured: Error importing middleware cms.middleware.media: "No module named media"
The offending line is the last one in the middleware list in settings.py
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'cms.middleware.page.CurrentPageMiddleware',
'cms.middleware.user.CurrentUserMiddleware',
'cms.middleware.multilingual.MultilingualURLMiddleware',
'cms.middleware.media.PlaceholderMediaMiddleware',
)
If I remove the final line then the code continues and falls over later saying that item is required in middleware.
I'm using slightly different version of django, 1.2.1 final on the old working server and 1.2.3 final on the new server.
All the things I've tried:
The same version of django_cms - 2.1.0 beta 3 - that was used on the old server
The latest version on github - 2.1.0.beta2-550 Putting the cms, mptt, menus, publisher folders in the
app From python importing the
googled (nobody having the same problem that I can find)
middleware file directly (no problem)
result of opening in python:
python manage.py shell
Python 2.5.2 (r252:60911, Jan 20 2010, 23:14:04)
[GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import cms.middleware.media
>>> cms.middleware.media.__file__
'/var/www/vhosts/compdoctest.com/django/compdoc/cms/middleware/media.pyc'
>>> from django.forms.widgets import Media
>>> import cms.middleware.media
>>>
Thanks to my friend Bartosz Ptaszynski for pointing me in the right direction on this one. It was a path problem. Added this to the top of the settings.py file and it all magically started working.
sys.path.insert(0, '/path_to_app/app/')
And as he pointed out:
Exception occurred within WSGI script means that the path while running under the web server was wrong it's a completely different environment than the manage.py shell
I had the same problem. But since it only occurs when using mod_wsgi, another solution is adding the path in the apache config (rather than editing the syspath inside setting.py):
# mod_wsgi settings
WSGIDaemonProcess name user=user group=group python-path=/app_path/app/:/app_path/lib/python2.6/site-packages/:/app_path/
WSGIProcessGroup polykum
Including the site packages in the path is also given in the example of Jon Black.

non-consistent django error

I'm running django on Dreamhost right now with fastcgi, and I'm getting really weird behavior. First, the server runs Python 2.3. On my computer, I'm running 2.6 and all my source code works. When I put it on my host though, nothing works. Right now, when I pkill python and then load a page, the first error complains about a syntax error at 'class Item_list()' line:
from dtms.models import *
class Item_list():
def __init__(self, list = None, house_id = None):
self.list = list
self.house_id = house_id
def ret_list(self):
return self.list
Then, if I reload it again without changing anything, I get this error:
Django Version: 1.1 alpha 1 SVN-10114
Python Version: 2.3.5
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'mysite.dtms']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')
Traceback:
File "/home/victor/django/django_src/django/core/handlers/base.py" in get_response
82. callback, callback_args, callback_kwargs = resolver.resolve(
File "/home/victor/django/django_src/django/core/urlresolvers.py" in resolve
184. for pattern in self.url_patterns:
File "/home/victor/django/django_src/django/core/urlresolvers.py" in _get_url_patterns
212. raise ImproperlyConfigured("The included urlconf %s doesn't have any"
Exception Type: ImproperlyConfigured at /dtms/login/
Exception Value: The included urlconf mysite.urls doesn't have anypatterns in it
Any ideas?
class Item_list():
You can't include an empty inheritance list in Python 2.3. There seems to have been a change in the grammar that allows it now but not then.
It would normally be written:
class Item_list:
if you don't want any base classes. But generally these days you'd want to derive from object to get new-style classes.
I don't know much about your deployment environment, but in general when you've tried to import something and got an exception, it can leave behind partially-initialised modules in sys.modules that will frustrate future attempts to import them, resulting in otherwise inexplicable errors where properties and actions of the module are not where they were expected.
In general once an import has failed you should consider the environment lost and start again, but I don't know how your Django deployment copes with errors like that and process-restarting issues. Maybe the original error has left an interpreter running without having written the expected stuff to url_patterns, or something.