0

How return json from queryset - A.objects.all() to bootstrap table (http://wenzhixin.net.cn/p/bootstrap-table/docs/examples.html):

<table data-toggle="table" data-url="data" data-cache="false" data-height="299">
    <thead>
        <tr>
            <th data-field="id">Item ID</th>
            <th data-field="name">Name</th>
        </tr>
    </thead>
</table>

in views:

data = serializers.serialize("json", A.objects.all())
return render(request, 'a.html', {'data': data})
pirr
  • 445
  • 1
  • 8
  • 15
  • 1
    why do you want to return a json here? You can directly send you data without serializing it and use template tags to display them in your page – Abhishek May 30 '15 at 17:32

3 Answers3

3

There is 2 modes : server or client

For server mode:

in utils.py :

from django.core.serializers import serialize
import json
def serialize_bootstraptable(queryset):
    json_data = serialize('json', queryset)
    json_final = {"total": queryset.count(), "rows": []}
    data = json.loads(json_data)
    for item in data:
        del item["model"]
        item["fields"].update({"id": item["pk"]})
        item = item["fields"]
        json_final['rows'].append(item)
    return json_final

in views.py :

from django.http import JsonResponse
json_send = serialize_bootstraptable(Model.objects.all())
return JsonResponse(json_send, safe=False)
Matleses
  • 71
  • 1
  • 7
1

You can use Django JsonResponse. See the documentation here.

You would do something like this:

def my_json_view(request):
    context = {'foo': bar}
    return JsonResponse(context)

See also this SO question here.

Hope this helps ! :)

Community
  • 1
  • 1
laugri
  • 597
  • 6
  • 13
1

Solution:

In views:

def test(request):
    data = A.objects.all().values()
    return render(request, 'test.html', {'data': data})

In template:

<script type="text/javascript">
    $(document).ready(function(){
        $('#table').bootstrapTable({
           data:{{data|safe}}
        });    
    });
</script>

<table id="table">
    <thead>
        <tr>
            <th data-field="id">Item ID</th>
            <th data-field="name">Name</th>
        </tr>
    </thead>
</table>
pirr
  • 445
  • 1
  • 8
  • 15