首页 > 解决方案 > Django 错误:NoReverseMatch at / Reverse for 'like-post' 未找到

问题描述

我正在用 Django 开发一个简单的博客。我尝试将 ajax 功能添加到我的喜欢按钮。但是得到了这个错误:

未找到参数“(”,)”的“like-post”反向。尝试了 1 种模式:['like/(?P[0-9]+)$']

PS:我按照这个视频创建了一个喜欢按钮,这个视频添加了 ajax 功能

视图.py

class PostDetailView(FormMixin, DetailView):
    model = Post
    form_class = CommentForm

    def get_success_url(self):
        return reverse('post-detail', kwargs={'pk': self.object.id})

    def get_context_data(self, **kwargs):
        context = super(PostDetailView, self).get_context_data(**kwargs)
        postid = get_object_or_404(Post, id=self.kwargs['pk'])
        total_likes = postid.total_likes()
        context['form'] = CommentForm(initial={'post': self.object})
        context['total_likes'] = total_likes
        return context

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        form = self.get_form()
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

    def form_valid(self, form):
        form.save()
        return super(PostDetailView, self).form_valid(form)



def LikeView(request, pk):
    post = Post.objects.get(id=pk)
    #post = get_object_or_404(Post, id=request.POST.get('post-id'))
    post.likes.add(request.user)
    context = {
        'post': post,
        'total_likes': post.total_likes,
    }
    if request.is_ajax():
        html = render_to_string('blogsite/like_section.html', context, request=request)
        return JsonResponse({'form': html})
    return HttpResponseRedirect(reverse('blogsite-home'))

网址.py

urlpatterns = [
path('', PostListView.as_view(), name='blogsite-home'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/new/', PostCreateView.as_view(), name='post-create'),
path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('like/<int:pk>', LikeView, name='like-post'),
]

base.html

<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" 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(rs, e){
        console.log(rs.responseText);
      }
    });
  });
}); 
</script>

like_section.html

<h5><form method="POST" action="{% url 'like-post' post.id %}">
{% csrf_token %}
<button type="submit" id="like" class="btn btn-link btn-sm" name="post-id" value="{{ post.id }}"><a href="#"><strong><i class="fa fa-thumbs-up"></i> {{ post.total_likes }}</strong></a></button><h6 align ="right" class="d-inline-block">
  <a href="http://www.facebook.com/sharer/sharer.php?u=http://your-domain{{ request.get_full_path|urlencode }}"><i class="fa fa-facebook-f"></i></a>   <a href="http://www.linkedin.com/shareArticle?url=http://your-domain{{ request.get_full_path|urlencode }}&title=<your title>&summary=<your desc>&source=http://your-domain"><i class="fa fa-linkedin"></i></a>           
</h6></form>   

like_section.html 然后包含在我的 post_detail.html 中

<div id="like-section">
    {% include 'blogsite/like_section.html' %}
  </div> 

我似乎无法找到解决这个问题的方法。

标签: djangoajax

解决方案


如果在您尝试加载帖子详细信息视图时出现错误。您post缺少. get_context_data_ PostDetailView当您尝试访问post.pk. {% url "like-post" post.pk %}当 Django 在上下文中找不到变量时,模板系统会插入引擎的string_if_invalid配置选项的值,默认为 ''(空字符串)。因此,url 标签会尝试查找like/<string:pk>urls.py 中未定义的 url,从而输出错误。所以,实际上你要做的就是添加postcontextin get_context_data


推荐阅读