Django Quiz-用户生成

时间:2013-02-16 10:19:07

标签: python django

所以我有这些模型QuestionAnswerUserAnswer组成了一个测验。我面临的问题是制作一个用这些模型验证的表格。我知道如何做到但它没有用。

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)

2 个答案:

答案 0 :(得分: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模型有一个问题模型的外键,它们已经被填满了。

答案 1 :(得分: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