【问题标题】:JsonResponse Returns NOT serializable error in Django viewJsonResponse 在 Django 视图中返回不可序列化的错误
【发布时间】:2020-08-15 14:55:24
【问题描述】:

我正在尝试以 Json 格式将数据传递给模板。 JsonResponse 返回错误

TypeError:类型方法的对象不是 JSON 可序列化的

这是导致错误的代码视图:

    if request.method == 'POST':
        ... SOME CODE HERE ....
    elif request.method == 'GET' and request.is_ajax():
        df = pd.read_csv(project.base_file,  encoding='ISO-8859-1')
        cols = df.keys
        return JsonResponse({'features': cols, }, status=200)
    else:
        form = mForm(project_id=pk)

Json 数据应在以下 Ajax 代码中处理:

  $(document).ready(function(){
    var id_number =$("#projectID").text();
        
    $("#btnSelect").click(function(){
        $.ajax({
            url: '',
            method: 'GET',
            data: {
                project_id: id_number,
            },
            success: function(response){
                $("#id_features").text(response.features)
            }
        });
    });
  });

【问题讨论】:

    标签: django ajax


    【解决方案1】:

    问题出在这里:

    df = pd.read_csv(project.base_file,  encoding='ISO-8859-1')
    cols = df.keys
              ^
    

    因为keys 是一种方法,您不能将方法序列化为 JSON(这就是错误标题对吗?),并且由于您希望将 df 值作为序列化 JSON,您必须调用该方法来实现它

    但是试试

    cols=df.keys()
    

    【讨论】:

      猜你喜欢
      • 2021-03-03
      • 2017-12-24
      • 2014-12-10
      • 2018-07-27
      • 1970-01-01
      • 2021-03-19
      • 2011-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多