A_K
A_K

Reputation: 912

Ajax to submit a like button leading to Page 404 Error

I am trying to use Ajax to submit a like button, I believe everything is in order but I keep getting PAge 404 error after submitting the like button,

I am not sure what is the reason. Need help to identify the error.

I have made some amendments to the URL path moving it from app urls.py to the main project urls.py but the error showing now is

LikeView() missing 1 required positional argument: 'pk'

Here is the view

class PostDetailView(DetailView):
    model = Post
    template_name = "post_detail.html"

    def get_context_data(self, *args, **kwargs):
        context = super(PostDetailView, self).get_context_data()
        stuff = get_object_or_404(Post, id=self.kwargs['pk'])
        total_likes = stuff.total_likes()
        liked = False
        if stuff.likes.filter(id=self.request.user.id).exists():
            liked = True
        context["total_likes"] = total_likes
        context["liked"] = liked
        return context


def LikeView(request, pk):
    # post = get_object_or_404(Post, id=request.POST.get('post_id'))
    post = get_object_or_404(Post, id=request.POST.get('id'))
    like = False
    if post.likes.filter(id=request.user.id).exists():
        post.likes.remove(request.user)
        like = False
    else:
        post.likes.add(request.user)
        like = True
    context["total_likes"] = total_likes
    context["liked"] = liked

    if request.is_ajax:
        html = render_to_string('like_section.html', context, request=request)
        return JsonResponse({'form': html})

Here is the url.py in the main project, I have moved it from the app called Score the main 'url.py'

urlpatterns = [
    path('like/', views.LikeView, name='like_post'),

here is the updated template

                        <form class="mt-0" action="{% url 'like_post' %}" method='POST'>
                            {% csrf_token %}
                            <strong> Likes
                            : {{total_likes}} </strong> 
                            {% if user.is_authenticated %}
                            {% if liked %}
                                <button id='like' type='submit' name='post_id' class= "btn btn-danger btn-sm" value="{{post.id}}"> Unlike </button>                            
                            {% else %}
                                <button id='like' type='submit' name='post_id' class= "btn btn-primary btn-sm" value="{{post.id}}"> Like </button>                            
                            {% endif  %}
                            {% else %}
                            <p><small><a href="{% url 'login' %}"> Login</a> to Like </small></p>
                            {% endif %}                   
                        </form>   

here is the ajax

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(event){
            $(document).on('click','#like', function(event){
                event.preventDefault();
                $var pk= $(this).attr('value');
                $.ajax({
                    type:'POST',
                    url:'{% url "like_post" %}',
                    data:{'id': pk, 'csrfmiddlewaretoken':'{{csrf_token}}'},
                    dataType:'json', 
                    success:function(response){
                        $('#like-section').html(response['form'])
                        console.log($('#like-section').html(response['form']));                    
                    },
                    error:function(rs, e){
                        console.log(rs.responseText);                   
                    },
                });
            });
        });
    </script>

Thank you

Upvotes: 0

Views: 60

Answers (1)

Deniz Kaplan
Deniz Kaplan

Reputation: 1609

As error indicates, ListView class requires a positional argument which is pk. So your view class should change.

def LikeView(request):

Use this code as ListView definition.

Upvotes: 1

Related Questions