jax to submit a like button leading to LikeView() missing 1 required positional argument: 'pk'

Submitted 2 years ago
Ticket #2
Views 202
Language Python
Priority Low
Status Closed

I am trying to add a like button using Ajax and & Jquery in Like Button but  I keep getting the below error:

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

Here is the view.py:

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 to 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>

Submitted on May 19, 20
add a comment

2 Answers

Can you try removing the "submit" type from button?. Seems like you have ajax call but it has POST method on the FORM

Submitted 2 years ago

also what is your URL?. can you show that?

- arun 2 years ago

seems like issue in your url pattern .

- arun 2 years ago

My url pattern in the main project

path('like/', views.LikeView, name='like_post'),
- ahmed.hisham87 2 years ago

why var declation in $ in ajax call. You can simply assign like this "var pk= this_.attr("href");" .. try changing this and let us know .

- arun 2 years ago

could you please show me where exactly to change it by copying it in the ajax code

- ahmed.hisham87 2 years ago

change this line "$var pk= $(this).attr('value');" to "var pk= $(this).attr('value');"

- arun 2 years ago

nothing is happening no action is taking place

- ahmed.hisham87 2 years ago

Actually there is an action taking place but i have to refresh manually to change from like to unlike and the other way around

- ahmed.hisham87 2 years ago

are you getting "missing pk error" now? . If not we are in right direction

- arun 2 years ago

yes we are in the right direction no errors now

- ahmed.hisham87 2 years ago

can you console the response and check the output in success, "success:function(response){ console.log(response); }|

- arun 2 years ago

how do i do this ? console the response and check the output in success, "success:function(response){ console.log(response); }|

- ahmed.hisham87 2 years ago

when you click "like" button whats happening?

- arun 2 years ago

nothing happens I have to refresh to see the change from like to unlike

- ahmed.hisham87 2 years ago

where is this $('#like-section').html(response['form']) button?.. i dont see like-section id in your form

- arun 2 years ago

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

context = {
    # 'total_likes': total_likes,
    'liked': liked,
    'post': post
}

if request.is_ajax:
    html = render_to_string('like_section.html', context, request=request)
    return JsonResponse({'form': html})
- ahmed.hisham87 2 years ago

i think the ajax now is working fine the problem now is with the count if i added it in the context the button is not working if it is removed it works perfectly and the like is added and removed in the admin

- ahmed.hisham87 2 years ago

i hope you are referring LikeView. If yes, total_like is a variable is assigned to that, are you getting the total_like count in your ajax success output?

- arun 2 years ago


Verified

yes thank you so much it is working now

Submitted 2 years ago

yes the only thing im not getting the count in the ajax

- ahmed.hisham87 2 years ago

Awesome !!!. You can console the log & check the count value whether its passing or not.

- arun 2 years ago

the count value is passing but i removed it from the function because it is causing the error and I dont know how to return it back : i have commented it in the following code to help me with it

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

context = {
    # 'total_likes': total_likes,
    'liked': liked,
    'post': post
}

if request.is_ajax:
    html = render_to_string('like_section.html', context, request=request)
    return JsonResponse({'form': html})
- ahmed.hisham87 2 years ago

cool !!. feel free to contact us whenever you need any support from us.

- arun 2 years ago


Wanna Post Ad?
Reach a large group of audience by posting an ad about your business here. For more details
Drop us a Message