简体   繁体   中英

Manipulating and passing JSON from back to front end in Django

From my DB, I am:

  • Catching all the posts that my users posted.
  • Order them from newest to oldest and...
  • Try to pass the load into JSONResponse so that my Front end Javascript can handle it.

The idea is that for each post, it displays a DIV containing the data.

def allpoststest (request, posttype):

    if posttype == "allposts":
        allposts_ever = Post.objects.all()
        allposts_ever = allposts_ever.order_by("-timestamp").all()
        # Serialize the QuerySet into JSON (This strings it)
        json_data = serializers.serialize("json", allposts_ever)
        # DeString it the data into JSON data (LIST)
        json_data = json.loads(json_data)
        # Try to turn list into numpy.ndarray
        json_data = np.array(json_data)
        # Context it
        context = {'json_data': json_data}
        # Pass the JSON formatted data to the Front End
        return JsonResponse(context, safe=False)

document.addEventListener('DOMContentLoaded', function() {

    document.querySelector('#trigger').addEventListener('click', () => load_allposts('allposts'));


})

function load_allposts(posttype) {

    fetch(`/test/${posttype}`)
        .then(response => response.json())
        .then(response => console.log(response))
        .then(json_data => {
            console.log(json_data);

            json_data.forEach(post => {
    
                const div = document.createElement("div");
    
                div.innerHTML =
                `
                <div class="card" style="width: 100%;">
                <div class="card-body">
                    <h5 class="card-title">Posted by ${ post.user }</h5>
                    <h6 class="card-subtitle mb-2 text-muted">Posted on ${ post.timestamp }</h6>
                    <p class="card-text" style="text-align: center;">${ post.post }</p>
                    <div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups">
                        <div class="btn-group mr-2" role="group" aria-label="First group">
                            <button id="likebtn" class="btn btn-info" type="button">Like</button>
                            <button id="unlikebtn" class="btn btn-info" type="button">Unlike</button>
                            <button id="likecount" class="btn btn-info disabled" type="button">0</button>
                        </div>
                        <div class="btn-group mr-2 btn-group-sm" role="group" aria-label="Second group"> 
                            <button id="editbtn" class="btn btn-secondary mr-2" type="button">Edit</button>
                            <button id="deletebtn" class="btn btn-danger" type="button">Delete</button>
                        </div>
                    </div>
                </div>
                </div>
                `
                document.querySelector('#allposts-view').append(div);
            })   
        })
}
  1. Can you please help in drastically make the python code easier? While it is my understanding that serializing the QuerySet and THEN pass it in the front end to JSONify it somehow should work, it does not.

I do not think that there would be a need to convert the QuerySet > Serialize > Destringfy > change from List to Array.

  1. The Javascript itself seems to load properly since I can trigger my function when clicking on the div "id=trigger", however, with the code above, I obtain:
XHRGEThttp://127.0.0.1:8000/test/allposts
[HTTP/1.1 500 Internal Server Error 34ms]

Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

I am happy to edit fetch( /test/${posttype} ) to fetch( /test ) as this then remove the XHR Error. But I still have the issue with the parsing.

Hope you can help !

Would this maybe work for you?

def allpoststest (request, posttype):
    if posttype == "allposts":
        allposts_ever = Post.objects.all()
        allposts_ever = allposts_ever.order_by("-timestamp").all().values()
        allposts_list = list(allposts_ever)
        return JsonResponse(allposts_list, safe=False)

Need to simply get list(QuerySets.values()) and pass it to the front end like this:

def allpoststest (request, posttype):

    allposts_ever = Post.objects.all()
    allposts_ever = allposts_ever.order_by("-timestamp").all().values()
    allposts_list = list(allposts_ever)
    return JsonResponse(allposts_list, safe=False)

The front end can then handle the "JSON List", parse it (.json()) and handle it:

function load_allposts(posttype) {

    fetch(`/test/${posttype}`)
        .then(response => response.json())
        .then(allposts_list => {
            
        console.log(allposts_list);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM