Django – Can't fetch Json data in javascript
Question:
Hello I am pretty new to Django and Javascript I want to build a simple application where users can write posts and see a list of all posts in reverse chronologial order on the index page. (The index page is rendered fine.)
I created some Posts via the admin interface.
Unfortunately I can’t figure out why I am not able to fetch the JsonResponse and no div gets append to my template.
the code looks as following:
first I’ve created a Posts model
class Posts(models.Model):
text = models.TextField(max_length=512)
timestamp = models.DateTimeField(auto_now=True)
def serialize(self):
return {
"id": self.id,
"text": self.text,
"timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"),
}
My view function to get all posts from the datatbase is called via
path("get_posts", views.get_posts, name="get_posts"),
and looks like this:
def get_posts():
# get all posts
posts = Posts.objects.all()
# Return posts in reverse chronologial order
posts = posts.order_by("-timestamp").all()
return JsonResponse([post.serialize() for post in posts], safe=False)
In my Javascript file (index.js) I want to load all Posts, create a div for each post and append them to my template
document.addEventListener('DOMContentLoaded', function() {
// By default, load_posts
load_posts();
});
function load_posts() {
// get posts from /posts API Route
fetch('/get_posts')
.then(response => response.json())
.then(posts => {
// create a div element for each post
posts.forEach(post => {
let div = document.createElement('div');
div.className = "post-item row";
div.innerHTML = `
<span class="col"> <b>${post['text']}</b> </span>
`;
// append div to posts-view
document.querySelector('#posts-view').append(div);
});
});
}
my template index.html
{% load static %}
{% block body %}
<div id="posts-view">
</div>
{% endblock %}
{% block script %}
<script src="{% static 'network/index.js' %}"></script>
{% endblock %}
I imported the required library to my views.py
from django.http import JsonResponse
I imported the Posts model
from .models import Posts
I checked all variable and function names more than twice…
Edit:
When checking the path manually I get a TypeError.
Traceback (most recent call last):
File "D:NetworkvenvLibsite-packagesdjangocorehandlersexception.py", line 56, in inner
response = get_response(request)
File "D:NetworkvenvLibsite-packagesdjangocorehandlersbase.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
Exception Type: TypeError at /get_posts Exception Value: get_posts() takes 0 positional arguments but 1 was given
In the browser console I see two errors.
index.js:10
GET http://127.0.0.1:8000/get_posts 500 (Internal Server Error)
load_posts @ index.js:10
(anonymous) @ index.js:4
and
Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
Promise.then (async)
load_posts @ index.js:12
(anonymous) @ index.js:4
Answers:
Each Django view function takes an HttpRequest
object as its first parameter, which is missing from your view function definiton:
def get_posts(request):
...
The JS fetch()
call try to parse the returned Django error message as a JSON object. You can add error-checking to that.
Hello I am pretty new to Django and Javascript I want to build a simple application where users can write posts and see a list of all posts in reverse chronologial order on the index page. (The index page is rendered fine.)
I created some Posts via the admin interface.
Unfortunately I can’t figure out why I am not able to fetch the JsonResponse and no div gets append to my template.
the code looks as following:
first I’ve created a Posts model
class Posts(models.Model):
text = models.TextField(max_length=512)
timestamp = models.DateTimeField(auto_now=True)
def serialize(self):
return {
"id": self.id,
"text": self.text,
"timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"),
}
My view function to get all posts from the datatbase is called via
path("get_posts", views.get_posts, name="get_posts"),
and looks like this:
def get_posts():
# get all posts
posts = Posts.objects.all()
# Return posts in reverse chronologial order
posts = posts.order_by("-timestamp").all()
return JsonResponse([post.serialize() for post in posts], safe=False)
In my Javascript file (index.js) I want to load all Posts, create a div for each post and append them to my template
document.addEventListener('DOMContentLoaded', function() {
// By default, load_posts
load_posts();
});
function load_posts() {
// get posts from /posts API Route
fetch('/get_posts')
.then(response => response.json())
.then(posts => {
// create a div element for each post
posts.forEach(post => {
let div = document.createElement('div');
div.className = "post-item row";
div.innerHTML = `
<span class="col"> <b>${post['text']}</b> </span>
`;
// append div to posts-view
document.querySelector('#posts-view').append(div);
});
});
}
my template index.html
{% load static %}
{% block body %}
<div id="posts-view">
</div>
{% endblock %}
{% block script %}
<script src="{% static 'network/index.js' %}"></script>
{% endblock %}
I imported the required library to my views.py
from django.http import JsonResponse
I imported the Posts model
from .models import Posts
I checked all variable and function names more than twice…
Edit:
When checking the path manually I get a TypeError.
Traceback (most recent call last):
File "D:NetworkvenvLibsite-packagesdjangocorehandlersexception.py", line 56, in inner
response = get_response(request)
File "D:NetworkvenvLibsite-packagesdjangocorehandlersbase.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
Exception Type: TypeError at /get_posts Exception Value: get_posts() takes 0 positional arguments but 1 was given
In the browser console I see two errors.
index.js:10
GET http://127.0.0.1:8000/get_posts 500 (Internal Server Error)
load_posts @ index.js:10
(anonymous) @ index.js:4
and
Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
Promise.then (async)
load_posts @ index.js:12
(anonymous) @ index.js:4
Each Django view function takes an HttpRequest
object as its first parameter, which is missing from your view function definiton:
def get_posts(request):
...
The JS fetch()
call try to parse the returned Django error message as a JSON object. You can add error-checking to that.