Render JSON data received from an API in an HTML/Django Table

Asked

Viewed 658 times

0

Friends, I need your help!

I am new to Python/Django and I am doing this project with the knowledge that I acquire in day-to-day studying.

I have a function in my views.py that communicates with an API and brings a result in Json. The result is basically this:

[
{
    "_id": "5d6f28ec02523e0012a4eae6",
    "repasse": false,
    "renderSatisfacao": false,
    "botTimeOut": false,
    "ignore": false,
    "sair": false,
    "erroslog": [],
    "chaterroslog": [],
    "Historico": [],
    "userID": "5b43b8a48b769470363b58909a9049",
    "usuario_key": "ABCD",
    "usuario_nome": "Igor Miranda",
    "Created_at": "2019-09-04T03:01:00.716Z",
    "__v": 0
},
{
    "_id": "5d6f291d55d3f500402d338e",
    "repasse": false,
    "renderSatisfacao": false,
    "botTimeOut": false,
    "ignore": false,
    "sair": false,
    "erroslog": [],
    "chaterroslog": [],
    "Historico": [],
    "userID": "577a55a043aab2a6aa78586b2520392",
    "usuario_key": "ABCD",
    "usuario_nome": "Igor Miranda",
    "Created_at": "2019-09-04T03:01:49.484Z",
    "__v": 0
},
]

I need to render this result inside a table in an HTML page with Django, where I have the result of the fields "usuario_nome", "usuario_key" and "Historico".

I’ve read several topics here at Stackoverflow, but I still can’t resolve my need.

Follow my views.py files, Consumirapi.html and the result on the page.

py views.

def ConsumirApi(request):
    url = 'http://urlapi.test.com.br'
    body = {"start" : "2019-09-04 19:30:00", "end" : "2019-09-04 23:59:59"}
    response = requests.post(url, auth=HTTPBasicAuth('123456', 'password1234'), 
    headers={'Content-Type': 'application/json'}, json=body)
    resultado = json.loads(response.content)

    resultado_saida = [{k:v for k,v in x.items() if k in ["Historico", "usuario_nome", "usuario_key"]} for x in resultado]
    drop_falsey = lambda path, key, value: bool(value)
    clean = remap(resultado_saida, visit=drop_falsey)
    resultadofinal = json.dumps(clean, indent=4, sort_keys=True)

    return TemplateResponse(request, 'ConsumirApi.html', { "resultadofinal": resultadofinal })

Consumirapi.html

<table id="test_table" class="display table table-striped table-bordered" border="1" cellspacing="0" width="100%">
    <thead>
      <tr>
        <th>usuario_nome</th>
        <th>usuario_key</th>
        <th>Historico</th>
      </tr>
    </thead>     
</table>
<script type="text/javascript">
$(document).ready(function() {

    var json={{ response.content | safe }}

    $('#test_table').DataTable({
        resultadofinal : json.resultadofinal ,   //get the array of object data
        "columns":[
        {"resultadofinal ": "usuario_key"},
        {"resultadofinal ": "usuario_nome"},
        {"resultadofinal ": "Historico"}]
        });
    });  
</script>

Result obtained so far: Resultado obtido até o momento: Could someone help me identify where I’m going wrong or if something’s missing? I read on some topics that some people use functions within the models.py file, but I don’t have anything inside that file, it’s really necessary to have something in it?

1 answer

0

Come on, from what I saw you just want to check results, then the request would be a GET and not a POST as you put:

response = requests.post(url, auth=HTTPBasicAuth('123456', 'password1234'), 

Another thing, if you just show the data in a table you can do this using Django’s own template, without needing a JS script. Follow an example I made:

Return example of my JSON:

[
    {
        "id": 265,
        "nome": "ARM Vergalhão 10,0 (3/8) SOB MEDIDA",
        "estoque_min": 0,
        "estoque": 0
    },
    {
        "id": 262,
        "nome": "ARM Vergalhão 10,0 (3/8) SOB MEDIDA C/ AMARR",
        "estoque_min": 0,
        "estoque": 0
    },
    {
        "id": 224,
        "nome": "ARM Vergalhão 12,5 (1/2)",
        "estoque_min": 0,
        "estoque": 0
    }
]

Views:

def json_teste(request):
    url = 'SUA_URL_API_AQUI'
    headers={'Content-Type': 'application/json'}
    response = requests.get(url, headers=headers)
    response = json.loads(response.content)

    resultado = response

    context = {}
    context['resultado'] = resultado

return render(request, 'api.html', context)

api.html

<table id="test_table" class="display table table-striped table-bordered" border="1" cellspacing="0" width="100%">
<thead>
    <tr>
        <th>ID</th>
        <th>Item</th>
        <th>Estoque Min</th>
        <th>Estoque</th>
    </tr>
</thead>
<tbody>
        {% for r in resultado %}
        <tr>
            <td>{{ r.id }}</td>
            <td>{{ r.nome }}</td>
            <td>{{ r.estoque_min }}</td>
            <td>{{ r.estoque }}</td>
        </tr>
        {% endfor %}
</tbody>
        <tfoot>
        <tr>
            <th>ID</th>
            <th>Item</th>
            <th>Estoque Min</th>
            <th>Estoque</th>
        </tr>
        </tfoot>
</table>

Upshot:

Resultado final

Browser other questions tagged

You are not signed in. Login or sign up in order to post.