用户投票选择后如何将投票转换为已投票?

时间:2019-03-13 09:33:18

标签: python django

此代码运行良好。我唯一要更改的是在用户对选项进行投票后将提交按钮“投票”更改为“已投票”,而不是显示错误消息“您已经投票”。这样,用户登录时就可以知道自己已经投票了哪些选项下次投票选择

  

urls.py

var jayson = require('jayson');
  

models.py

   path('<slug>/',views.options,name='options'),
   path('<slug>/vote/', views.vote, name='vote'),
  

views.py

 class Category(models.Model):
    name = models.CharField(max_length=250)
    slug = AutoSlugField(populate_from='name')
    details = models.TextField(blank=True)
    image = models.ImageField(blank=True,upload_to='categories')
    views = models.IntegerField(default=0)
    created = models.DateTimeField(auto_now=True)
    modified = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "Categories"


class Option(models.Model):
    name = models.CharField(max_length=250)
    slug = AutoSlugField(populate_from='name')
    image = models.ImageField(blank=True,upload_to='options')
    details = models.TextField()
    category = models.ForeignKey(Category, on_delete=CASCADE)
    votes = models.IntegerField(default=0)
    active = models.BooleanField(default=True)

    def __str__(self):
        return self.name


class Vote(models.Model):
    option = models.ForeignKey(Option, on_delete=CASCADE)
    voter = models.ForeignKey(User, on_delete=CASCADE)
    slug = AutoSlugField(populate_from='option')

    def __str__(self):
        return self.voter
  

options.html

def options(request,slug):
category = Category.objects.get(slug=slug)
category.views += 1
category.save()
options = category.option_set.all().order_by('-votes')
if request.method == "POST":
    if request.user.is_authenticated:
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.category = category
            comment.user = request.user
            comment.save()
            messages.success(request, 'Comment Posted.')
    else:
        messages.error(request, 'You have to login first to give comment')
        return redirect('rank:login')
else:
    form = CommentForm()
return render(request, 'rank/options.html', {'options': options,'form':form,'title': 'options','category':category})

def vote(request,slug):
if request.user.is_authenticated:
    option = Option.objects.get(slug=slug)
    category = option.category

    if Vote.objects.filter(slug=slug,voter_id=request.user.id).exists():
         messages.error(request,'You Already Voted!')
         return redirect('rank:options', category.slug)
    else:
        option.votes += 1
        option.save()
        voter = Vote(voter=request.user,option=option)
        voter.save()
        messages.success(request,'Voted.{} peoples also agree with you.'.format(option.votes-1))
        return redirect('rank:options',category.slug)
else:
    messages.error(request,"You have to login first to vote.")
    return redirect('rank:login')

1 个答案:

答案 0 :(得分:0)

实现此目的最简单的方法可能是向每个选项添加属性,以指示在将选项传递给模板之前,当前登录的用户是否对该选项进行了投票。

例如:

def options(request,slug):
    category = Category.objects.get(slug=slug)
    category.views += 1
    category.save()
    options = category.option_set.all().order_by('-votes')

    # Indicate whether the user has voted or not
    for option in options:
        option.has_voted = option.vote_set.filter(voter=request.user).exists()

    ...

    return render(request, 'rank/options.html', {'options': options,'form':form,'title': 'options','category':category})

然后您可以在呈现按钮时检查模板中的has_voted属性:

{% if option.has_voted %}
    You already voted
{% else %}
    <input type="submit" class="btn btn-success" value="Vote" >
{% endif %}