2013-02-16 42 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