Workaround for Django 1.4 -> Django 1.6 message cookie error

The messages cookie format has changed in Django 1.5. However, support for the old format has been removed from Django 1.6 which means that if you migrate from Django 1.4 to Django 1.6 directly, you may get an unexpected and hard to solve IndexError:

 

Exception Type: IndexError
Exception Value:
list index out of range
Exception Location: (...) django/contrib/messages/storage/cookie.py in process_messages, line 37

 

I have reported an issue for this.

There's no easy workaround for this issue: you can't ask all your visitors to clear their cookies. As a workaround, I have created the following middleware to clear message cookies that fail to decode properly:

 

from django.contrib.messages.storage.cookie import CookieStorage
class FixMessageMiddleware(object):
"""
The message cookie format has changed from Django 1.4 to
Django 1.5. Django 1.5 probably supported both formats,
but if you move from 1.4.x to 1.6.x directly, you will run into
an IndexError:

Exception Type: IndexError Exception Value:
list index out of range
Exception Location: (...) django/contrib/messages/storage/cookie.py in process_messages, line 37
This small piece of middleware will track those cookies and destroy
them (leaving new-style in tact)
https://code.djangoproject.com/ticket/22426
DISCLAIMER: This middleware will not attempt to rewrite the messages! You may
miss important notifications because of this!
"""
def process_request(self, request):
data = request.COOKIES.get("messages")
storage = CookieStorage(request)
try:
storage._decode(data)
except IndexError:
del request.COOKIES['messages']

 

 

Last updated April 12, 2014, 7:11 p.m. | filed under django | django bug migrate 1.6 1.4 python
comments powered by Disqus