I am building a Quiz app where a user (Content Creator or Author) can create quizzes (choice based questions and their solutions).
I have these models:
class question(models.Model):
text = models.TextField(max_length=512, blank=False)
author = models.OneToOneField(User)
doc = models.DateField(auto_now_add=True)
dscore = models.IntegerField()
btax = models.CharField(max_length=3)
subj = models.CharField(max_length=3)
qtype = models.CharField(max_length=1)
flag = models.CharField(max_length=16)
tags = TaggableManager()
class choice(models.Model):
text = models.CharField(max_length=64, blank=False)
ques = models.ForeignKey('question')
tags = TaggableManager()
class answer(models.Model):
text = models.TextField(max_length=512)
ques = models.ForeignKey('question')
choice = models.ForeignKey('choice')
tags = models.CharField(max_length=32)
I have to create a single form incorporating all the three models: question, choice, answer. I know that this can be achieved using inline formset like
from django.forms.models import inlineformset_factory
inlineformset_factory(question, choice)
What is not clear: how do I put all three models in here, something like
inlineformset_factory(question, choice, answer)
and also be able to specify what fields are to appear on the form.
You will need an inline formset per foreign key :
QuestionChoiceFormset = inlineformset_factory(question, choice)
QuestionAnswerFormset = inlineformset_factory(question, answer)
In your template, accessing for fields is just like for a normal formset / form.
@Rexford comment's link is spot on, it does the same thing as what you want. You can find examples for functions based views as well based on the same 'recipe' example.