我是 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')
最佳答案
您可以执行一些操作,例如将 User 字段添加到您的 Vote 类中。
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)
关于python - Django 如何在登录时只显示用户自己的帖子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35689724/