2017-04-07 51 views
0

嗨我已经创建了教程的Django投票应用程序。我正在寻找添加,以便登录用户投票选择时,选择部分存储到数据库。 Models.pyDjango民意调查教程与Voterid每选择存储

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() 

所以我试图挽救%的用户选择了到数据库的选择,这将被存储,用于以后的处理和分析。

+0

你有问题吗? –

回答

0

您可以将QuestionChoice添加到VoterForeignKey字段中。

您可能已有Question FK Voter只是没有写在这里。

另外,考虑重新命名从Voter你的模型Vote

+0

明白了,谢谢! –