1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Display JavaScript Fetch for JsonResponse 2 Tables on HTML

Discussão em 'Python' iniciado por Stack, Setembro 28, 2024 às 02:32.

  1. Stack

    Stack Membro Participativo

    I'm learning JavaScript right now and I'm trying to display data from 2 tables, which is profile and posts of the user profile.

    Here is the API view API

    I tried to display the data on index.html using JavaScript. index.js

    function load_profile(author_id) {

    // Load posts list
    fetch(`/profile/${author_id}`)
    .then(response => response.json())
    .then(response => {
    // Print profile & posts
    console.log(response.prof);
    console.log(response.posts);

    const content_profile = document.createElement('div');
    content_profile.className = "content_profile";

    const user = document.createElement('p');
    user.innerHTML = `<h3>${response.prof.user}</h3>`;

    const followers = document.createElement('p');
    followers.innerHTML = `Follower: ${response.prof.followers}`;

    const following = document.createElement('p');
    following.innerHTML = `Following: ${response.prof.following}`;

    const a = document.createElement('a');
    a.className = "btn btn-primary";
    a.innerHTML = "Follow";

    content_profile.append(user, followers, following, a);
    document.querySelector('#profile').append(content_profile);

    response.posts.forEach(post =>{
    const list_item = document.createElement('ul');
    const data_author = document.createElement('li');
    data_author.innerHTML = post.author+" at "+post.timestamp+" say:";
    const data_content = document.createElement('li');
    data_content.innerHTML = post.content;
    const data_like = document.createElement('li');
    data_like.innerHTML = post.like+" Likes";

    list_item.append(data_author, data_content, data_like);
    document.querySelector('#postbox').append(list_item);
    })
    })
    }


    index.html

    {% extends "sinpage/layout.html" %}
    {% load static %}

    {% block body %}
    <div class="container">
    <div class="row">
    <div class="col" id="userpage">
    <h2>{{ request.user.username }}</h2>
    <div id="postit">
    <form id="compose-form">
    {{form.as_p}}
    <input type="submit" class="btn btn-primary" value="Post">
    </form>
    </div>
    </div>
    <div class="col" id="profile"></div>
    <div class="col" id="postbox"></div>
    </div>
    </div>
    {% endblock %}

    {% block script %}
    <script src="{% static 'sinpage/index.js' %}"></script>
    {% endblock %}


    So the profile data show up but the posts data didn't. This is my first time displaying 2 data using JavaScript, I think I'm doing it wrong? Any pointer is appreciated. Thanks.

    Continue reading...

Compartilhe esta Página