Can't Fix the No Reverse Error in Ajax

301 views
Skip to first unread message

Ahmed Khairy

unread,
May 19, 2020, 1:54:14 PM5/19/20
to Django users

I am trying to use Ajax to submit a like button, I believe everything is in order but I keep getting django.urls.exceptions.NoReverseMatch: Reverse for 'like_post' with arguments '('',)' not found. 1 pattern(s) tried: ['score/like/(?P<pk>[0-9]+)$']


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


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(requestpk):
    # 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 updated

urlpatterns = [

    path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
    path('', PostListView.as_view(), name='score'),
    path('who_we_Are/', who_we_are, name='who_we_are'),
    path('<int:pk>/', PostDetailView.as_view(), name='post-detail'),
    path('like/<int:pk>', LikeView, name='like_post'),
    path('new/', PostCreateView.as_view(), name='post-create'),
    path('<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
    path('<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete')
]

here is the template

                        <form class="mt-0" action="{% url 'score:like_post' post.pk %}" 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 "score:like_post" post.pk %}',
                    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(rse){
                        console.log(rs.responseText);                   
                    },
                });
            });
        });
    </script>


Hella Nick

unread,
May 19, 2020, 11:11:12 PM5/19/20
to django...@googlegroups.com
button标签中的type属性设置为button,

Ahmed Khairy <ahmed.he...@gmail.com> 于2020年5月20日周三 上午1:54写道:
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5aaa1274-dd6b-42bc-8a5e-bce4596ace98%40googlegroups.com.

Hella Nick

unread,
May 19, 2020, 11:13:38 PM5/19/20
to django...@googlegroups.com
Django中的表单提交按钮不要使用submit属性,否则会触发get请求,或者发生错误。

Hella Nick <perso...@gmail.com> 于2020年5月20日周三 上午11:09写道:

Ahmed Khairy

unread,
May 20, 2020, 12:17:46 AM5/20/20
to Django users
Do you mean that this line should be changed?

                                <button id='like' type='submit' name='post_id' class"btn btn-danger btn-sm" value="{{post.id}}"> No ! Don't Print it </button>                            
button标签中的type属性设置为button,

To unsubscribe from this group and stop receiving emails from it, send an email to django...@googlegroups.com.

Motaz Hejaze

unread,
May 20, 2020, 2:07:20 AM5/20/20
to Django users
Change your ajax method from "post" to "get" , you are not submitting any data to use post .

Also change the method in your form too , and share the error message please.

To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/6aa0bb16-9ded-4ad6-8ffa-5d82713ec7ad%40googlegroups.com.

Hella Nick

unread,
May 20, 2020, 7:26:30 AM5/20/20
to django...@googlegroups.com
是的,正确的写法为   <button id='like' type='button' name='post_id' class= "btn btn-primary btn-sm" value="{{post.id}}"> Like </button>

Motaz Hejaze <trapp...@gmail.com> 于2020年5月20日周三 下午2:06写道:
Reply all
Reply to author
Forward
0 new messages