我一直在关注用于构建民意调查应用程序的django教程,我不明白为什么应用程序允许用户多次投票。
答案 0 :(得分:0)
嗯,实现你描述的内容会更复杂,而对于教程,你需要简单的代码。这还需要身份验证才能识别用户,以获取我将在下面使用的request.user
值(除非视图设置为login_required
,否则该值并非始终可用)
使用教程中的模型,我担心不可能这样做,因为当用户投票时,所有发生的操作都是selected_choice += 1
操作,如您所见,不会记录用户
如果您想在投票中记录用户,则必须创建一个模型来执行此操作,例如
class Vote(Model):
question = ForeignKey(Question)
selected_choice = ForeignKey(Choice)
user = ForeignKey(User)
class Meta:
unique_together = (
('question', 'user'),
)
如上所述unique_together
确保我们的数据库每个问题只能为每个用户选择一个选项
这里有一些关于如何处理投票行动的伪代码
def vote(request, question_id):
user = request.user
question = get_object_or_404(Question, pk=question_id)
selected_choice = question.choice_set.get(pk=request.POST['choice'])
# Update the vote info, or create if doesn't exist yet
Vote.objects.update_or_create(
user=user,
question=question,
defaults={'selected_choice': selected_choice}
)
# Recalculate the select choice counts for the question
# For the question, set each question.choice to the count