2 years ago

#73339

test-img

rakin235

How do I get rid of error 403 while fetching an API using javascript in my Django application?

I am very new to javascript. I was working on a project, that I have to make a social-networking site using Django. There I have a like feature that will asynchronously update the like button to an unlike button and the number of liked users will also be updated without reloading the page. That is, I have to update the like button and number of likes using javascript fetch. I have trouble fetching that API, where I get error 403.enter image description here

I got the marked error while clicking on my like button. Here I am sharing my js code.

document.addEventListener("DOMContentLoaded",function(){
    document.querySelector('#like').addEventListener('click', ()=> like_function('like'));
})

// let posts_id = "{{ posts.id }}";

let is_like = "{{is_like}}";
let num_like = "{{num_like}}";

function like_function(like){
    fetch(`/index/${posts_id}`,{
        method:"POST",
        body : JSON.stringify({
            "is_like" : is_like,
            "num_like" : num_like,
        })
    })
    .then(response => response.json())
    .then(result => {
        if(result.is_like){
            document.querySelector('#like').innerHTML = "Unike";
        }
        else{
            document.querySelector('#like').innerHTML = "Like";
        }
    })
}

Also, I can't figure out why I am getting "Unexpected token < in JSON at position 1". My Django views method generates JSON data. Here is the views function.

@login_required
def likepost(request,posts_id):
    posts = NewPost.objects.get(id = posts_id)
    is_like = False
    for like in posts.likepost.all():
        if like == request.user and request.method == "POST":
            is_like = True
            break
    
    if not is_like:
        posts.likepost.add(request.user)
    
    else:
        posts.likepost.remove(request.user)

    # serialize_obj = serializers.serialize("json",posts_id)
    
    return JsonResponse({
        "is_like" : is_like,
        "num_like" : posts.likepost.count()
    },safe=False)

Here I am sharing my like button in the Django template (HTML file):

<form action="{% url 'likepost' posts_id=posts.id %}" id="likeform" method="POST" style="display: inline;">
        {% csrf_token %}
        <button id = "like" class="btn btn-link">Like</button>
    </form>

    <small id="num_of_likes">{{ posts.likepost.all.count }}</small>
    {% block script %} 
        <script>
            let posts_id = "{{ posts.id }}";
        </script>
        <script src="{% static 'network/controller.js' %}"></script>
    {% endblock %}

And also I'm sharing my urls.py file here if you need it.

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("profile/<int:id>",views.profilepage,name="profile"),
    path("profile/<int:id>/following/addfollower",views.followersPeople,name="addfollower"),
    path("profile/<int:id>/following/removefollower",views.followersRemove,name="removefollower"),
    path("postform", views.createpost, name="postform"),
    path("editform/<int:id>",views.editpost,name="editpost"),
    path("following",views.followerspost,name="following"),
    path("index/<int:posts_id>",views.likepost, name="likepost"),
    path("postpage/<int:id>",views.view_post,name="postpage"),
]+ static(settings.MEDIA_URL, document_root= settings.MEDIA_ROOT)

I can't understand where I've made the mistake or which one I've skipped. Here is what I am actually happening in my project. https://youtu.be/lPGX9RhcSpU I want my javascript function will take the JSON data generated by Django views likepost method and will take me back to my homepage by updating the number of likes and the like button to an unlike-button asynchronously without reloading the homepage.

So, what should I do now?

javascript

api

django-views

django-templates

django-urls

0 Answers

Your Answer

Accepted video resources