django-rest-framework-datatables JSON将不会加载

时间:2019-07-11 08:39:07

标签: django datatables

我正在使用django-rest-framework-datatables并按照说明进行操作,但无法正常工作。

我遵循了这一点:

https://django-rest-framework-datatables.readthedocs.io/en/latest/index.html

我收到警告“ DataTables警告:表id =事务-无效的JSON响应。有关此错误的更多信息,请参见http://datatables.net/tn/1

我的网址位于名为“自定义”的应用程序中

app_name = 'custom'

router = routers.DefaultRouter()
router.register(r'exber', views.ExberViewSet)

urlpatterns = [

    url('^exber/api/', include(router.urls)),
    url('^exber/', views.exber_index, name='exber'),

]

我的观点:

class ExberViewSet(viewsets.ModelViewSet):
    queryset = Exber_transactions.objects.all()
    serializer_class = ExberSerializer


def exber_index(request):

    return render(request, 'custom/exber/transactions.html)

模型:

class Exber_transactions ( models.Model ):

    date = models.DateField ( null = True, blank = True )
    desc = models.CharField ( max_length = 100 )
    activity = models.CharField ( max_length = 100 )
    qty = models.DecimalField ( max_digits = 12, decimal_places = 3, default = 0 )
    price = models.DecimalField ( max_digits = 12, decimal_places = 2, default = 0 )
    accrued_int = models.DecimalField ( max_digits = 12, decimal_places = 3, default = 0 )
    amount = models.DecimalField ( max_digits = 12, decimal_places = 2, default = 0 )

序列化器:

class ExberSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField ( read_only = True )

    class Meta:
        model = Exber_transactions
        fields = ('date','desc', 'activity','qty', 'price', 'accrued_int', 'amount')
        datatables_always_serialize = ('id',)

这是表格:

<table id="transactions" class="table table-striped table-bordered" style="width:100%" data-server-side="true" data-ajax="custom/api/exber?format=datatables">

      <thead>
        <tr>
          <th data-data="date">date</th>
          <th data-data="desc">desc</th>
          <th data-data="activity">activity</th>
          <th data-data="qty">qty</th>
          <th data-data="price">price</th>
          <th data-data="accrued_int">accrued_int</th>
          <th data-data="amount">amount</th>
        </tr>
      </thead>

    </table>


<script>
  $(document).ready(function() {
      $('#transactions').DataTable();
  });
</script>

我怀疑它在某个地方?我尝试了很多组合。

谢谢。

2 个答案:

答案 0 :(得分:0)

该错误似乎是在序列化程序中未包含“ id”字段。我刚刚添加了这个。

fields = ('id', 'date','desc', 'activity','qty', 'price', 'accrued_int', 'amount'

答案 1 :(得分:0)

这是因为您的序列化程序中有这一行:

datatables_always_serialize = ('id',)

但是您没有在序列化程序 id 列表中包含 fields 字段。

因此,要解决此问题,请删除 datatables_always_serialize 行或将 id 添加到序列化程序字段中。