我是django的新手并制作了一个简单的应用程序,让用户可以选择六个名单来挑选前六名。我遇到的问题是,任何用户登录后都可以看到其他人的投票!如何让已登录的用户(没有管理员)只看到他们的投票,而不是每个人的投票? 我一直在这里阅读,看起来它可以用查询集完成?但希望'能够实现这个想法。
我的model.py中有两个类:
class CandidateName(models.Model):
canidate_name = models.CharField(max_length=15)
def __str__(self):
return self.canidate_name;
class Vote(models.Model):
first_pick = models.ForeignKey(CandidateName, related_name= 'first')
second_pick = models.ForeignKey(CandidateName, related_name='second')
third_pick = models.ForeignKey(CandidateName, related_name='third')
fourth_pick = models.ForeignKey(CandidateName, related_name='fourth')
fifith_pick = models.ForeignKey(CandidateName, related_name='fifth')
sixth_pick = models.ForeignKey(CandidateName, related_name='sixth')
答案 0 :(得分:5)
您可以执行诸如向投票类添加“用户”字段之类的操作。
from django.contrib.auth.models import User
class Vote(models.Model):
user = models.ForeignKey(User)
first_pick = models.ForeignKey(CandidateName, related_name= 'first')
second_pick = models.ForeignKey(CandidateName, related_name='second')
third_pick = models.ForeignKey(CandidateName, related_name='third')
fourth_pick = models.ForeignKey(CandidateName, related_name='fourth')
fifith_pick = models.ForeignKey(CandidateName, related_name='fifth')
sixth_pick = models.ForeignKey(CandidateName, related_name='sixth')
然后在views.py中检索与当前登录用户关联的投票,并将其传递给您的模板。
if request.user.is_authenticated():
votes_by_user = Vote.objects.filter(user=request.user)