2013-02-16 76 views
0

所以我有這些模型Question,Answer,和UserAnswer組成一個測驗。我面臨的問題是製作一個可以通過這些模型進行驗證的表單。我有一個如何做的想法,但它不工作。Django測驗 - 用戶生成

class QAForm(forms.Form): 
    answers = forms.ChoiceField(label='Question is this', choices=[('Answer1','Answer1'),('Answer2','Answer2')], widget=forms.RadioSelect()) 

這適用於1表格,而不是數千。我將如何修改此代碼,以便用戶將所有用戶生成的問題作爲表單答案,並可以提供自己的答案。

我有這樣的(它的工作原理,但我知道這是不是一個好的做法):

def questions(request): 
    queryset = Questions.objects.all() 
    if request.method =='POST': 
     a = request.POST['answer'] 
     answer = Answer.objects.get(answer=a) 
     importance = request.POST['importance'] 
     q = request.POST['question'] 
     question = Questions.objects.get(id=q) 
     try: 
      user_answer = UserAnswers.objects.get(owner=request.user, question=question) 
      user_answer.answer = answer 
      user_answer.importance = importance 
      user_answer.save() 
     except: 
      user_answer = UserAnswers(owner=request.user, question=question, answer=answer, importance=importance) 
      user_answer.save() 
    else: 
     try: 
      current = UserAnswers.objects.all().filter(owner=request.user) 
     except: 
      current = '' 
return render_to_response("questions/base.html", locals(), context_instance=RequestContext(request)) 

我的模型:

class Answer(models.Model): 
     answer = models.CharField(max_length=120) 
     question = models.ForeignKey('Questions', null=True, blank=True) 

     def __unicode__(self): 
       return self.answer 

IMPORTANCE = (
     ('Irrelevant', 'Irrelevant'), 
     ('A Little Important', 'A Little Important'), 
     ('Somewhat Important', 'Somewhat Important'), 
     ('Very Important', 'Very Important'), 
     ('Mandatory', 'Mandatory'), 
) 

class Questions(models.Model): 
     owner = models.ForeignKey(User) 
     question = models.CharField(max_length=300) 
     importance = models.CharField(max_length=120, choices=IMPORTANCE, null=True, blank=True) 
     updated = models.DateTimeField(auto_now=False, auto_now_add=True) 
     timestamp = models.DateTimeField(auto_now=True) 

     def __unicode__(self): 
       return self.question 

     class Meta: 
       verbose_name   ='Question' 
       verbose_name_plural  ='Questions' 


class UserAnswers(models.Model): 
     owner = models.ForeignKey(User) 
     question = models.ForeignKey(Questions) 
     answer = models.ForeignKey(Answer) 
     importance = models.CharField(max_length=120, choices=IMPORTANCE) 

     def __unicode__(self): 
       return str(self.owner) + " " + str(self.answer) + " " + str(self.importance) 
+0

[你嘗試過什麼?](http://whathaveyoutried.com) – arulmr 2013-02-16 10:21:48

+0

@arulmr只是增加了我的意見,告訴你如何我現在有它的工作。 – jmitchel3 2013-02-16 10:24:00

+0

用戶生成的部分工作正常。這是表單的渲染不能正常工作。 – jmitchel3 2013-02-16 10:29:47

回答

2

這個怎麼樣? (沒有實際測試它,但它應該工作)

class QuestionForm(forms.ModelForm): 
    answer = forms.ChoiceField(required=True, widget=forms.RadioSelect()) 

    def __init__(self, question=None, *args, **kwargs): 
     super(QuestionForm, self).__init__(*args, **kwargs) 
     self.fields['answer'].choices = [(a.text, a.value) for a in Answer.objects.filter(question=question)] 

    class Meta: 
     model = Question 
     fields = ('text') 

然後啓動它喜歡 -

q = Question.objects.get(pk=1) 
qform = QuestionForm(instance=q) 

這可以當你想只是一種形式來完成。如果你想要成千上萬的話,你可以使用FormSet。 PS:我假設Answer模型對Question模型有一個外鍵,並且它們已經被填滿了。

+0

老兄!那工作得很好。非常感謝。我現在遇到的問題是它顯示了Answer模型中的所有對象(而不是關聯的對象)。我將更新我的原始問題以包含我的模型。 – jmitchel3 2013-02-17 22:17:11

+0

TBH:你不需要多種多樣的關係來回答。答案已經與Foreignkey在多對一關係中的問題有關。刪除行'answers = models.ManyToManyField(Answer)'並檢查答案的foreignkey字段的值。 – 2013-02-17 22:23:51

+0

哦耶謝謝你。我一直在玩這一段時間,以獲得理想的結果。除了調用'form.cleaned_data ['answer']'返回所有的答案實例,而不是所選的實例外,它現在可以很好地工作。 (與request.POST ['answer']'相同) – jmitchel3 2013-02-17 22:41:31

1

您的需求的最新編碼。你可以試試這個代碼:

class QuestionForm(forms.ModelForm): 
    answer = forms.ChoiceField(required=True, widget=forms.RadioSelect()) 

def __init__(self, question=None, *args, **kwargs): 
    super(QuestionForm, self).__init__(*args, **kwargs) 
    self.fields['answer'].choices = [(a.text, a.value) for a in Answer.objects.filter(question=question)] 

class Meta: 
    model = Question 
    fields = ('text') 

general knowledge