没有获取模板Django中的对象

时间:2014-04-28 15:47:09

标签: python ajax json django

我收到json无法序列化的错误。

views.py

def get_post(request):
    if request.is_ajax():
        if request.method=="GET":
            craves = CraveData.objects.filter(person=request.user)
            print craves
            response = json.dumps({"craves":craves})
            return HttpResponse(response,mimetype="application/json")

crave.html

function next(){
                    alert("you in")
                $.ajax({
                                url: "/crave/get_post/",
                                type: "GET",
                                data: "",
                                success: function(response){
                                    alert('success');
                                    alert(response.craves)
                                    //$('.ajaxProgress').html(response.HTML_USER);
                                    $('.ajaxProgress').html(response.craves);                                   
                                },
                                error:function(){
                                    alert('some error');
                                }
                }); 
            }

我正在TypeError: [<CraveData: Gaurav>, <CraveData: Rahul>] is not JSON serializable

但是当我试图获得

craves = len(CraveData.objects.filter(person=request.user))

我正在获得价值。请帮助我在模板中获取对象。

1 个答案:

答案 0 :(得分:2)

使用正确的serializer

from django.core import serializers

def get_post(request):
    if request.is_ajax():
        if request.method=="GET":
            craves = CraveData.objects.filter(person=request.user)
            response = serializers.serialize('json', craves)
            return HttpResponse(response, mimetype="application/json")