Permalink
Browse files

Added AJAX messages handling.

  • Loading branch information...
1 parent 58648fb commit d0bd7a03cbba2a9c6805ac4b1b5495cd6d002ad4 @carljm carljm committed Jun 28, 2011
Showing with 138 additions and 18 deletions.
  1. +1 −0 AUTHORS.rst
  2. +10 −3 CHANGES.rst
  3. +56 −9 README.rst
  4. +1 −1 messages_ui/__init__.py
  5. +49 −0 messages_ui/middleware.py
  6. +21 −3 messages_ui/static/messages_ui/jquery.messages-ui.js
  7. +0 −2 setup.py
View
1 AUTHORS.rst
@@ -2,3 +2,4 @@ Contributors
============
Jonny Gerig Meyer <jonny@oddbird.net>
+Carl Meyer <carl@oddbird.net>
View
13 CHANGES.rst
@@ -1,13 +1,20 @@
CHANGES
=======
-0.1.0 (2011.06.25)
+0.1.2 (2011.06.27)
------------------
-* Initial release.
+* Added ``AjaxMessagesMiddleware`` and ``handleAjax`` plugin option.
+
0.1.1 (2011.06.27)
------------------
-* Updated HTML template (removed <aside> and moved #messages to <ul>).
+* Updated HTML template (removed ``<aside>`` and moved ``#messages`` to
+ ``<ul>``).
+
+0.1.0 (2011.06.25)
+------------------
+
+* Initial release.
View
65 README.rst
@@ -1,21 +1,35 @@
jQuery messages-UI plugin package for Django
-===============================================
+============================================
+
+django-messages-ui adds JS and HTML to support the Django contrib.messages
+app. It should be called on the message list element, and accepts options for
+message selectors, transient messages (that disappear on click or key-press),
+and close-links.
+
+Messages can be dynamically added via ICanHaz.js, and there's a Python
+middleware to automatically add messages from the request into Ajax JSON
+responses.
-django-messages-ui adds JS and HTML to support the Django contrib.messages app. It should be called on the message list object, and accepts options for message selectors, transient messages, and close-links. Messages are added via ICanHaz.js.
Dependencies
------------
-- jQuery library (http://jquery.com/)
-- jQuery doTimeout (http://benalman.com/projects/jquery-dotimeout-plugin/)
-- iCanHaz (http://icanhazjs.com/)
-- django-icanhaz 0.2.0+ (https://github.com/carljm/django-icanhaz)
+- `jQuery`_ library
+- `jQuery doTimeout`_ plugin
+- (optionally) `ICanHaz.js`_
+- (optionally) `django-icanhaz`_ 0.2.0+
+
+.. _jQuery: http://jquery.com/
+.. _jQuery doTimeout: http://benalman.com/projects/jquery-dotimeout-plugin/
+.. _ICanHaz.js: http://icanhazjs.com/
+.. _django-icanhaz: https://github.com/carljm/django-icanhaz
Installation
------------
In your Django project settings, add "messages_ui" to your INSTALLED_APPS.
+
Usage
-----
@@ -31,8 +45,41 @@ Calling the plugin::
$('#messages').messages();
-Adding a message in JS::
+Calling the plugin with a variety of options explicitly configured to their
+default values::
+
+ $('#messages').messages({
+ message: '.message', // Selector for individual messages
+ closeLink: '.close', // Selector for link to close message
+ transientMessage: '.success', // Selector for transient messages
+ transientDelay: 500, // Transient message fade delay (ms)
+ transientFadeSpeed: 3000, // Transient message fade speed (ms)
+ handleAjax: false // Enable automatic AJAX handling
+ });
+
+Adding a message in JS (requires `ICanHaz.js`_)::
+
+ $(ich.message({message: "Sample Message", tags: "info"}).appendTo(
+ $('#messages'));
+
+To override the default JS template, add a ``message.html`` file to a directory
+listed in your ``ICANHAZ_DIRS`` setting (a `django-icanhaz`_ setting).
+
+
+Ajax
+~~~~
+
+To enable automatic handling of messages from Ajax requests, add
+``"messages_ui.middleware.AjaxMessagesMiddleware"`` to your
+``MIDDLEWARE_CLASSES`` setting, and pass ``handleAjax: true`` to the plugin
+initialization.
+
+.. warning::
- $(ich.message({message: "Sample Message", tags: "info"}).appendTo($('#messages'));
+ ``AjaxMessagesMiddleware`` converts all HTML AJAX responses into JSON
+ responses with a ``messages`` key, and the HTML embedded in an ``html``
+ key. If your site uses HTML AJAX responses, this will likely require
+ updates to other Ajax-handling code in your site.
-To override the default JS template, add a message.html file to a directory listed in your ICANHAZ_DIRS setting.
+ Similarly, ``handleAjax: true`` globally sets the default expected dataType
+ for AJAX requests to ``"json"``.
View
2 messages_ui/__init__.py
@@ -1 +1 @@
-__version__ = "0.1.1"
+__version__ = "0.1.2"
View
49 messages_ui/middleware.py
@@ -0,0 +1,49 @@
+try:
+ import json
+except ImportError:
+ from django.utils import simplejson as json
+
+from django.contrib import messages
+
+
+
+class AjaxMessagesMiddleware(object):
+ """
+ Middleware to handle messages for AJAX requests
+
+ If the AJAX response is already JSON, add a "messages" key to it (or append
+ to an existing "messages" key) a list of messages (each message is an
+ object with "level", "message", and "tags" keys). If an existing key
+ "no_messages" is present and True, messages will not be read or added.
+
+ If the AJAX response is currently html, turn it into JSON and stuff the
+ HTML content into the "html" key, adding a "messages" key as well.
+
+ If the AJAX response is neither json nor html, return it as-is (with no
+ messages attached, and without iterating over messages).
+
+ """
+ def process_response(self, request, response):
+ if request.is_ajax():
+ content_type = response['content-type'].split(";")[0]
+
+ if content_type == "application/json":
+ data = json.loads(response.content)
+ elif content_type == "text/html":
+ data = {"html": response.content}
+ else:
+ return response
+
+ if not data.get("no_messages", False):
+ messagelist = data.setdefault("messages", [])
+
+ for message in messages.get_messages(request):
+ messagelist.append({
+ "level": message.level,
+ "message": message.message,
+ "tags": message.tags,
+ })
+
+ response.content = json.dumps(data)
+ response["content-type"] = "application/json"
+ return response
View
24 messages_ui/static/messages_ui/jquery.messages-ui.js
@@ -1,5 +1,5 @@
/**
- * jQuery Messages UI 0.1.1
+ * jQuery Messages UI 0.1.2
*
* Copyright (c) 2011, Jonny Gerig Meyer
* All rights reserved.
@@ -30,6 +30,23 @@
});
});
}
+ if (options.handleAjax)
+ $.ajaxSetup(
+ {
+ dataType: "json",
+ dataFilter: function(data, type) {
+ if (type == "json") {
+ var parsed = $.parseJSON(data),
+ messages = $(parsed.messages);
+ messages.each(function() {
+ $(ich.message(this)).appendTo(messageList);
+ });
+ messageList.messages();
+ }
+ return data;
+ }
+ }
+ );
};
/* Setup plugin defaults */
@@ -38,6 +55,7 @@
transientMessage: '.success', // Selector for messages that will disappear on mousedown, keydown
closeLink: '.close', // Selector for link that closes message
transientDelay: 500, // Delay before mousedown or keydown events trigger transient message fade (ms)
- transientFadeSpeed: 3000 // Fade speed for transient messages (ms)
+ transientFadeSpeed: 3000, // Fade speed for transient messages (ms)
+ handleAjax: false // Enable automatic handling of messages in "messages" key of JSON AJAX response
};
-})(jQuery);
+})(jQuery);
View
2 setup.py
@@ -1,5 +1,3 @@
-
-
from os.path import join, dirname
from setuptools import setup

0 comments on commit d0bd7a0

Please sign in to comment.