gpt4 book ai didi

jquery - 如何将用户 ID 传递到 django ajax post 中?

转载 作者:行者123 更新时间:2023-12-01 03:40:32 25 4
gpt4 key购买 nike

我正在尝试ajaxify一个类似按钮,无需ajax即可正常工作。所以我定义了一个静态文件:

$(function(){

$('#like').click(function(){
$.ajax({
type: "POST",
url: "/news/like/",
data: {
'post_id': $(this).attr('name'),
'user': '{{request.user.id}}',
'csrfmiddlewaretoken': '{{csrf_token}}'
},
dataType: "json",
success: function(response) {
alert('You liked this')
},
error: function(rs, e) {
alert(rs.responseText);
}
});
})

});

并修改相应的 View 如下:

 @csrf_exempt
def like(request):
args = {}
if request.method == 'POST':
#lu = User.objects.get(id= request.user.id)
puid = int(request.POST.get('puid', None))
lu= User.objects.get(id= puid)
post_id = request.POST.get('post_id', None)
try:
liked_news = News.objects.get(id = post_id)
except:
liked_news = None

if NewsLike.objects.filter(liker=lu.id, news=post_id):

liked_news.likes -=1
liked_news.save()
NewsLike.objects.filter(news=post_id, liker=lu.id).delete()
return HttpResponse(simplejson.dumps(args),
mimetype='application/javascript')
#return HttpResponseRedirect(reverse("news.views.post_withslug", args=[liked_news.slug]))

else:

liked_news.likes +=1
liked_news.save()
messages.success(request, "You liked this news")
newliker = NewsLike(liker=lu.id, news=post_id)
newliker.save()


args.update(csrf(request))
#return HttpResponseRedirect(reverse("news.views.post_withslug", args=[liked_news.slug]))
return HttpResponse(simplejson.dumps(args),
mimetype='application/javascript')

临时添加“@csrf_exempt”装饰器以消除 csrf 错误。

但是,当我单击来自 Firefox 的按钮时

ValueError at /news/like/
invalid literal for int() with base 10: '{{request.user.id}}'

我应该如何解决这个问题?

最佳答案

无论如何,都不需要从 Javascript 传递当前用户。 View 已经知道该信息,因为它在请求中。因此,您应该将 View 代码中的 lu 替换为 request.user

关于jquery - 如何将用户 ID 传递到 django ajax post 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21638713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com