2017-04-07 87 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

明白了,謝謝! –