从管理页面添加新用户时,如何显示使用AJAX Django更新的用户列表 [英] How to display list of users using AJAX Django that get updated while adding new users from admin page

查看:74
本文介绍了从管理页面添加新用户时,如何显示使用AJAX Django更新的用户列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试显示使用AJAX更新的用户列表,同时使用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,我在Windows计算机上工作

Django 1.9 , Python 3.5 , I am working with a windows machine

我的index.html

My index.html

<table class="table">
        <thead>
          <tr>
            <th>Firstname</th>
            <th>Email</th>
          </tr>
        </thead>
        <tbody>
            {% for User in users %}
                <tr> 
                    <td>{{ User.username }}</td>
                    <td>{{ User.email }}</td>
                </tr>
            {% endfor %}
        </tbody>
      </table>

我的views.py

My views.py

def index(request):
context = RequestContext(request)
users=User.objects.all()
return render_to_response('index.html',{'users':users},context)

如何实现AJAX?请帮助我如何在Django中使用ajax并完成此简单任务。

How to implement AJAX ? Please help me how to use ajax with Django and fulfill this simple task.

推荐答案

欢迎使用stackoverflow!
如果您只想使用Django调用Ajax,则应尝试以下操作:

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

这将调用您的ajax并获取用户的数据。

This will call your ajax and get User's data.

这篇关于从管理页面添加新用户时,如何显示使用AJAX Django更新的用户列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆