首页 > 解决方案 > 如何修复 Ajax 中没有反向匹配错误

问题描述

我正在尝试使用 Ajax 提交一个赞按钮而不刷新页面,我之前遇到了几个错误,但现在我收到了这个错误:

django.urls.exceptions.NoReverseMatch: Reverse for 'like_post' with arguments '('',)' not found. 1 pattern(s) tried: ['score/like/(?P<pk>[0-9]+)$']

我不确定是什么原因。需要帮助来识别错误。

这是视图:

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})

这是url.py更新的:

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')
]

这是模板:

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

这是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 %}',  <---- Error in this line
                    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>

标签: djangoajaxdjango-url-reverse

解决方案


您需要将 post 对象作为上下文发送。

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

    def get_context_data(self, *args, **kwargs):
        context = super(PostDetailView, self).get_context_data()

        post = get_object_or_404(Post, id=self.kwargs['pk'])
        content["post"] = post

        total_likes = post.total_likes()
        liked = False
        if post.likes.filter(id=self.request.user.id).exists():
            liked = True
        context["total_likes"] = total_likes
        context["liked"] = liked
        return context

推荐阅读