How to display list of users using AJAX Django that get updated while adding new users from admin page

后端 未结 1 1243
半阙折子戏
半阙折子戏 2021-01-17 06:02

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 wi

相关标签:
1条回答
  • 2021-01-17 06:21

    Welcome to stackoverflow! If you simply wants to call Ajax using Django then You should try this:

    views.py

    def index(request):
        return render(request, 'index.html', locals())
    
    
    def ajax_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

    <script src="/path/to/js/my_ajax.js"></script>
    <table class="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.

    0 讨论(0)
提交回复
热议问题