Django custom middleware messes session middleware - django

I'm trying to diagnose the error in my custom middleware somehow brings down my session middleware.
The custom middleware is a simple app which deletes old files in some folders.
class DeleteMediaMiddleware(object):
time_limit = 100.
def check_folder(self,folder):
'''Deletes the files older than "time_limit" '''
os.chdir(folder)
files_in_folder = os.listdir(os.curdir)
for my_file in files_in_folder:
creation_time = os.path.getmtime(my_file)
file_lifetime = time.time() - creation_time
if file_lifetime > self.time_limit:
os.remove(my_file)
def process_request(self, request):
'''Standard middleware method which runs on every request'''
self.check_folder(config.input_folder)
self.check_folder(config.output_folder)
self.check_folder(config.plot_folder)
self.check_folder(config.report_folder)
return None
It is located in the Django project folder. (The levels is how Django creates by default. In my case the project is named expofit, and the folder structure is expofit/expofit)
project_folder_lvl1/project_folder_lvl2/mymiddleware.py
I added the middleware to Djagno settings:
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',
'server.mymiddleware.DeleteMediaMiddleware',
)
However, i end up with an error.
Exception Value: no such table: django_session
which is from checking a session value in views.py:
....
if request.session.has_key('user_id'):
....
As soon as i disable my middleware in Django settings, everything works normally.
UPDATE:
I sucesfully open the database, which is an sqlite file located in the project_folder_lvl1, and locate the table which isn't accessible.
Here is the complete Django traceback.
Environment:
Request Method: GET
Request URL: http://localhost:8000/expofit/
Django Version: 1.4.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'expofit_django_app',
'south',
'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',
'server.mymiddleware.DeleteMediaMiddleware')
Traceback:
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
77. return view_func(*args, **kwargs)
File "/home/alan/Desktop/expofit/expofit_hg/py/server/expofit_django_app/views.py" in check
59. return view(request, *args, **kwargs)
File "/home/alan/Desktop/expofit/expofit_hg/py/server/expofit_django_app/views.py" in start
23. if request.session.has_key('user_id'):
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py" in has_key
103. return key in self._session
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/contrib/sessions/backends/base.py" in _get_session
165. self._session_cache = self.load()
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/contrib/sessions/backends/db.py" in load
19. expire_date__gt=timezone.now()
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/db/models/manager.py" in get
131. return self.get_query_set().get(*args, **kwargs)
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/db/models/query.py" in get
361. num = len(clone)
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/db/models/query.py" in __len__
85. self._result_cache = list(self.iterator())
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/db/models/query.py" in iterator
291. for row in compiler.results_iter():
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in results_iter
763. for rows in self.execute_sql(MULTI):
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
818. cursor.execute(sql, params)
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/db/backends/util.py" in execute
40. return self.cursor.execute(sql, params)
File "/home/alan/Desktop/expofit/expofit_env/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py" in execute
337. return Database.Cursor.execute(self, query, params)
Exception Type: DatabaseError at /expofit/
Exception Value: no such table: django_session
Looking for ideas on how to debug this problem?

The problem was fixed by adding the absolute path to the sqlite database.
settings.py which yielded the error:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'expofit_database',
...
...
new settings.py:
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join( PROJECT_PATH, 'expofit_database'),
...
...
From what i figured, the problem was in calling the
os.chdir(folder)
inside the check_folder function which messed up the runtime paths.
Although setting the absolute path solved the problem for accessing the database, i removed the os.chdir(folder) to prevent potential errors in the future.
def check_folder(folder):
time_limit = 100.
files_in_folder = os.listdir(folder)
for file_name in files_in_folder:
file_path = os.path.join(folder,file_name)
creation_time = os.path.getmtime(file_path)
file_lifetime = time.time() - creation_time
if file_lifetime > time_limit:
os.remove(file_path)

Related

Django says OverflowError at /admin/ while trying to access /admin/

I noticed this error while trying to access /admin/. Whenever /admin/model_name or /admin/ or /admin/* is accessed django says OverflowError at /admin/ and regular expression code size limit exceeded. I did a little digging and came across this SO post. I have checked urls.py of app since regex are mostly used in urls. But all I have is a typical admin url, nothing complex.
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
....
]
Stack trace
Environment:
Request Method: GET
Request URL: http://domain/admin/
Django Version: 1.9.8
Python Version: 2.7.6
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'haystack',
'myapp.apps.core',
'myapp.apps.home',
'myapp.apps.accounts',
'myapp.apps.dashboard',
'myapp.apps.app1',
'myapp.apps.app3',
'myapp.apps.app5',
'myapp.apps.app6',
'myapp.apps.app7',
'myapp.apps.app8',
'myapp.apps.app9']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in wrapper
265. return self.admin_view(view, cacheable)(*args, **kwargs)
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
149. response = view_func(request, *args, **kwargs)
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
244. return view(request, *args, **kwargs)>
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)>
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in index
505. app_list = self.get_app_list(request)>
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in get_app_list
488. app_dict = self._build_app_dict(request)>
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/contrib/admin/sites.py" in _build_app_dict
473. current_app=self.name,
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/core/urlresolvers.py" in reverse
600. return force_text(iri_to_uri(resolver._revers>e_with_prefix(view, prefix, *args, **kwargs)))
File "/home/tuxbox/.virtualenvs/dekkho-qa/lib/python2.7/site-packages/django/core/urlresolvers.py" in _reverse_with_prefix>
488. if re.search('^%s%s' % (re.escape(_prefix), pattern), candidate_pat % candidate_subs, re.UNICODE):
File "/usr/lib/python2.7/re.py" in search>
142. return _compile(pattern, flags).search(string)
File "/usr/lib/python2.7/re.py" in _compile>
242. p = sre_compile.compile(pattern, flags)
File "/usr/lib/python2.7/sre_compile.py" in compile
521. groupindex, indexgroup
Exception Type: OverflowError at /admin/
Exception Value: regular expression code size limit exceeded
We are using django+apache.
Any help is much appreciated.
TIA
I have managed to solve this by restarting apache2 with
sudo service apache2 restart.
Of course, I have inspected apache2 error log with
sudo tail-f /var/logs/apache2/error.log
But that gave me same output as stack trace. Aforementioned is a work around for this issue. I am not marking this question as solved since real issue have not been found yet.
Thanks.

Django 1.9: 'AnonymousUser' object is not iterable

I was working on a Django 1.9 project, and suddenly this error popped up when I attempted to view my site's home page as a logged-out user.
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.9.7
Python Version: 2.7.10
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.sites',
'django.contrib.staticfiles',
'captcha',
'debug_toolbar',
'django_extensions',
'djstripe',
'crm',
'launch',
'rentals',
'widget_tweaks']
Installed Middleware:
[u'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
174. response = self.process_exception_by_middleware(e, request)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
172. response = response.render()
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/template/response.py" in render
160. self.content = self.rendered_content
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/template/response.py" in rendered_content
137. content = template.render(context, self._request)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/template/backends/django.py" in render
95. return self.template.render(context)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/template/base.py" in render
204. with context.bind_template(self):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py" in __enter__
17. return self.gen.next()
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/debug_toolbar/panels/templates/panel.py" in _request_context_bind_template
79. context = processor(self.request)
File "/Users/me/projects/rentalguru/src/rentals/processors.py" in allCategories
4. expense_categories = ExpenseCategory.objects.filter(user=request.user)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
122. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/query.py" in filter
790. return self._filter_or_exclude(False, *args, **kwargs)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/query.py" in _filter_or_exclude
808. clone.query.add_q(Q(*args, **kwargs))
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/sql/query.py" in add_q
1243. clause, _ = self._add_q(q_object, self.used_aliases)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/sql/query.py" in _add_q
1269. allow_joins=allow_joins, split_subq=split_subq,
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/sql/query.py" in build_filter
1174. self.check_related_objects(field, value, opts)
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/db/models/sql/query.py" in check_related_objects
1073. for v in value:
File "/Users/me/projects/rentalguru/lib/python2.7/site-packages/django/utils/functional.py" in inner
205. return func(self._wrapped, *args)
Exception Type: TypeError at /
Exception Value: 'AnonymousUser' object is not iterable
I'm not sure what would be causing this, and there's only one Google search result (for this site) for this error. I searched the code for the is_authenticated() method and didn't find anything, so I'm unsure where to turn. Working through the stack trace didn't show any useful (for me) information.
Here is my view:
class HomePageView(TemplateView):
template_name = 'home.html'
No login decorators or wrapped functions that I can tell.
Let me know if I need to post anything else.
EDIT: Asked for the model, here is the offending context processor instead:
def allCategories(request):
expense_categories = ExpenseCategory.objects.filter(user=request.user)
tags = {'categories': expense_categories}
return tags
I just stumbled myself upon this error. Thankfully the answer was provided in the comments:
As you said you tried to view home page with logged out user and this ExpenseCategory.objects.filter(user=request.user) filtering of Anonymous user (because you are logged out now) seems to be the culprit. Either you should allow only a authenticated user to this view or handle the case where your user is Anonymous
As for myself, I had a view, where I was filtering on a model based on the current user, which apparantly fails, when the user is the AnonymousUser.
I fixed this by adding a check:
if request.user.is_active:
expense_categories = ExpenseCategory.objects.filter(user=request.user)
Note that some people seem to prefer to check request.user.is_authenticated instead.
If you are dealing with a view that shall be accessed by logged in users only, you can also use the #login_required decorator.
For reference:
https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User.is_active
https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User.is_authenticated
https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.decorators.login_required

python-social-auth getting nothing but 400 Client Error: Bad Request

I've been trying to get python-social-auth working and all I ever get is the error Client Error: Bad Request which totally doesn't help me debug the situation. In my research, I've come across some mention of a bug here but there are no real indications of how to resolve it. This question addresses it too, but again, points to the same GitHub thread with no real resolutions.
I can't seem to figure out what is going on. It seems that it's trying to complete the authentication process, but is failing at /complete/facebook/. Here's the trace:
Environment:
Request Method: GET
Request URL: http://23.239.3.97:8000/complete/facebook/?redirect_state=big_long_string_of_letters_and_numbers_i_removed_for_security
Django Version: 1.6.1
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ms',
'users',
'south',
'social.apps.django_app.default')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.7/dist-packages/django/views/decorators/csrf.py" in wrapped_view
57. return view_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/social/apps/django_app/utils.py" in wrapper
52. return func(request, backend, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/social/apps/django_app/views.py" in complete
20. redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/social/actions.py" in do_complete
43. user = backend.complete(user=user, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/social/backends/base.py" in complete
40. return self.auth_complete(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/social/backends/facebook.py" in auth_complete
69. 'code': self.data['code']
File "/usr/local/lib/python2.7/dist-packages/social/backends/base.py" in get_querystring
229. return parse_qs(self.request(url, *args, **kwargs).text)
File "/usr/local/lib/python2.7/dist-packages/social/backends/base.py" in request
222. response.raise_for_status()
File "/usr/lib/python2.7/dist-packages/requests/models.py" in raise_for_status
773. raise HTTPError(http_error_msg, response=self)
Exception Type: HTTPError at /complete/facebook/
Exception Value: 400 Client Error: Bad Request
Here's the relevant settings.py info:
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_CONTEXT_PROCESSORS += (
'social.apps.django_app.context_processors.backends',
'social.apps.django_app.context_processors.login_redirect',
)
AUTHENTICATION_BACKENDS = (
'social.backends.facebook.FacebookOAuth2',
'django.contrib.auth.backends.ModelBackend',
)
SOCIAL_AUTH_FACEBOOK_KEY = '***' #replaced actual with *** for security
SOCIAL_AUTH_FACEBOOK_SECRET = '***' #replaced actual with *** for security
SOCIAL_AUTH_USERNAME_IS_FULL_EMAIL = True
LOGIN_REDIRECT_URL = '/'
SOCIAL_AUTH_LOGIN_URL = '/login/'
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/logged-in/'
SOCIAL_AUTH_LOGIN_ERROR_URL = '/login-error/'
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']
SOCIAL_AUTH_URL_NAMESPACE = 'social'
SOCIAL_AUTH_ADMIN_USER_SEARCH_FIELDS = ['username', 'email']
SOCIAL_AUTH_AUTHENTICATION_BACKENDS = (
'social.backends.facebook',
)
SOUTH_MIGRATION_MODULES = {
'default': 'social.apps.django_app.default.south_migrations',
}
The django dev server is returning a 500 error code, so it's something internal I'm guessing. I'm pulling my hair out on this one! Any ideas?
I had a similar error when I failed to set the correct callback URL in the app settings in facebook. You have to indicate "http://www.yourdomain.com/login/facebook" callback url in the advanced settings of the app. Hope this helps.

Is it possible to parse excel files in the forms.py?

I'm trying to do validation of an uploaded excel file in forms.py. Is this even possible?
I'm getting this error message "coercing to Unicode: need string or buffer, NoneType found"
forms.py
from .parse_excel import *
class FileSurveyForm(forms.ModelForm):
file = forms.FileField()
....
def clean_file(self):
data_file = self.cleaned_data.get('file')
data = parse_file(data_file.read())
netmaskRegex = '^(((128|192|224|240|248|252|254)\.0\.0\.0)|(255\.(0|128|192|224|240|248|252|254)\.0\.0)|(255\.255\.(0|128|192|224|240|248|252|254)\.0)|(255\.255\.255\.(0|128|192|224|240|248|252|254)))$'
for order in data:
if re.match(netmaskRegex, order['netmask']) is not None:
raise ValidationError("Invalid netmask!")
return file
parse_excel.py
import xlrd
def parse_file(datafile):
workbook = xlrd.open_workbook(file_contents=datafile)
sheet = workbook.sheet_by_index(0)
START_ROW = 35
END_ROW = 60
myList = []
for row in range(START_ROW,END_ROW):
values = (sheet.row_values(row, start_colx=1, end_colx=20))
headers = ["controller", "hostname", "domain", "ip_address", "netmask", "gateway", "dns1", "dns2", "ntp1", "ntp2",
"order_name", "order_phone", "order_email",
"shipping_adress", "shipping_city", "shipping_region", "shipping_region_code", "shipping_country", "shipping_diff"]
dictionary = dict(zip(headers, values))
myList.append(dictionary)
return myList
stack trace added:
Environment:
Request Method: POST
Request URL: http://10.21.145.103:8000/cooking/survey/file_upload/
Django Version: 1.6.6
Python Version: 2.6.6
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.formtools',
'contact',
'cooking')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/usr/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python2.6/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/usr/lib/python2.6/site-packages/django/views/generic/base.py" in dispatch
87. return handler(request, *args, **kwargs)
File "/home/jeremy.kwong/mysite/cooking/views.py" in post
101. if (form.is_valid() and ingredient_form.is_valid()):
File "/usr/lib/python2.6/site-packages/django/forms/forms.py" in is_valid
129. return self.is_bound and not bool(self.errors)
File "/usr/lib/python2.6/site-packages/django/forms/forms.py" in errors
121. self.full_clean()
File "/usr/lib/python2.6/site-packages/django/forms/forms.py" in full_clean
273. self._clean_fields()
File "/usr/lib/python2.6/site-packages/django/forms/forms.py" in _clean_fields
291. value = getattr(self, 'clean_%s' % name)()
File "/home/jeremy.kwong/mysite/cooking/forms.py" in clean_file
226. data = parse_file(data_file.read())
File "/home/jeremy.kwong/mysite/cooking/parse_excel.py" in parse_file
4. workbook = xlrd.open_workbook(file_contents=datafile)
File "/usr/lib/python2.6/site-packages/xlrd/__init__.py" in open_workbook
394. f = open(filename, "rb")
Exception Type: TypeError at /cooking/survey/file_upload/
Exception Value: coercing to Unicode: need string or buffer, NoneType found
This error occurs because file_contents argument of the xlrd.open_workbook() is empty.

Some cache problems

I'm wondering if I can delete a cached content made in template cache. I want to delete it from my view. I have in my template {% cache 500 cache_name sites.number %}
Is it possible to delete all "cache_name" cached content within the view, for example when some action is made?
I want to use per-vie cache. I do all what is described, but when I call: #cache_page(3600, cache="cache_name") I get error:
Exception Type: ValueError Exception
Value: need more than 1 value to
unpack
(Below is the traceback)
What I want to achieve is to cache all my template block or view and have a possibility to delete all cache connected with it when some actions are made. Pagination is included
Traceback:
Environment:
Request Method: GET
Request URL: http://localhost:8000/portfolio/
Django Version: 1.3 beta 1 SVN-15661
Python Version: 2.7.1
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'apps.index']
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')
Traceback:
File "E:\Python\django\core\handlers\base.py" in get_response
101. request.path_info)
File "E:\Python\django\core\urlresolvers.py" in resolve
252. sub_match = pattern.resolve(new_path)
File "E:\Python\django\core\urlresolvers.py" in resolve
252. sub_match = pattern.resolve(new_path)
File "E:\Python\django\core\urlresolvers.py" in resolve
158. return ResolverMatch(self.callback, args, kwargs, self.name)
File "E:\Python\django\core\urlresolvers.py" in _get_callback
164. self._callback = get_callable(self._callback_str)
File "E:\Python\django\utils\functional.py" in wrapper
124. result = func(*args)
File "E:\Python\django\core\urlresolvers.py" in get_callable
91. lookup_view = getattr(import_module(mod_name), func_name)
File "E:\Python\django\utils\importlib.py" in import_module
35. __import__(name)
File "E:\Python\apps\index\views.py" in <module>
29. #cache_page(600, cache='my_cache')
File "E:\Python\django\views\decorators\cache.py" in cache_page
58. return decorator_from_middleware_with_args(CacheMiddleware)(cache_timeout=args[0], cache_alias=cache_alias, key_prefix=key_prefix)
File "E:\Python\django\utils\decorators.py" in _make_decorator
81. middleware = middleware_class(*m_args, **m_kwargs)
File "E:\Python\django\middleware\cache.py" in __init__
204. self.cache = get_cache(self.cache_alias, **cache_kwargs)
File "E:\Python\django\core\cache\__init__.py" in get_cache
173. backend, location, params = parse_backend_conf(backend, **kwargs)
File "E:\Python\django\core\cache\__init__.py" in parse_backend_conf
131. mod_path, cls_name = backend.rsplit('.', 1)
Exception Type: ValueError at /portfolio/
Exception Value: need more than 1 value to unpack
What version of Django are you using? The parameter "cache" is only available in the development version. If you're using Django 1.2, you can only use "key_prefix".
http://docs.djangoproject.com/en/1.2/topics/cache/
The cache middleware caches every page
that doesn't have GET or POST
parameters.