当尝试将django dict转换为json对象时,它说“'str'对象没有属性'_meta'”

时间:2014-07-16 13:37:08

标签: python ajax json django

我需要在下拉列表更改时更新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()时会出现此错误

enter image description here

我该如何修复此错误?需要快速帮助

2 个答案:

答案 0 :(得分:1)

这是serializers.serialize

的常见错误

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

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

答案 1 :(得分:0)

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)