存储每个选项的Voterid的Django民意调查教程

时间:2017-04-07 10:17:35

标签: django vote

您好我已经使用教程创建了Django投票应用程序。我希望添加,以便当登录用户投票选择时,选择部分存储到db中。 Models.py

class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=400)
vote = models.IntegerField(default=0)
points = models.IntegerField(default=1)
def __str__(self):
    return self.choice_text


class Voter(models.Model):
user = models.ForeignKey(User)
selections = models.CharField( 'question.choice', max_length=600)

我的Views.py和Vote.view:

class VoteView(generic.View):
def dispatch(self, request, *args, **kwargs):
    # Getting current question
    question = get_object_or_404(Question,     pk=kwargs.get('question_id'))

    try:
        selected_choice =    question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Display flash message
        messages.error(request, "You didn't select a choice.")

        # Redirect to the current question voting form again
        return HttpResponseRedirect(reverse('questionaire:detail', args=(kwargs.get('question_id'),)))
    else:
        selected_choice.vote += 1
        selected_choice.save()
        v = Voter(user=request.user, Question=q)
        v.save()

所以我试图将每个用户选择的选项保存到数据库中,数据库将被存储以供以后处理和分析。

1 个答案:

答案 0 :(得分:0)

您可以将QuestionChoice添加到模型Voter作为ForeignKey字段。

Question您可能已经Voter FK在这里没有写过。

另外,请考虑将模型从Voter重命名为Vote