简体   繁体   中英

CS50 Web - Project 4 Network

I am currently working on the CS50 Web Project 4 - Network. The task is to design a twitter-like Network. Currently, I am stuck at the Like-Function.

I have a like-button and a counter of the likes. When I click the like-button, the counter on the page says "undefined". But when I reload the page, everything is fine and the like-count shows the right number of likes and also the like button has changed to an unlike button. Does anyone have an idea what the issues? I am stuck for days now and cannot figure it out. Any help is much appreciated.

Here is my code:

views.py

@csrf_exempt
def like(request, post_id):
    post = Post.objects.get(id=post_id)

    if request.method == "GET":
        return HttpResponseRedirect(reverse("index"))

    if request.method == "PUT":
        data = json.loads(request.body)
        if data.get("like"):
            Likes.objects.create(user=request.user, post=post)
            post.likes = Likes.objects.filter(post=post).count()
        else:
            Likes.objects.filter(user=request.user, post=post).delete()
            post.likes = Likes.objects.filter(post=post).count()
        post.save()
        return HttpResponse("done")

java.js

function like(id) {
    fetch(`/like/${id}`, {
        method: 'PUT',
        body: JSON.stringify({
            like: true
        })
    })
    .then(post => {
        document.querySelector(`#like_count${id}`).innerHTML = post.likes;
    });
}

function unlike(id) {
    fetch(`/like/${id}`, {
        method: 'PUT',
        body: JSON.stringify({
            like: false
        })
    })
    .then(post => {
        document.querySelector(`#like_count${id}`).innerHTML = post.likes;
    });
}

and on my html:

<div id="like_count{{post.id}}">Likes: {{ post.likes }}</div>

{% if liked %}
<button class="btn btn-outline-danger" id="unlike_button{{post.id}}" onclick="unlike('{{ post.id }}')">Unlike</button>

{% else %}
<button class="btn btn-outline-primary" id="like_button{{post.id}}" onclick="like('{{ post.id }}')">Like</button>

{% endif %}
  1. Your view only ever returns "done" , not an object that would have a likes attribute.
    You may want something like return JSONResponse({"likes": post.likes}) instead.
  2. The value fetch() returns is a Response. (You're trying to access likes on it.) You'll need to await on res.json() to decode a JSON response into an object. (While at it, we can remove a bit of repetition in the code.)
function likeOrUnlike(id, like) {
  fetch(`/like/${id}`, {
    method: "PUT",
    body: JSON.stringify({ like: !!like }),
  })
    .then((resp) => resp.json())
    .then((post) => {
      document.querySelector(`#like_count${id}`).innerHTML = post.likes;
    });
}

function like(id) {
  likeOrUnlike(id, true);
}

function unlike(id) {
  likeOrUnlike(id, false);
}

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