簡體   English   中英

限制每個用戶的投票 django

[英]Limiting voting per user django

我有這段代碼可以讓你為一篇文章投票,現在用戶可以無限次投票,我想這樣做,所以當人們第一次點擊按鈕時,它的值會減一,然后減一,依此類推。

這是文章。html:

<button id="vote">vote</button>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script>
        $("#vote").click(function (e) {
          e.preventDefault()
          var upvotes = $("#total_votes").html()
          var updatedUpVotes = parseInt(upvotes) + 1
          $("#total_votes").html(updatedUpVotes)
          $.ajax({
            url: 'vote/',
            method: "GET",
            data: {},
            success: function (data) {
              console.log(data)
            },
            error: function (error) {
              console.log(error)
            }
          })
        })
      </script>

在views.py中投票function:

def vote(request, article_id):
    article = get_object_or_404(Article, pk=article_id)
    article.votes += 1
    article.save()
    return JsonResponse(data = {"vote": "Voted! Thank you for the vote."})

您需要有一個單獨的 model 來存儲用戶附帶的投票信息。 否則,您將不知道是誰投了那篇文章。 你可以嘗試這樣的事情:

# Model

class Vote(models.Model):
    user = models.ForeignKey(User,on_delete=models.DO_NOTHING)
    article = models.ForeignKey(Article,on_delete=models.DO_NOTHING)

# View

from django.contrib.auth.decorators import login_required

@login_required
def vote(request, article_id):
    article = get_object_or_404(Article, pk=article_id)
    vote, created = Vote.objects.get_or_create(article=article, user=request.user)
    if created:
        return JsonResponse(data = {"vote": "Voted! Thank you for the vote."})
    return JsonResponse(data = {"vote": "You already voted for this article."})

僅供參考:即使GET請求可以工作,但我建議使用POST方法,因為根據MDN

使用 GET 的請求應該只檢索數據。

但顯然這種方法會在數據庫中改變。

創建一個單獨的 model 將包含文章 ID 和用戶 ID。 單擊“贊”按鈕時,檢查該用戶和文章是否存在數據。 如果存在,則將投票減 1,否則增加其值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM