Django: 无刷新推送按钮的最佳方法是什么?

-1 投票
1 回答
1372 浏览
提问于 2025-04-29 05:24

我正在使用djangoratingsapp来创建一个“点赞”和“点踩”的按钮系统,整体运行得还不错。不过,我在模板中使用的是一种非常简单的按钮布局,并且用标准的POST协议来记录按钮的点击和评分。我的主要问题是,每个页面上都有很多评论,用户可以为这些评论点击点赞按钮,而我现在的写法是每次点击按钮后都会重新加载页面,这样用户就会被带回到页面顶部,这对用户来说非常烦人。我在想,有没有更简单的方法可以在Django应用中记录按钮点击,而不需要重新加载整个页面。我查了一下,正在研究comet技术。我想知道有没有更简单的方法,或者有没有人愿意给我一些提示,我会非常感激。这不是一个复杂的网站,我只需要在不重新加载页面的情况下记录按钮点击,其他的功能比如实时聊天或状态更新都不需要。谢谢大家的帮助。

这是我在模板中使用的按钮的简单代码:

<form action="/myapp/r/{{pageid}}/" method="post">
 {% csrf_token %}
 <input type="submit" class="btn" value="+1" name="likebtn"/>
</form>

这是与按钮相关的views.py代码:

if (request.POST.get('likebtn')):
        votenum = instance.likerating.votes #get the number of total votes before casting a vote
        pagelikerating = instance.likerating.add(score=2, user=request.user, ip_address=request.META['REMOTE_ADDR']) #use the djangoratings app to add the rating
        if votenum != instance.likerating.votes: #check to see if the voting went through or got blocked from IP limit. If voting went through, the votenum variable will be 1 integer lower than the new queried total votes
            instance.likeratingcounter += 1 #this is a simple integerfield in the model that serves as a counter for number of likes
            instance.save() #save the addition of +1 on the counter 
暂无标签

1 个回答

0

我得到了答案,多亏了Daniel的进一步解释。谢谢你,Daniel!你可以简单地使用AJAX来实现它们。这里有一个很好的指南,专门讲解如何在Django教程中为按钮使用AJAX: http://www.tangowithdjango.com/book/chapters/ajax.html

撰写回答