1

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 !

1
  • Why do you need to serialize the posts and then deserialize them? Commented Feb 15, 2021 at 18:01

2 Answers 2

1

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) 
Sign up to request clarification or add additional context in comments.

4 Comments

Hello @Mellet Your suggestion with the following Javascript still returns the JSON Parse error. function load_allposts() { fetch(/test/${allposts}) .then(response => response.json()) .then(allposts_list => { console.log(allposts_list); } I did update allposts_list = list(users) to => list(allposts_ever) as well since "users" was not undefined.
Note that I have I remove then(response => response.json()), the parsing error disappear and i do manage to get the "HTML Response" to log in the console, but this response is not the list that I am sending from the backend.
You try using Postman/Insomnia or some other client to do the request and check if the response looks correct. Check that the response is a json list and that it has the correct headers. Then once it is working there you can move to the JS part. Helps you isolate the problem.
Adding .values() in allposts_ever.order_by("-timestamp").all().values() did the trick ..! After listing it, it does return a json looking list which can then be handled in the front end.
0

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); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.