Getting a ValueError. My view is not returning a HttpResponse. Returns None instead
Also getting: File “C:\Users\hp\Documents\djangosocial\newproject\core\views.py”, line 312, in likeView
id = data[“id”]
KeyError: ‘id’ in my terminal.
My goal is to like each post on a user’s timeline without page refreshing
The {{posts}} variable is from the key value in my index view i.e: context = {“posts”:posts}
Please post your view here.
Side note: Don’t post images of code, copy/paste the code itself into the body of your message.
When posting code here, enclose the code between lines of three backtick - ` characters. That means you will have a line of ```, then your code, then another line of ```. (When posting code from multiple files, it’s generally most useful to do this for each file individually.) This forces the forum software to keep your code properly formatted. This is also the recommended process when posting templates, error messages, and other pre-formatted text.
Alright. Really appreciate your response. Here is the view handling the like/unlike functionality:
def likeView(request):
if request.method == "POST":
username = request.user.username
data = json.loads(request.body)
id = data["id"]
post=Post.objects.get(id=id)
liked_post = LikePost.objects.filter(post_id=id, username=username).first()
if liked_post == None:
new_like = LikePost.objects.create(post_id=id,username=username)
new_like.save()
post.likes.add(new_like)
checker = 1
post.save()
else:
liked_post.delete()
post.likes.remove(liked_post)
checker = 0
post.save()
context = {'checker':checker}
return JsonResponse(context, safe=False)
You could start with checking the network tab of your browser’s developer tools to verify that what you’re sending is what you think you’re sending.
Then, the easiest way to see what’s going on in the view would be to print data
after the json.loads function call to be able to visually verify that the data has loaded in the format expected.
.