【发布时间】:2021-06-16 15:34:44
【问题描述】:
我是 Django 新手。我想为我的博客文章创建点赞图标。这是我的html文件中的一个心形图标,当我单击它时,它会变为红色,然后在后端调用一个函数来更改数据库中的数字并将新数字发送回模板,全部使用Ajax,在点赞后不要刷新页面。我该怎么办,问题出在哪里?
在 html 文件中:
<i class="fas fa-heart"></i>
<b>{{ note.like }}</b>
脚本部分:
<script>
$(document).ready(function() {
$('.fa-heart').click(function(e){
this.style.color = this.style.color == 'red' ? 'white' : 'red';
e.preventDefault();
$.ajax({
type:'POST',
url:"vote/like/",
data:{
num:"niloofar",
//I think the problem is with this csrf token part
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
},
success: function(data){
alert(data);
},
error : function() {
console.log("Error");
}
});
});
});
</script>
在视图中:
def like(request):
if request.method == 'POST':
print(request.POST)
return HttpResponse('done')
在 urls.py 中:
path('<int:id>/vote/like/', views.like, name='like'),
错误是:
内部服务器错误:/notes/1/vote/like/ Traceback(最近调用 最后):文件 “/home/niloofar/git/djangoenv/lib/python3.9/site-packages/django/core/handlers/exception.py”, 第 47 行,在内部 response = get_response(请求)文件“/home/niloofar/git/djangoenv/lib/python3.9/site-packages/django/core/handlers/base.py”, 第 181 行,在 _get_response 中 response = Wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: like() got an unexpected keyword argument 'id'
【问题讨论】:
-
您是否在您的
urls.py中设置了vote/like/端点? -
@stackdon 是的。我已经更新了问题。
标签: javascript django ajax csrf-token