Coder Social home page Coder Social logo

twtrubiks / drf-datatable-example-server-side Goto Github PK

View Code? Open in Web Editor NEW
95.0 8.0 40.0 2.1 MB

DataTables Example (server-side) - Python Django REST framework

License: MIT License

Python 16.31% JavaScript 5.65% CSS 19.66% HTML 58.38%
django django-rest-framework datatables server-side

drf-datatable-example-server-side's Introduction

DRF-dataTable-Example-server-side

此版本為 django<2.0,以及搭配 SQLite 的範例,

如果使用 Django>2.0,請參考 django_2_and_mysql_5.7 branch

DataTables Example (server-side) - Python Django REST framework

DataTables (server-side) 搭配 Django REST framework 簡單範例 📝

特色

安裝套件

請在你的命令提示字元 (cmd ) 底下輸入

安裝 Django

這邊請注意,django<2.0 ( django 請安裝小於 2.0 的版本)

pip install Django==1.11.20

安裝 Django-REST-framework

pip install djangorestframework

安裝 django-model-utils

pip install django-model-utils

或是使用 cmd (命令提示字元)

pip install -r requirements.txt

說明

  • LOG 資訊非常重要,可以參考官網 django logging , 或是看範例裡面的 settings.py 裡面的 LOGGING。

  • 建議透過 django-db-backends 來觀看目前的 orm 到底執行了什麼 SQL 指令,可以到範例裡面的 settings.py 找 django.db.backends。

執行方法

使用命令提示字元 ( cmd ) 輸入下方指令

python manage.py runserver

然後瀏覽

http://127.0.0.1:8000/index/

執行畫面

首頁

[Get] api/music/{額外 DataTables 參數}

alt tag

新增

[POST] api/music/

alt tag

編輯

[PUT] api/music/{id}/

alt tag

刪除

[DELETE] api/music/{id}/

alt tag

搜尋 排序

[Get] api/music/{ 額外 DataTables 參數 }

alt tag

後記

  • 從影片中的 demo 可以很明顯的看出當資料量很大(5 萬筆)的時候,如果沒有用 server-side 的方式,而是一次全部載入,使用者體驗非常差。

  • 本範例前後端並沒有分離,而是寫在一起,比較好的方式,應該是前後端分離。

  • api document 可參考 api_document.html ,直接用瀏覽器開啟即可。 ( 文件教學可參考 aglio_tutorial )

更換 MySQL 資料庫

因為有些人反映換成 MySQL 之後無法 work,所以我測試了一下,

步驟一,先要多安裝兩個套件,

安裝 PyMySQL

pip install PyMySQL

安裝 mysqlclient

pip install mysqlclient

( 這個有可能安裝不起來,我自己最後是去找 mysqlclient-1.4.2-cp36-cp36m-win32.whl 安裝成功 )

settings.py 要改成

......

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'demo',
        'USER': 'root',
        'PASSWORD': 'password123',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}

......

也可參考之前的文章 Django 如何連結 MySQL

這邊要特別注意,MySQL 我使用 5.7,如果使用 MySQL 8.0,會遇到 django.db.utils.OperationalError: (2059, )

的問題,原因是 MySQL 8.0 的密碼加密方式改成了 caching_sha2_password,要再自行修改,簡單一點就是使用

MySQL 5.7。

執行環境

  • Python 3.6.6

Reference

Donation

文章都是我自己研究內化後原創,如果有幫助到您,也想鼓勵我的話,歡迎請我喝一杯咖啡:laughing:

alt tag

贊助者付款

License

MIT license

drf-datatable-example-server-side's People

Contributors

dadokkio avatar twtrubiks avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

drf-datatable-example-server-side's Issues

Edit and Delete

Hello,

this is more of a question not an issue. I don't see you implement these two methods(Edit and Delete) in views nor add them in urls.py

How do they work?

分页选择显示所有,django报错

js:
lengthMenu: [
[10, 25, 50, 100, -1],
['10 rows', '25 rows', '50 rows', '100 rows', 'Show All']
],
django:
TypeError: AssertionError('Negative indexing is not supported.',) is not JSON serializable

Pagination

Hey! hope this goes to help section...

I got almost everything that what I wanted to do to work by following your example. Except for pagination, it simply shows the first 10 records(which is what i wanted) but the rest are simply hidden. Pagination menu is displayed but is basically dead...
What could I be missing?

views.py
`
class TeamsViewSet(generics.ListCreateAPIView):
authentication_classes = [SessionAuthentication, BasicAuthentication]
permission_classes = [IsAuthenticated, IsAdminUser]

queryset = Team.objects.all()
serializer_class = TeamSerializer

def query_teams_by_args(**kwargs):
    draw = int(kwargs.get('draw', None)[0])
    length = int(kwargs.get('length', None)[0])
    start = int(kwargs.get('start', None)[0])
    search_value = kwargs.get('search[value]', None)[0]
    order_column = kwargs.get('order[0][column]', None)[0]
    order = kwargs.get('order[0][dir]', None)[0]

    order_column = ORDER_COLUMN_CHOICES[order_column]
    # django orm '-' -> desc
    if order == 'desc':
        order_column = '-' + order_column

    queryset = Team.objects.all()
    total = queryset.count()

    if search_value:
        queryset = queryset.filter(Q(toon1__name__icontains=search_value) |
                                   Q(toon2__name__icontains=search_value) |
                                   Q(toon3__name__icontains=search_value) |
                                   Q(toon4__name__icontains=search_value) |
                                   Q(toon5__name__icontains=search_value) |
                                   Q(author_username__icontains=search_value))

    count = queryset.count()
    queryset = queryset.order_by(order_column)[start:start + length]

    return {
        'items': queryset,
        'count': count,
        'total': total,
        'draw': draw
    }

def list(self, request):
    try:
        teams = TeamsViewSet.query_teams_by_args(**request.query_params)
        serializer = TeamSerializer(teams['items'], many=True)
        result = dict()
        result['data'] = serializer.data
        result['draw'] = teams['draw']
        result['recordsTotal'] = teams['total']
        result['recordsFiltered'] = teams['count']
        return Response(serializer.data)

    except Exception as e:
        return Response(str(e), status=status.HTTP_404_NOT_FOUND, template_name=None, content_type=None)

.js
table = $('#teams').DataTable({

    "ajax": "/teamsapi/?format=datatables",
    "serverSide": true,
    "processing": true,
    "columns": col,
    "dom": "Bfrtip",
    "rowCallback": function( row, data ) {
        /* This will filter out the teams which have already been assigned*/
        if ( data["assignment"] != "1" ) {
            $(row).hide();
        }
    }

});`

I got some functions that hide rows and reloads ajax. Not sure were I'm screwing up here...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.