Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Django错误:NoReverseMatch at/Reverse for';像post';找不到_Django_Ajax - Fatal编程技术网

Django错误:NoReverseMatch at/Reverse for';像post';找不到

Django错误:NoReverseMatch at/Reverse for';像post';找不到,django,ajax,Django,Ajax,我正在用Django开发一个简单的博客。我尝试将ajax功能添加到我的“喜欢”按钮中。但我犯了这个错误: 找不到参数为“(“”,)”的“like post”的反转。1幅(s) 已尝试:[“like/(?P[0-9]+)$”] PS:我随后创建了一个like按钮并添加了ajax功能 views.py class PostDetailView(FormMixin, DetailView): model = Post form_class = CommentForm def

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

找不到参数为“(“”,)”的“like post”的反转。1幅(s) 已尝试:[“like/(?P[0-9]+)$”]

PS:我随后创建了一个like按钮并添加了ajax功能

views.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'))
url.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'),
]
urlpatterns=[
路径(“”,PostListView.as_view(),name='blogsite-home'),
路径('post/',PostDetailView.as_view(),name='post-detail'),
路径('post/new/',PostCreateView.as_view(),name='post-create'),
路径('post//update/',PostUpdateView.as_view(),name='post-update'),
路径('post//delete/',PostDeleteView.as_view(),name='post-delete'),
路径('like/',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>

$(文档).ready(函数(事件){
$(文档).on('click','like',函数(事件){
event.preventDefault();
var pk=$(this.attr('value');
$.ajax({
键入:“POST”,
url:“{%url”类似于post“post.pk%}”,
数据:{'id':pk'csrfmiddlewaretoken':{{{csrf_token}}},
数据类型:“json”,
成功:功能(响应){
$('like section').html(响应['form'])
log($('#like section').html(response['form']);
},
错误:函数(rs,e){
console.log(rs.responseText);
}
});
});
}); 
像_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>   

{%csrf_令牌%}
然后,like_section.html包含在我的post_detail.html中

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

{%include'blogsite/like_section.html%}

我似乎找不到解决此问题的方法。

如果在尝试加载post detail视图时出现“相信”错误。在
PostDetailView
get\u context\u data
中缺少
post
变量。当您试图访问
{%url“like post”post.pk%}
中的
post.pk
时。当Django在上下文中找不到变量时,模板系统将插入引擎配置选项的值,该值默认为“”(空字符串)。结果,url标记尝试查找url,该url与url.py中未定义的类似,因此输出错误。因此,实际上您需要做的是将
post
添加到
get\u context\u data
中的
context