CPC464
CPC464

Reputation: 63

How to parse output of .serialize('json', data) from Django in HTML

I'm trying to loop through a serialized JSON object and display it as a list, but instead of listing the attributes I want, the loop runs over each individual character in the JSON string. When I do the same with a list of dicts it works. What am I doing wrong?

Ptyhon code:

 def menu(request):
    # This is the object that I want to parse
    dishes = Dish.objects.all()
    dishes_ser = serializers.serialize('json', dishes)

    # This list is copy-pasted directly from the output of the serialized query 
    to see if I could get that to work
    check = [
        {"model": "orders.dish", "pk": 1, "fields": {"dish": "Pizza"}},
        {"model": "orders.dish", "pk": 3, "fields": {"dish": "Sub"}},
        {"model": "orders.dish", "pk": 5, "fields": {"dish": "Pasta"}},
        {"model": "orders.dish", "pk": 6, "fields": {"dish": "Salad"}},
        {"model": "orders.dish", "pk": 7, "fields": {"dish": "Dinner platter"}}
    ]

    context = {
    'dishes': dishes_ser,
    'check': check,
    }

    return render(request, "menu.html",context)

HTML

{% extends "layout.html" %}

{% block title %}
    Menu
{% endblock %}

{% block content %}
    <h1>Menu</h1>
    <a href="/">Home</a>

    Raw output of the check variable as received from Django:
    <br />
    <br />
        {{check}}
    <br/>
    <br/>

    <ul>
        {% for data in check  %}
            <li>{{ data.fields.dish }}</li>
        {% empty %}
            <li>No Dishes</li>
        {% endfor %}
    </ul>
    <br/>

    Raw output of the dishes variable as received from Django::
    <br />
    <br />
        {{dishes}}
    <br/>
    <br/>
    <ul>
        {% for data in dishes  %}
            <li>{{ data.fields.dish }}</li>
        {% empty %}
            <li>No Dishes</li>
        {% endfor %}
    </ul>
{%endblock%}

Result

Screenshot from HTML page Screenshot from HTML page

Upvotes: 0

Views: 541

Answers (1)

ruddra
ruddra

Reputation: 51978

This is because when you serialize using serializer.serialize, it returns a string. You need to convert it to a json object like this:

import json
json_data = json.loads(dishes_ser)
# then pass this as context
context = {
    'dishes': json_data,
    'check': check,
}

But, why would you need to do that when you can directly send the queryset to template and use it like this:

// context
context = {
    'dishes': Dish.objects.all(),
    'check': check,
}
// template
{% for data in dishes  %}
        <li>{{ data.dish }}</li>
{% empty %}
        <li>No Dishes</li>
{% endfor %}

Upvotes: 1

Related Questions