I'm trying to get the post data from the backend using fetch. However i am getting a 500 server error when trying to fetch the data. I have tried using .serialize() in the backend to pass the data. as well as trying to return the jsonResponse by serializing the query object which would give me this error: Object of type User is not JSON serializable. I tried it by sending an object and without an object. Any suggestions?
code models.py
class Post(models.Model):
user = models.ForeignKey(User,on_delete=models.PROTECT, default='',null=True)
message = models.TextField()
date = models.DateTimeField()
likes = models.ManyToManyField(User,blank=True,null=True,related_name="posts")
def serialize(self):
return {
"id": self.id,
"user": self.user,
"likes": [user for user in self.likes.all()],
"message": self.message,
"date": self.date.strftime("%b %d %Y")
}
code urls.py
path("post/<int:id>",views.post, name="post")
code views.py
@csrf_exempt
def post(request,id):
post = Post.objects.get(id=id)
if request.method == "GET":
return JsonResponse({"post":post.serialize()})
code script.js (post.getAttribute('name') is the post id)
posts.forEach(post => {
fetch(`post/${post.getAttribute('name')}`)
.then(response => response.json())
.then(data => {
console.log(data)
})
)}
CodePudding user response:
Because you are trying User model instance to convert JSON. Just change "user": self.user to "user": self.user.email
or whatever you want
def serialize(self):
return {
"id": self.id,
"user": self.user.email,
"likes": [user.id for user in self.likes.all()],
"message": self.message,
"date": self.date.strftime("%b %d %Y")
}