将DataTables插件与django框架集成 [英] Integrating DataTables plugin with django framework

查看:203
本文介绍了将DataTables插件与django框架集成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是django框架和DataTables的初学者。目前,我正在尝试加载一个从服务器返回的数据的jQuery DataTable。我已经使用django REST框架构建了一个API来将数据传递给DataTables。但是,我无法从服务器的json数据加载DataTable。请在下面找到我的代码片段,并且请求告诉我是否缺少任何东西。



index.html看起来像以下。

 < table id =packages_tableclass =table table-striped table-bordered> 
< thead>
< tr>
< th>用户名< / th>
< th>名字< / th>
< th>电子邮件< / th>
< / tr>
< / thead>
< tbody>
< tr>
< td>< / td>
< td>< / td>
< td>< / td>
< / tr>
< / tbody>
< / table>
< script type =text / javascript>
$(document).ready(function(){
$('#packages_table')。dataTable({
ajax:'http://127.0.0.1:3434/user/' ,
列:[
{data:username},
{data:first_name},
{data:email},
]
});
});
< / script>

urls.py,我已经定义了viewset,serializer和router看起来像这样。

  class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields =( 'username','first_name','email','is_staff')

#ViewSets定义视图行为。

class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer


#路由器提供一种自动确定URL conf的简单方法。
router = router.DefaultRouter()
router.register(r'user',UserViewSet)

#使用自动URL路由连接我们的API。
urlpatterns = [
url(r'^ admin /',include(admin.site.urls)),
url(r'^ $',include(datagrid_urls)),
#configure通过添加REST框架的登录和注销视图来使用可浏览的API
url(r'^',include(router.urls)),
url(r'^ api-auth /' ,include('rest_framework.urls',namespace ='rest_framework'))
] + static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)

而且,下面是来自url的json数据。

  
{
url:http://127.0.0.1:3434/user/2/,
username:morgoth,
first_name: morgoth,
email:duke.valafar@gmail.com,
is_staff:true
},
{
url http://127.0.0.1:3434/user/3/,
username:anna,
first_name:,
email:anna @ anna.com,
is_staff:false
},
{
url:http://127.0.0.1:3434/user/4/,
username:adam,
first_name:,
email :ada@abc.com,
is_staff:false
}
]

这里是我的调试书签

解决方案

解决方案



您需要使用以下初始化代码来匹配数据结构:

  $('#packages_table')。dataTable({
ajax:{
url :'http://127.0.0.1:3434/user/',
dataSrc:''
},
列:[
{data:username} ,
{data:first_name},
{data:email},
]
});

dataSrc 选项说明:


请注意,如果您的Ajax源只返回数据数组到
显示,而不是一个对象,将此参数设置为一个空的
字符串。


DEMO



  $(document).ready(function(){//仅用于演示的AJAX仿真$ .mockjax({url:'arrays.txt',responseTime:200,response:function(settings){this.responseText = [{url:http://127.0.0.1:3434/user/2/ ,username:morgoth,first_name:morgoth,email:duke.valafar@gmail.com,is_staff:true},{u rl:http://127.0.0.1:3434/user/3/,username:anna,first_name:,email:anna@anna.com,is_staff :false},{url:http://127.0.0.1:3434/user/4/,username:adam,first_name:,email:ada @ abc。 com,is_staff:false}]}}); var table = $('#packages_table')。DataTable({ajax:{url:arrays.txt,dataSrc:},列:[{data:username},{data first_name},{data:email}]});});  

 <!DOCTYPE html>< html>< head> < meta charset =ISO-8859-1> < link href =// cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css =stylesheet/> < script src =https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js>< / script> < script src =// cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js\"></script> < script src =http://vitalets.github.com/x-editable/assets/mockjax/jquery.mockjax.js>< / script>< / head>< body> < table id =packages_tableclass =display> < thead> < tr> < th>用户名< / th> < th>名字< / th> < th>电子邮件< / th> < / tr> < / thead> < tbody> < tr> < td>< / td> < td>< / td> < td>< / td> < / tr> < / tbody> < / table>< / body>< / html>  


I am a beginner in django framework and DataTables. Currently, I am trying to load a jquery DataTable with the data coming back from the server. I have built an api using django REST framework to pass the data to DataTables. However, I am not able to load the DataTable from the json data from the server. Please find below my code snippets and pleas tell me if I am missing anything.

the index.html looks like following.

<table id="packages_table" class="table table-striped table-bordered">
        <thead>
            <tr>
                <th>User Name</th>
                <th>First Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td></td>
                <td></td>
                <td></td>
            </tr>
        </tbody>
     </table>
<script type="text/javascript">
    $(document).ready(function () {
        $('#packages_table').dataTable({
            ajax: 'http://127.0.0.1:3434/user/',
            columns: [
                { "data": "username"},
                { "data": "first_name"},
                { "data": "email"},
            ]
        });
    });
</script>

urls.py, where I have defined the viewset, serializer and router looks like this.

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'first_name', 'email', 'is_staff')

# ViewSets define the view behavior.

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer


# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'user', UserViewSet)

# Wire up our API using automatic URL routing.
urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', include(datagrid_urls)),
    #configure to use the browsable API by adding REST framework's login and logout views
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]  + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

And, below is the json data from the url.

[
    {
        "url": "http://127.0.0.1:3434/user/2/",
        "username": "morgoth",
        "first_name": "morgoth",
        "email": "duke.valafar@gmail.com",
        "is_staff": true
    },
    {
        "url": "http://127.0.0.1:3434/user/3/",
        "username": "anna",
        "first_name": "",
        "email": "anna@anna.com",
        "is_staff": false
    },
    {
        "url": "http://127.0.0.1:3434/user/4/",
        "username": "adam",
        "first_name": "",
        "email": "ada@abc.com",
        "is_staff": false
    }
]

And here is my debug bookmarklet

解决方案

SOLUTION

You need to use the following initialization code to match your data structure:

$('#packages_table').dataTable({
    ajax: {
        url: 'http://127.0.0.1:3434/user/',
        dataSrc: '' 
    },
    columns: [
        { "data": "username"},
        { "data": "first_name"},
        { "data": "email"},
    ]
});

From the dataSrc option description:

Note that if your Ajax source simply returns an array of data to display, rather than an object, set this parameter to be an empty string.

DEMO

$(document).ready(function() {
  // AJAX emulation for demonstration only
  $.mockjax({
    url: 'arrays.txt',
    responseTime: 200,
    response: function(settings) {
      this.responseText = [
        {
          "url": "http://127.0.0.1:3434/user/2/",
          "username": "morgoth",
          "first_name": "morgoth",
          "email": "duke.valafar@gmail.com",
          "is_staff": true
        }, {
          "url": "http://127.0.0.1:3434/user/3/",
          "username": "anna",
          "first_name": "",
          "email": "anna@anna.com",
          "is_staff": false
        }, {
          "url": "http://127.0.0.1:3434/user/4/",
          "username": "adam",
          "first_name": "",
          "email": "ada@abc.com",
          "is_staff": false
        }
      ]
    }
  });

  var table = $('#packages_table').DataTable({
    ajax: {
      url: "arrays.txt",
      dataSrc: ""
    },
    columns: [
        { "data": "username" },
        { "data": "first_name"},
        { "data": "email"}
    ]    
  });

});

<!DOCTYPE html>
<html>

<head>
  <meta charset="ISO-8859-1">

  <link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
  <script src="http://vitalets.github.com/x-editable/assets/mockjax/jquery.mockjax.js"></script>

</head>

<body>
  <table id="packages_table" class="display">
    <thead>
      <tr>
        <th>User Name</th>
        <th>First Name</th>
        <th>Email</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td></td>
        <td></td>
        <td></td>
      </tr>
    </tbody>
  </table>
</body>

</html>

这篇关于将DataTables插件与django框架集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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