0

I am working on the cs50 web project network. When the like button is clicked the text in the button should then change to say unlike and the like count should increase by one without reloading the page. The database information is updated, but the page itself reloads to a white background and the only thing on the page is my json data "{"likeButton": "Unlike", "total_likes": 0}", instead of the page itself. Any help would be appreciated.

Here is a screenshot of the result I am getting webpage screenshot

views.py

@login_required
def likes(request, post_id):
    try:
        current_user = request.user
        post = Post.objects.get(id = post_id)
        likeCount = Post.objects.get(id = post.id)
        total_likes = likeCount.like_count
        likeButton = request.POST.get('buttonForLikes')
        if likeButton == 'Like':
            total_likes = total_likes + 1
            post.like_count = total_likes
            post.save()
            post.like.add(current_user)        
            post.save()
        else:
            total_likes = total_likes - 1
            post.like_count = total_likes
            post.like.remove(current_user)
            post.save()
        return JsonResponse ({'likeButton': likeButton, 'total_likes': total_likes,}, status=200,)
    except KeyError:
        return HttpResponseBadRequest("Like Error")

urls.py

from django.urls import path

from . import views

app_name = "network"

urlpatterns = [
    path("", views.index, name="index"),
    path("login", views.login_view, name="login"),
    path("logout", views.logout_view, name="logout"),
    path("register", views.register, name="register"),
    path("new-post", views.new_post, name="new-post"),
    path("profile/<str:username>", views.profile, name="profile"),
    path("follows/<str:username>", views.follows, name="follows"),
    path("following", views.following, name="following"),
    path("edit", views.edit, name="edit"),
    path("likes/<int:post_id>", views.likes, name='likes')
]

HTML

{% extends "network/layout.html" %}
{% load static %}

{% block body %}
{% if user.is_authenticated %}
    <div class="borderDiv">
    <div class="newPostCard">
        <form id = "new_post_form" name="newPost" action = "{% url 'network:new-post' %}" method ="POST">
            {% csrf_token %}
            <label id="test"><h2>New Post</h2></label><br>
            <textarea id="newPostBox" name="newPost"></textarea></textarea><br><br>            
            <input type ="submit" id = "new_post_submit" class = "btn btn-primary">
        </form>
        
    </div>
    </div>
{% endif %}
<div class="newPostCard">
    {% for item in all_post %}
    <div class="borderDiv">
        <div class="newPostCard">
            <a href="{% url 'network:profile' item.user %}" value="{{ item.user }}"><h2>{{ item.user }}</h2></a>
                <p id="user_post">{{ item.post }}</p>
            </div>
            
            <form id = "like_form" method ="POST" action = "{% url 'network:likes' item.id %}" >
                
            {% if request.user in item.like.all %}
            
            <div> <button claas="likes" id = 'likeButton' data-id= '{{ item.id }}'  value="Unlike" name="buttonForLikes">
                Unike</button>: <span id="numOfLikes">{{ item.like_count }}</span>
                {% csrf_token %}
            </div>
            {% else %}
            <div> <button class="likes" id = 'likeButton' data-id= '{{ item.id }}' value="Like" name="buttonForLikes">
                Like</button>: <span id="numOfLikes">{{ item.like_count }}</span>
                {% csrf_token %}
            </div>
            {%  endif %}
            </form>
            <div>
                {% if user.is_authenticated and request.user == item.user %}
                <button class ="btn btn-primary" id="edit">Edit</button>
                {% endif %}
                <textarea id="editText" name="editBox" style="display: none;"></textarea>
                <button class="btn btn-primary" id="editSaveButton" style="display: none;">Save</button>
            </div>
            <p><i>{{ item.timestamp }}</i></p>            
        </div>
        </div>
    {% endfor %}
    <div id="page_num">
        <span class="page_numbers">
        {% if all_post.has_previous %}
            <a href="?page=1">&laquo; first</a>
            <a href="?page={{ all_post.previous_page_number }}">previous</a>
        {% endif %}
    
        <span class="current_page">
            Page {{ all_post.number }} of {{ all_post.paginator.num_pages }}.
        </span>
            {% if all_post.has_next %}
                <a href="?page={{ all_post.next_page_number }}">next</a>
                <a href="?page={{ all_post.paginator.Num_pages }}">last &raquo;</a>
            {% endif %}
        </span>          
    </div>
</div>
<script src="{% static 'network/edit.js' %}"></script>
<script src="{% static 'network/likes.js' %}"></script>
{% endblock %}

Javascript

let likes = document.getElementById('likeButton');

    likes.addEventListener("click", (e) =>{
    e.preventDefault();
    e.stopPropagation();
    let likeCount = document.getElementById('numOfLikes');
        
        fetch(`/likes/${likes.dataset.id}`, {
            credentials: "include",
            method: "PUT",
            headers: {
                "Accept": "application/json",
                'Content-Type': 'application/json',
            },
        
            
        })

            .then(response => response.json())
            .then(result => {

            if (result.likeButton === 'Like'){
                likes.innerHTML = "Unlike";
                likeCount.innerHTML = result.total_likes;

            }
            else{
                likes.innerHTML = 'Like';
                likeCount.innerHTML = result.total_likes;
            }

        })

        return false;
    });

0

You must log in to answer this question.

Browse other questions tagged .