我有一个 Entry 模型,其中有一个“推送”字段,我希望每个用户“推送”(投票)一次。 我进行了搜索,但没有找到我需要的内容。
这是我的模型:
class Entry(models.Model):
title = models.CharField(max_length = 100)
link = models.URLField(verify_exists=False)
posted = models.DateTimeField(auto_now_add=True)
submitter = models.ForeignKey(User, blank=True, null=True)
pushes = models.PositiveIntegerField(default=0)
def __unicode__(self):
return self.title + " - " + unicode(self.submitter)
这是我的主页 View :
def homepage(request):
entries = Entry.objects.all().order_by('-posted')
paginator = Paginator(entries, 30)
try: page = int(request.GET.get('page', '1'))
except ValueError: page = 1
try:
entries = paginator.page(page)
except (InvalidPage, EmptyPage):
entries = paginator.page(paginator.num_pages)
return render_to_response('index.html', {'entries' : entries},
context_instance=RequestContext(request))
如何才能让用户不能多次推送?
我必须创建一个新函数吗?
我应该更改模型中的某些内容吗?
最佳答案
如果您只想允许唯一选民,则不能只用数字跟踪选票 - 您需要执行以下两项操作之一:
- 将投票记录为与用户关联的独立对象
- 将用户的投票历史记录记录为该用户对象的一部分
第一个几乎总是更容易做到,特别是如果您的用户要在多个“选举”中投票。
通常,您要做的是创建一个投票对象,该对象与被投票的事物和进行投票的用户相关联,然后在这两个项目上创建一个唯一的 key ,以便任何给定配对中只有一个实例被允许存在。
关于python - 如何确保用户在 python django 中只投票一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9649617/