Tabulator通过Ajax放置到Django REST端点-将表缩减为最后编辑的记录

问题描述 投票:0回答:1

我正在将Tabulator与Django一起使用来编辑模型。对单元格进行任何更改之后,我将使用setData对使用Django REST Framework创建的REST端点进行Ajax调用。数据库更新正常。问题在于服务器的响应仅包含已更新的单个记录,这使得制表器数据减少为仅该记录。

我的问题是,如何让Tabulator忽略响应,否则在编辑后将数据留给其他人?

我在这方面(包括Django,尤其是JavaScript)非常陌生,如果我错过了一些基本的知识,我们深表歉意。

我的制表符代码如下。

  1. function getCookie将按照Django文档here中的说明生成CSRF_TOKEN。然后将其作为header包含在'X-CSRFTOKEN': CSRF_TOKEN中。
  2. 变量ajaxConfigPut用于将方法设置为PUT并包含CSRF_TOKEN,如上所述。然后,将其用于稍后在[table.setData)的table.setData(updateurl, updateData, ajaxConfigPut);调用中。
  3. 最后的函数ajaxResponse只是检查响应是否为数组(因为Tabulator期望使用一个适合GET的数组,但是PUT响应只是单个{}对象。因此,此函数强制执行PUT响应到由一个对象[{}]组成的数组中。
  4.     <div id="example-table"></div>
    
        <script type="text/javascript">
    
            // get CSRF token
            // https://docs.djangoproject.com/en/dev/ref/csrf/#acquiring-the-token-if-csrf-use-sessions-and-csrf-cookie-httponly-are-false
            function getCookie(name) {
                var cookieValue = null;
                if (document.cookie && document.cookie !== '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = cookies[i].trim();
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                    }
                }
                }
                return cookieValue;
            }
    
            var CSRF_TOKEN = getCookie('csrftoken');
    
            // set variable to customise ajaxConfig for use in the setData call
            var ajaxConfigPut = {
                    method:"PUT", //set request type to Position
                    headers: {
                        // "Content-type": 'application/json; charset=utf-8', //set specific content type
                        'X-CSRFTOKEN': CSRF_TOKEN,
                    },
            };
    
            //create Tabulator on DOM element with id "example-table"
            var table = new Tabulator("#example-table", {
                ajaxURL:"{% url 'cust_listapi' %}", // reverse pick up the url since in a django template (?)
                height:205, // set height of table (in CSS or here), this enables the Virtual DOM and improves render speed dramatically (can be any valid css height value)
                layout:"fitColumns", //fit columns to width of table (optional)
                columns:[ //Define Table Columns
                    {title:"Name", field:"name", width:150, editor:true},
                    {title:"Age", field:"age", hozAlign:"center",editor:true},
                    {title:"Age_Bar", field:"age", hozAlign:"left", formatter:"progress"},
                    {title:"Customer Status", field:"is_customer", hozAlign:"left"},
                    // {title:"Favourite Color", field:"col"},
                    // {title:"Date Of Birth", field:"dob", sorter:"date", hozAlign:"center"},
                ],
                // see http://tabulator.info/docs/4.6/components#component-cell
                cellEdited:function(cell){ //trigger an alert message when the row is clicked
                    console.log("Cell edited in row " + cell.getData().id 
                            + " and column " + cell.getField()
                            + " from " + cell.getOldValue() + " to " 
                            + cell.getValue()
                            + ". The row pk=" + cell.getData().id 
                            );
                    console.log(cell.getData());
    
                    var updateurl = "{% url 'cust_listapi' %}" + cell.getData().id + "/"
                    console.log('URL is: ' + updateurl)
                    // Create variable from full row data but drop the id;
                    console.log('About to create updateData')
    
                    var updateData = {};
                    updateData[cell.getField()] = cell.getValue();
    
                    console.log(updateData);
    
                    console.log('About to setData');
                    table.setData(updateurl, updateData, ajaxConfigPut);
                    console.log('Finished setData');
                    //cell.restoreOldValue();
                },
                ajaxResponse:function(url, params, response){
                    console.log('Beginning ajaxResponse')
                    console.log('The type is:', typeof(response));
                    console.log(Array.isArray(response))
                    console.log(response)
                    result = response;
                    if(Array.isArray(response) === false){
                        result = [response];
                    };
                    return result;
                }
            });
    
        </script>
    

以下是表格在编辑之前的屏幕截图:Table Before Editing

这是编辑第一行后的屏幕截图(将“ Mabel”更改为“ Jemima”):Screenshot after editing

这是控制台日志:Console Log

我尝试修改端点的响应,以便返回数据库中的所有记录,但是这样做的问题是它不包括编辑,因此Tabulator表数据被覆盖。这是我在Django views.py中使用的代码。也许有一种方法可以返回已更改的数据?views.py

from rest_framework import generics, mixins

from apps.app_mymodel.models import Customer
from .serializers import CustomerSerializer

class CustomerListAPIView(generics.ListAPIView):
    serializer_class = CustomerSerializer
    queryset = Customer.objects.all()

class CustomerUpdateAPIView(generics.GenericAPIView,
                            mixins.ListModelMixin,
                            mixins.UpdateModelMixin):

    serializer_class = CustomerSerializer
    queryset = Customer.objects.all()

    # Override the put function here to return all records
    def put(self, request, *args, **kwargs):
        # return self.update(request, *args, **kwargs)
        return self.list(request, *args, **kwargs)

这里是序列化器:serializers.py

from rest_framework import serializers
from apps.app_mymodel.models import Customer

class CustomerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Customer
        fields = '__all__'

有人能指出我正确的方向吗?

我正在将Tabulator与Django一起使用来编辑模型。对单元格进行任何更改之后,我将使用setData对使用Django REST Framework创建的REST端点进行Ajax调用。数据库更新正常。 ...

django tabulator
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.