Skip to content

Instantly share code, notes, and snippets.

@swasher
Forked from DmytroLitvinov/messages.html
Last active July 19, 2017 20:19
Show Gist options
  • Save swasher/5312cdbba5df83f9d14c77ee7939e012 to your computer and use it in GitHub Desktop.
Save swasher/5312cdbba5df83f9d14c77ee7939e012 to your computer and use it in GitHub Desktop.
[Django middleware for AJAX messages] Middleware for JSON responses. It adds to each JSON response array with messages from django.contrib.messages framework. It allows handle messages on a page with javascript. Django 1.10. #tags: django, python, ajax
<div id="messages">
{% for message in messages %}
<div {% if message.tags %}class="alert alert-dismissable alert-{{ message.tags }}"{% endif %}>
<a class="close" data-dismiss="alert" href="#">&times;</a>
{{ message }}
</div>
{% endfor %}
</div>
import json
from django.contrib import messages
class AjaxMessaging(object):
"""
Middlware for JSON responses. It adds to each JSON response array with messages from django.contrib.messages framework
It allows handle messages on a page with javascript
"""
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
response = self.get_response(request)
# Code to be executed for each request/response after
# the view is called.
if request.is_ajax():
if response['Content-Type'] in ["application/javascript", "application/json"]:
try:
if isinstance(response.content, bytes):
content = json.loads(response.content.decode(response.charset))
else:
content = json.load(response.content)
except ValueError:
return response
django_messages = []
for message in messages.get_messages(request):
django_messages.append({
"level": message.level,
"message": message.message,
"extra_tags": message.tags,
})
content['django_messages'] = django_messages
response.content = json.dumps(content)
return response
$(document).ready(function() {
function addMessage(text, extra_tags) {
var message = $(`
<div class="alert alert-dismissable alert-${extra_tags}">\n
<a class="close" data-dismiss="alert" href="#">&times;</a>\n
${text}\n
</div>`).hide();
$("#messages").append(message);
message.fadeIn(500);
setTimeout(function() {
message.fadeOut(500, function() {
message.remove();
});
}, 3000);
}
$(document).ajaxComplete(function (e, xhr, settings) {
var contentType = xhr.getResponseHeader("Content-Type");
if (contentType == "application/javascript" || contentType == "application/json") {
var json = $.evalJSON(xhr.responseText);
$.each(json.django_messages, function (i, item) {
addMessage(item.text, item.tags);
});
}
}).ajaxError(function (e, xhr, settings, exception) {
addMessage("There was an error processing your request, please try again.", "error");
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment