【问题标题】:How to send data generated from python to jquery datatable for rendering如何将python生成的数据发送到jquery数据表进行渲染
【发布时间】:2011-04-10 22:17:48
【问题描述】:

A] 问题总结:

在html页面上使用jquery datatable(http://www.datatables.net/),想将python查询生成的数据发送到javascript,这样就可以打印到表中了。如果有人可以为此提供示例实现或入门链接,那就太棒了。

B] 模型结构:

模型之间的层次关系如下:

UserReportecCountry(一)到 UserReportedCity(多)

UserReportedCity(one) 到 UserReportedStatus(many)

class UserReportedCountry(db.Model):
  country_name = db.StringProperty( required=True,
                          choices=['Afghanistan','Aring land Islands']
                         )

class UserReportedCity(db.Model):
  country = db.ReferenceProperty(UserReportedCountry, collection_name='cities')
  city_name = db.StringProperty(required=True)   

class UserReportedStatus(db.Model):
  city = db.ReferenceProperty(UserReportedCity, collection_name='statuses')
  status = db.BooleanProperty(required=True)
  date_time = db.DateTimeProperty(auto_now_add=True)

C] HTML 代码摘录

HTML 代码包括 jquery 、数据表 javascript 库。数据表 javascript 库配置为允许多列排序。

<!--importing javascript and css files -->
<style type="text/css">@import "/media/css/demo_table.css";</style>  
<script type="text/javascript" language="javascript" src="/media/js/jquery.js"></script>
<script type="text/javascript" src="/media/js/jquery.dataTables.js"></script>

<!-- Configuring the datatable javascript library to allow multicolumn sorting -->
<script type="text/javascript">
    /* Define two custom functions (asc and desc) for string sorting */
    jQuery.fn.dataTableExt.oSort['string-case-asc']  = function(x,y) {
        return ((x < y) ? -1 : ((x > y) ?  1 : 0));
    };

    jQuery.fn.dataTableExt.oSort['string-case-desc'] = function(x,y) {
        return ((x < y) ?  1 : ((x > y) ? -1 : 0));
    };

    $(document).ready(function() {
    /* Build the DataTable with third column using our custom sort functions */
    // #user_reported_data_table is the name of the table which is used to display the data reported by the users
    $('#user_reported_data_table').dataTable( {
        "aaSorting": [ [0,'asc'], [1,'asc'] ],
        "aoColumns": [
            null,
            null,
            { "sType": 'string-case' },
            null
        ]
    } );
} );
</script>

<!-- Table containing the data to be printed--> 
<div id="userReportedData">
<table cellpadding="0" cellspacing="0" border="0" class="display" id="user_reported_data_table">
    <thead>
        <tr>
            <th>Country</th>
            <th>City</th>
            <th>Status</th>
            <th>Reported at</th>
        </tr>
    </thead>

    <tbody>
        <tr class="gradeA">
            <td>United Status</td>
            <td>Boston</td>
            <td>Up</td>
            <td>5 minutes back</td>
        </tr>
    </tbody>
</table>    

C] python代码摘录:

代码摘录对数据进行查询,将数据放入“模板”中并将其发送到 HTML 页面(现在这不正常:()

__TEMPLATE_ALL_DATA_FROM_DATABASE = 'all_data_from_database'
def get(self): 
  template_values = {
        self.__TEMPLATE_ALL_DATA_FROM_DATABASE: self.get_data_reported_by_users()
    }

    self.response.out.write(template.render(self.__MAIN_HTML_PAGE, template_values))

def get_data_reported_by_users(self):
    return db.GqlQuery("SELECT * FROM UserReportedCountry ORDER BY country_name ASC")         

D] 正在使用的技术:

1] jQuery

2] Jquery 数据表

3] 谷歌应用引擎

4] 蟒蛇

5] Django。

感谢您的阅读。

[编辑#1]

基于@Mark 给出的响应的代码

尝试了以下

<!-- script snippet to setup the properties of the datatable(table which will contain site status    reported by the users) -->
<script type="text/javascript">
    /* Define two custom functions (asc and desc) for string sorting */
    jQuery.fn.dataTableExt.oSort['string-case-asc']  = function(x,y) {
        return ((x < y) ? -1 : ((x > y) ?  1 : 0));
    };

    jQuery.fn.dataTableExt.oSort['string-case-desc'] = function(x,y) {
        return ((x < y) ?  1 : ((x > y) ? -1 : 0));
    };

    $(document).ready(function() {
    /* Build the DataTable with third column using our custom sort functions */
    // #user_reported_data_table is the name of the table which is used to display the data reported by the users
    $('#user_reported_data_table').dataTable( {
        "aaSorting": [ [0,'asc'], [1,'asc'] ],
        "aoColumns": [
            null,
            null,
            { "sType": 'string-case' },
            null
        ],
        /* enabling serverside processing, specifying that the datasource for this will come from  
           file ajaxsource , function populate_world_wide_data
        */
        "bProcessing": true,
        "bServerSide": true,
        "sAjaxSource": "/ajaxsource/populate_world_wide_data"
    } );
} );
</script>

<div id="userReportedData">
<table cellpadding="0" cellspacing="0" border="0" class="display" id="user_reported_data_table">
    <thead>
        <tr>
            <th>Country</th>
            <th>City</th>
            <th>Status</th>
            <th>Reported at</th>
        </tr>
    </thead>
    <tbody>

    </tbody>
</table>    

Python代码,文件名为ajaxsource.py

从 django.utils 导入 simplejson 从 google.appengine.ext 导入数据库

def populate_world_wide_data(self,request):
    my_data_object = db.GqlQuery("SELECT * FROM UserReportedCountry ORDER BY country_name ASC") 
    json_object = simplejson.dumps(my_data_object)        
    self.response.out.write( json_object, mimetype='application/javascript')

然而,这仅在表格上显示“处理”。

几个查询,数据表如何知道在哪里打印国家,在哪里打印城市和状态?

[EDIT#2] 基于@Abdul Kader 给出的响应的代码

<script type="text/javascript" src="/media/js/jquery.dataTables.js"></script>

<!-- script snippet to setup the properties of the datatable(table which will contain site status reported by the users) -->
<script type="text/javascript">
    /* Define two custom functions (asc and desc) for string sorting */
    jQuery.fn.dataTableExt.oSort['string-case-asc']  = function(x,y) {
        return ((x < y) ? -1 : ((x > y) ?  1 : 0));
    };

    jQuery.fn.dataTableExt.oSort['string-case-desc'] = function(x,y) {
        return ((x < y) ?  1 : ((x > y) ? -1 : 0));
    };

    $(document).ready(function() {
    /* Build the DataTable with third column using our custom sort functions */
    // #user_reported_data_table is the name of the table which is used to display the data reported by the users
    $('#user_reported_data_table').dataTable( {
        "aaSorting": [ [0,'asc'], [1,'asc'] ],
        "aoColumns": [
            null,
            null,
            { "sType": 'string-case' },
            null
        ]
    } );
} );
</script>


<!-- Table containing the data to be printed--> 
<div id="userReportedData">
<table cellpadding="0" cellspacing="0" border="0" class="display" id="user_reported_data_table">
    <thead>
        <tr>
            <th>Country</th>
            <th>City</th>
            <th>Status</th>
            <th>Reported at</th>
        </tr>
    </thead>

   <tbody>
    <tr class="gradeA">
         {% for country in all_data_from_database %}
         <td>{{country}}</td>
         {%endfor%}
    </tr>
    </tbody>
</table>  

Python 代码 --

__TEMPLATE_ALL_DATA_FROM_DATABASE = 'all_data_from_database'

def get(self): 
    template_values = {
        self.__TEMPLATE_ALL_DATA_FROM_DATABASE: self.get_data_reported_by_users()
    }

    #rendering the html page and passing the template_values
    self.response.out.write(template.render(self.__MAIN_HTML_PAGE, template_values))

def get_data_reported_by_users(self):
    return db.GqlQuery("SELECT * FROM UserReportedCountry ORDER BY country_name ASC") 

html页面中打印的项目:

[EDIT#3] 有效的编辑。

我稍微修改了@Abdul Kader 给出的解决方案,以下已经奏效了

HTML 代码:

<!-- Table containing the data to be printed--> 
<div id="userReportedData">
<table cellpadding="0" cellspacing="0" border="0" class="display" id="user_reported_data_table">
    <thead>
        <tr>
            <th>Country</th>
            <th>City</th>
            <th>Status</th>
            <th>Reported at</th>
        </tr>
    </thead>

   <tbody>

    {% for country in countries %}
        {%for city in country.cities %}
            {%for status in city.statuses %}
                <tr class="gradeA">
                    <td>{{country.country_name}}</td>
                    <td>{{city.city_name}}</td>
                    <td>{{status.status}}</td>
                    <td>{{status.date_time }}</td>
                </tr>
            {%endfor%}  
        {%endfor%}      
    {%endfor%}

    </tbody>
</table>  

Python 代码:

def get(self):

   __TEMPLATE_ALL_DATA_FROM_DATABASE = 'countries'

    country_query = UserReportedCountry.all().order('country_name')
    country = country_query.fetch(10)

    template_values = {
        self.__TEMPLATE_ALL_DATA_FROM_DATABASE: country
    }

    self.response.out.write(template.render(self.__MAIN_HTML_PAGE, template_values))

增强请求:我相信这是一种非常基本的方法,并且可能有一个解决方案可能涉及一点 ajax 或更优雅。如果有人有使用基于 python 的数据表的示例或开源项目,请告诉我。

代码审查请求:有人可以审查我所做的代码,如果我做错了或者可以做得更好或更有效的事情,请告诉我。

【问题讨论】:

  • @Nick Johnson,感谢您的回复。我尝试将查询生成的数据直接发送到 html 页面,但没有奏效。由于这似乎是一个常见问题,我希望有一个可以转换数据的库,以便客户端的 javascript 代码可以读取它。我确信编写自己的自定义库不是正确的解决方案,因此我发布了这个问题。
  • '直接发送'如何?回应什么?数据表文档提供了大量示例——基本用法是生成一个常规的 HTML 表格。如果您想在页面加载后添加数据,这也有记录,正如@Mark 演示的那样。
  • 我认为作为第一步,您应该确保您的表格正确呈现。这似乎是您问题的核心。那么包含 boston/usa 的行呢……这只是一个示例还是您查询的实际输出?如果您的表格正确呈现,我将从数据表 (datatables.net/examples/basic_init/zero_config.html) 的最小选项开始,稍后添加更复杂的参数。

标签: jquery python google-app-engine datatable


【解决方案1】:

您必须像往常一样简单地从数据存储中创建表。插件将负责其余的工作。 模型

class UserReportedCountry(db.Model):
  country_name = db.StringProperty( required=True,
                          choices=['Afghanistan','Aring land Islands']
                         )

class UserReportedCity(db.Model):
  country = db.ReferenceProperty(UserReportedCountry, collection_name='cities')
  city_name = db.StringProperty(required=True)   

class UserReportedStatus(db.Model):
  city = db.ReferenceProperty(UserReportedCity, collection_name='statuses')
  status = db.BooleanProperty(required=True)
  date_time = db.DateTimeProperty(auto_now_add=True)

Python

class MainPage(webapp.RequestHandler):
    def get(self):
        User_country=UserReportedCountry.all().fetch(1000)
        return self.response.out.write(template.render('#pathtohtml','{'user_c':User_country}))

HTML

<!--importing javascript and css files -->
<style type="text/css">@import "/media/css/demo_table.css";</style>  
<script type="text/javascript" language="javascript" src="/media/js/jquery.js"></script>
<script type="text/javascript" src="/media/js/jquery.dataTables.js"></script>

<!-- Configuring the datatable javascript library to allow multicolumn sorting -->
<script type="text/javascript">
    /* Define two custom functions (asc and desc) for string sorting */
    jQuery.fn.dataTableExt.oSort['string-case-asc']  = function(x,y) {
        return ((x < y) ? -1 : ((x > y) ?  1 : 0));
    };

    jQuery.fn.dataTableExt.oSort['string-case-desc'] = function(x,y) {
        return ((x < y) ?  1 : ((x > y) ? -1 : 0));
    };

    $(document).ready(function() {
    /* Build the DataTable with third column using our custom sort functions */
    // #user_reported_data_table is the name of the table which is used to display the data reported by the users
    $('#user_reported_data_table').dataTable( {
        "aaSorting": [ [0,'asc'], [1,'asc'] ],
        "aoColumns": [
            null,
            null,
            { "sType": 'string-case' },
            null
        ]
    } );
} );
</script>

<!-- Table containing the data to be printed--> 
<div id="userReportedData">
<table cellpadding="0" cellspacing="0" border="0" class="display" id="user_reported_data_table">
    <thead>
        <tr>
            <th>Country</th>
            <th>City</th>
            <th>Status</th>
            <th>Reported at</th>
        </tr>
    </thead>

    <tbody>
        <tr class="gradeA">
             {% for country in user_c %}
             <td>{{country}}</td>
             {%endfor%}
        </tr>
    </tbody>
</table>  

【讨论】:

  • @Abdul Kader,感谢您的回复。抱歉回复晚了,我将首先尝试@Mark在上述评论中给出的回复,并检查它是否有效。我也会通过您的回复,看看它是否适用于我所面临的情况。再次感谢您的回复。
  • @Abdul Kader,我根据您的回复尝试了代码。解释没有问题,但代码不会在 html 数据表上打印任何条目。代码和生成的数据表放在我的主帖的“EDIT#2”部分。
  • @bhavesh 确保您的 all_data_from_database 获取记录。导入日志并执行一些 logging.info() 以查找该 actullay 是否获取记录。还要确保数据存储中已经存在该类型的记录
  • @Abdul Kader,你成就了我的夜晚!!!。我稍微修改了你给出的解决方案,“EDIT#3”的解决方案已经奏效。问题是我们试图打印“国家”对象,需要访问“国家名称”和对象的其他字段。我仍然相信这是一种效率低下的机制来做我想做的事情。您能否查看我的代码并根据您的经验提供反馈。再次非常感谢您,非常感谢您的回复。
  • @bhavesh 我认为你不需要三个 for 循环。一个 for 循环就足够了。尝试弄清楚模板系统的呈现方式。
【解决方案2】:

在 DataTables 文档中,它们显示了返回数据“server-side”的示例。在他们的示例中,他们在服务器上使用 PHP,但它的返回方式是使用 JSON 编码。使用Python as well 很容易做到这一点。

编辑

关键是如何从服务器返回数据:

$(document).ready(function() {
    $('#example').dataTable( {
        "bProcessing": true,
        "bServerSide": true,
        "sAjaxSource": "url/to/json/returning/python"
    } );
} );

在上面的 javascript 中,它将直接调用 python Django 视图并期待 JSON 响应。

Django 视图类似于(我不是 Django 用户,所以这可能是关闭的):

from django.utils import simplejson

def ajax_example(request):
    ## do your processing
    ## your return data should be a python object
    return HttpResponse(simplejson.dumps(my_data_object), mimetype='application/javascript')

【讨论】:

  • 我很难理解您给定链接上的 php 代码。我会花更多的时间,但有没有更简单的方法来做到这一点?
  • @bhavesh,如果您可以绕过示例的 PHP 特性,它实际上非常简单。请参阅上面的修改。
  • 抱歉回复晚了,最近几天我无法上网。感谢您解释如何实现这一目标,我今晚将尝试这样做(美国东部时间晚上 8:00)并提供结果。
  • 如承诺的那样,我尝试了您给出的响应,但无法正常工作。我确信我犯了一个非常菜鸟的错误。我尝试的代码放在我主要帖子的“[EDIT#1]”部分。
  • 我尝试了@Abdul Kader 提供的机制,并在使事情正常工作方面取得了进展。我相信我使用的代码效率低下,并且可能有更好的机制来实现我想要做的事情。您能否对“EDIT#3”进行代码审查,如果我犯了任何错误,请告诉我。再次感谢 Mark 阅读我的问题并提供回复。
猜你喜欢
  • 2018-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多