【问题标题】:When try to convert django dict to json object it says "'str' object has no attribute '_meta'"当尝试将 django dict 转换为 json 对象时,它说“'str'对象没有属性'_meta'”
【发布时间】:2014-07-16 13:37:08
【问题描述】:

当下拉列表更改时,我需要更新 HTML 表格。我正在使用 Ajax 来执行此操作。 这是HTML代码和Ajax代码 HTML 代码

<form role="form" action="/surveys/viewsurveys/{{ survey_id }}"   method="post" >
  <div class="form-group">{% csrf_token %}
    <input type="hidden" id="Surey_ID" name="Surey_ID" value="{{ survey_id }}">
    <label>Select Department or Section</label>
    <select id="dept" name="dept" class="form-control" onchange="allusers();">
      {% for items in dept_data  %}
         <option value="{{ items.id }}">{{ items.dept_name }}</option>
      {% endfor %}
    </select>
  </div>
 <div class="box-header">
    <h3 class="box-title">All &nbsp<small class="badge pull-right bg-green"> {{ counts.hr_count }}</small></h3>
 </div><!-- /.box-header -->

  <div class="box-body table-responsive">
  <table id="example2" class="table table-bordered table-hover">
      <thead>
        <tr>
           <th> </th>
           <th>First Name</th>
           <th>Last Name</th>
           <th>Email</th>
           <th>Username</th>
           <th>Data join</th>
           <th>last login</th>
           <th>Is Active</th>
        </tr>
      </thead>
      <tbody>
          {% for items in allusers %}
              <tr >
                <td>
                   <div class="input-group">
                       <span class="input-group-addon">
                         <input name="{{ items.id }}" type="checkbox">
                       </span>
                   </div><!-- /input-group -->
                 </td>
                 <td>{{ items.first_name }}</td>
                 <td>{{ items.last_name }}</td>
                 <td>{{ items.email }}</td>
                 <td>{{ items.username }}</td>
                 <td>{{ items.date_join }}</td>
                 <td>{{ items.last_login }}</td>
                 <td>{{ items.is_active }}</td>
                 <td class="text-center"><a class='btn btn-info btn-xs' href="/accounts/editusers/{{ items.id }}"><span class="glyphicon glyphicon-edit"></span> Edit</a>
               </td>
              </tr>
           {% endfor %}   
       </tbody>
           <tfoot>
             <tr>
                <th> </th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Email</th>
                <th>Username</th>
                <th>Data join</th>
                <th>last login</th>
                <th>Is Active</th>
              </tr>
            </tfoot>
     </table>
 </div><!-- /.box-body -->
</form>

Ajax 代码

function allusers()
  {

    $.ajax({
          url : "/surveys/ajaxalldeptusers",
          type : "POST",
          dataType: "json",
          data : {
             csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
             dept: $('#dept').val(),
             Surey_ID:$('#Surey_ID').val(),


          },

          success : function(json) {
           //$('#result').append( 'Server Response: ' + json.server_response);
           $('#box').html(json.message),
           console.log('my message' + json)
          },
          error : function(xhr,errmsg,err) {
          alert(xhr.status + ": " + xhr.responseText);
          }

        });

  }

后端

def ajax_all_dept_users(request):
    try:
        request.session['user_login_data']
        dept_data=SuUserDepartment.objects.filter(org=request.session['user_login_data']['org'])
        dept=request.POST.get('dept','')
        survey_id=request.POST.get('Surey_ID','')
        responce_data={}

        if request.method == 'POST':
            surey_data=SuSurey.objects.get(id=survey_id)
            allusers=SuUser.objects.filter(dept_id=dept)
            responce_data['allusers']=allusers
            responce_data['dept_data']=dept_data
            responce_data['surey_data']=surey_data
            responce_data['survey_id']=survey_id
            data = serializers.serialize('json', responce_data)
            return HttpResponse(json.dumps(data),content_type="application/json")
            #return HttpResponse(json.dumps({'allusers':allusers,'dept_data':dept_data,'surey_data':surey_data, 'survey_id':survey_id }),content_type="application/json")
            #return  render_to_response("pages/forms/publish.html",{'allusers':allusers,'dept_data':dept_data,'surey_data':surey_data, 'survey_id':survey_id },context_instance=RequestContext(request))


    except KeyError, e:
        messages={'alert':'You need to loging'}
        return render(request, 'index.html',{'messages': messages},context_instance=RequestContext(request)) 

我尝试调试并尝试找出问题。我发现当来到 serializers.serialize() 时它给出了这个错误

我该如何解决这个错误?需要快速帮助

【问题讨论】:

    标签: python ajax json django


    【解决方案1】:

    这是 serializers.serialize 的常见错误

    您正在尝试序列化一个不是模型查询集的对象。

    您的数据对象是一个字典,因此您不需要对其进行序列化,只需使用 json 转储返回该字典即可。

    【讨论】:

    • 我也试过了,我得到了 [, , , , , , , ] 不是 JSON 可序列化
    • 我不知道你在做什么。但是 return HttpResponse(json.dumps({'responce_data': responce_data}), content_type='application/json; charset=utf8') 必须有效。并且 response_data 必须是字典 {key: value}。正如我所说,serializers.serialize 用于查询集对象。
    【解决方案2】:
    responce_data['allusers']=allusers
    responce_data['dept_data']=dept_data
    responce_data['surey_data']=surey_data
    responce_data['survey_id']=survey_id
    data = serializers.serialize('json', responce_data)
    

    在这里,您的调用将 dict response_data 传递给序列化程序,而不是您应该传递要序列化的对象列表。

    所以创建对象列表并且不要在列表中指定字符串survey_id进行序列化。

    将您的代码更新为

    dept_data=list(SuUserDepartment.objects.filter(org=request.session['user_login_data']['org']))
    
    allusers=list(SuUser.objects.filter(dept_id=dept))
    responce_data = [ surey_data, ] + dept_data + allusers
    data = serializers.serialize('json', responce_data)
    

    【讨论】:

    • 我尝试得到这个错误 'QuerySet' object has no attribute '_meta'
    • @user3480706,您需要从查询集中创建列表。查看更新的答案以创建列表。
    • 它说“SuSurey”对象不可迭代
    • @user3480706,您可能想显示更新后的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 2017-07-13
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 2015-02-28
    • 1970-01-01
    相关资源
    最近更新 更多