Friday, October 29, 2010

Using formsets with multiple models

Hi,

I'm creating an online questionnaire for my local community college,
and hitting a brick wall dealing with formsets. Please can someone
point me in the right direction?

On a questionnaire, you have one or more questions which will require
either an essay answer or multiple choice answers. When creating a new
questionnaire, I would like to show a textarea for the Question.text
common to both types, a radio select for the Question.question_type,
and then present either the EssayQuestion.initial_answer textarea or
the inputs for adding multiple choice options. The user can click "add
question" to append another form beneath to enter a new question. It's
only on the final "save questionnaire" that I handle the POST and
save.

I have spent a few days now trying different permutations of
formsets, modelformsets and inline_formsets but to no avail. The
closest I've got is to create a QuestionFormset, EssayQuestionFormset
and a MultipleChoiceQuestionFormset, then keep track of which form
belongs to which question when saving. I'm not sure how to reconstruct
the forms should it raise validation errors though.

Another option is to create a QuestionForm containing fields for 0..N
possible fields, i.e. multiplechoice_choice_0,
multiplechoice_correct_0, multiplechoice_choice_1,... But this feels
wrong to me.

It seems overly complicated which makes me think I'm going about it
the wrong way. Any help would be much appreciated please!

Thanks,

Bill

Here's my models.py, let me know what else may help.

models.py
========
class Questionnaire(models.Model):
name = models.CharField()

class Question(models.Model):
questionnaire = models.ForeignKey(Questionnaire)
question_type = models.CharField(choices=QUESTION_TYPES)
text = models.TextField()

class EssayQuestion(models.Model):
question = models.OneToOneField(Question)
initial_answer = models.TextField()

class MultipleChoiceQuestion(models.Model):
question = models.ForeignKey(Question)
choice = models.CharField()
correct = models.BooleanField()

--
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 django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment