我正在尝试在我的项目中使用 ajax 创建一个赞按钮。但它给出了错误:找不到“喜欢”的反向。'like' 不是有效的视图函数或模式名称。
这是我的代码。
视图.py
def like(request):
blog = get_object_or_404(Blogs, sno = request.POST.get('blog_id'))
is_liked = False
if blog.likes.filter(username = request.user).exists():
blog.likes.remove(request.user)
is_liked = False
else:
blog.likes.add(request.user)
is_liked = True
context = {
'is_liked' : is_liked,
'blog' : blog,
'total_like': blog.total_like(),
}
if request.is_ajax():
html = render_to_string('like_section.html',context,request=request)
return JsonResponse({'form':html})
网址.py
urlpatterns = [
path('',views.blogs, name='blogs'),
path('blog/<int:id>/<str:slug>',views.showblog, name='showblog'),
path('writeblog/',views.writeblog, name='writeblog'),
path('publish',views.publishBlog, name='publishblog'),
path('like',views.like, name='like'),]
模板
<p> Likes : {{total_likes}} Like{{total_likes| pluralize}} </p>
{% if is_liked %}
<button type="button" class="btn" id="like" name="blog_id" value="{{blog.sno}}"><i class="fa fa-thumbs-up">Dislike
</i></button>
{% else %}
<button type="button" class="btn" id="like" name="blog_id" value="{{blog.sno}}"><i class="fa fa-thumbs-up"> Like
</i></button>
{% endif %}
<script>
$(document).ready(function (event) {
$('#like').click(function(){
var pk = $(this).attr('value');
const path = '{% url "like" %}';
$.ajax({
type: "POST",
url: path,
data : {'id':pk, 'csrfmiddlewaretoken':'{{ csrf_token }}'},
dataType:'json',
success:function(event){
$('#like-section').html(resopnse['form']);
console.log($('#like-section').html(resopnse['form']));
}
});
});
});
</script>