How to return multiple JSON objects in an AJAX request in django -
How to return multiple JSON objects in an AJAX request in django -
currently have view render template , homecoming 2 query lists. view shown below
def view_notifications(request,user_id): context_instance=requestcontext(request) user = user.objects.get(pk=user_id) user.profile.notifications = 0 user.profile.save() notices = list(notifications.objects.filter(n_reciever=user.id, is_read=0).order_by('-time')) number = notifications.objects.filter(n_reciever=user.id, is_read=0).order_by('-time').count() if number < 5: old_notices = list(notifications.objects.filter(n_reciever=user.id, is_read=1).order_by('-time')[:5]) else: old_notices = false notifications.objects.all().update(is_read = 1) homecoming render_to_response('profiles/notifications.html', {'new_notice': notices, 'old_notices':old_notices, 'number': number,},context_instance=requestcontext(request))
in template iterate through 2 lists , give background color list objects new as
<ul id="notification_list"> <li id="first"></li> {% notice in new_notice %} <li class="new"> <a href="{{notice.n_sender.profile.get_absolute_url}}">{{ notice.n_sender.profile.url_name}} </a> {{notice.message}} <a href="{{notice.object_url}}"> {{notice.object_type}}</a></li> {% endfor %} {% notice in old_notices %} <li> <a href="{{notice.n_sender.profile.get_absolute_url}}">{{ notice.n_sender.profile.url_name}} </a> {{notice.message}} <a href="{{notice.object_url}}"> {{notice.object_type}}<a/></li> {% endfor %} </ul>
now want same thing via ajax
phone call , display these objects in drop downwards list instead of new page, user can view notifications there without navigating away. cannot understand how can send 2 json encoded object_lists
. know how serialize object list json
data = serializers.serialize('json', notifications.objects.all())
but can send 2 object_lists way? not know how display json encoded object list in html. can access same way access objects in template?
please help
i initiate empty list, loop through notices , append dict list containing of required attributes. example, new_notices
list may this:
[{'absolute_url': 'blah', 'url_name': 'blah', 'message': 'blah', 'type': 'blah'}, {'absolute_url': 'foo', 'url_name': 'foo', 'message': 'foo', 'type': 'foo'}]
once have created list each set of notices (old , new), can send them:
from django.utils import simplejson django.http import httpresponse ... json = simplejson.dumps({'old': old_notices, 'new': new_notices}) homecoming httpresponse(json, mimetype='text/json')
django json jquery
Comments
Post a Comment