-
Notifications
You must be signed in to change notification settings - Fork 7
/
middleware.py
49 lines (37 loc) · 1.7 KB
/
middleware.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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