#__init__.py
from flash.util import error, notice, error_next, notice_next
#exception.py
# -*- coding: utf-8
class RedirectException(Exception):
def __init__(self,redirect_uri,*args,**kwargs):
try:
self.error_message = kwargs['error']
del kwargs['error_message']
except KeyError:
self.error_message = None
try:
self.notice_message = kwargs['notice']
del kwargs['notice_message']
except KeyError:
self.notice_message = None
self.redirect_uri = redirect_uri
Exception.__init__(self,*args,**kwargs)
#middleware.py
from django.http import HttpResponse, HttpResponseRedirect
from flash.exception import RedirectException
class FlashMiddleware(object):
def process_request(self, request):
from util import data
data.session = request.session
old_flash = request.session.get('flash', None).copy()
try:
next_messages = request.session['flash']['next_messages'].copy()
print 'NEXT:', next_messages
except KeyError:
next_messages = {'errors':[],'notices':[]}
request.session.setdefault('flash', {})['next_messages'] = {
'errors': [], 'notices': []}
request.session['flash']['messages'] = next_messages
if old_flash != request.session['flash']:
request.session.modified = True
def process_exception(self, request, exception):
if isinstance(exception,RedirectException):
if exception.error_message:
request.session['flash']['next_messages']['errors'].append(
exception.error_message)
if exception.notice_message:
request.session['flash']['next_messages']['notices'].append(
exception.notice_message)
return HttpResponseRedirect(exception.redirect_uri)
#util.py
from threading import local
data = local()
def error(msg):
data.session['flash']['messages']['errors'].append(msg)
data.session.modified = True
def error_next(msg):
data.session['flash']['next_messages']['errors'].append(msg)
data.session.modified = True
def notice(msg):
data.session['flash']['messages']['notices'].append(msg)
data.session.modified = True
def notice_next(msg):
data.session['flash']['next_messages']['notices'].append(msg)
data.session.modified = True
#templatetags/flash_extras.py
# -*- coding: utf-8
from django import template
register = template.Library()
@register.inclusion_tag('flash/messages.html', takes_context=True)
def flash(context):
return {'errors': context['request'].session['flash']['messages']['errors'],
'notices': context['request'].session['flash']['messages']['notices']}
#templates/flash/messages.html
{% if errors or notices %}
<div class="flash-messages">
{% if errors %}
<ul class="errors">
{% for error in errors %}
<li>{{ error|safe }}</li>
{% endfor %}
</ul>
{% endif %}
{% if notices %}
<ul class="notices">
{% for notice in notices %}
<li>{{ notice|safe }}</li>
{% endfor %}
</ul>
{% endif %}
</div>
{% endif %}