Hello, I am working on a small app, based on Malcolm Tredinnick's "complex forms" article, located at http://www.pointy-stick.com/blog/2008/01/06/django-tip-complex-forms/.
I have a few quiz questions, where each displays its available answers. The end result is that there are multiple Django (new) forms within one HTML form object, as intended. However, the answers for each quiz question are getting set to those for the last question in the list, as shown below: What is your quest? Answers: Red! Purple! What is your favourite colour? Answers: Red! Purple! If there is one question, the answers match up, but otherwise they're wrong for all but the last one. My own version (his is below) just adds a bunch of debug print statements. What I think is happening though, is that the answers coming from the database are correct, but the part where the fields are set appears to reference answers as a class variable. Does this sound correct? From debug output, the self.fields value starts off pretty much empty, then is updated OK the first time. For the second question, the self.fields still has the contents from the first question, until it updates it. Shouldn't this be a separate variable instance per question? Suggestions are welcome. Thanks, Tim (code follows) """ Create the quiz form(s). """ from django import newforms as forms from django.http import Http404 from models import Question class QuestionForm(forms.Form): answers = forms.ChoiceField(widget=forms.RadioSelect()) def __init__(self, question, *args, **kwargs): super(QuestionForm, self).__init__(*args, **kwargs) self.problem = question.problem answers = question.answers.order_by('statement') self.fields['answers'].choices = [(i, a.statement) for i, a in enumerate(answers)] # We need to work out the position of the correct answer in the sorted # list of all possible answers. for pos, answer in enumerate(answers): if answer.id == question.correct_answer_id: self.correct = pos break def is_correct(self): """ Determines if the given answer is correct (for a bound form). """ if not self.is_valid(): return False return self.cleaned_data['answers'] == str(self.correct) def create_quiz_forms(quiz_id, data=None): questions = Question.objects.filter(quiz__pk=quiz_id).order_by('id') form_list = [] for pos, question in enumerate(questions): form_list.append(QuestionForm(question, data, prefix=pos)) if not form_list: # No questions found, so the quiz_id must have been bad. raise Http404('Invalid quiz id.') return form_list --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---