How To Display List Of Users Using Ajax Django That Get Updated While Adding New Users From Admin Page
I am trying to display a list of users that get updated using AJAX at the same time a new user is added using admin page . Django 1.9 , Python 3.5 , I am working with a windows ma
Solution 1:
Welcome to stackoverflow! If you simply wants to call Ajax using Django then You should try this:
views.py
defindex(request):
return render(request, 'index.html', locals())
defajax_view(request):
result = dict()
data_list = []
result['status'] = "success"for u in User.objects.all():
list_of_user = {'email': u.email, 'first_name': u.first_name}
data_list.append(list_of_user)
result['data'] = data_list
return HttpResponse(json.dumps(result), content_type='application/x-json')
index.html
<scriptsrc="/path/to/js/my_ajax.js"></script><tableclass="myTable"><thead></thead><tbody></tbody></table>
my_ajax.js
$( document ).ready(function() {
$.ajax({
type: 'GET',
url: '/ajax/',
success: function (result) {
if (result.status == "success") {
if (result['data']) {
jQuery.each(result['data'], function (i, val) {
$('.myTable').append(
'<tr><td id="first_name">'+val['first_name']+'</td>' +
'<td id="email">'+val['email']+'</td></tr>');
});
}
}
}
})
});
urls.py
url(r'^ajax/$', ajax_view, name='temp'), # Function calls ajax
url(r'^index/$', index, name='index'), # main function redirect to index.html
This will call your ajax and get User's data.
Post a Comment for "How To Display List Of Users Using Ajax Django That Get Updated While Adding New Users From Admin Page"