0

I want to display a form to answer multiple types of questions in a survey/test (kind of like Google Forms). My models are set up such that I have a Test model, an Answer model with a foreign key to the Test, and subclasses of Answer (such as multiple choice, short answer) with the necessary extra fields for that question type.

My first thought was to use an inline formset for to display the fields for the answers. However, if I create an inline formset for Answer, the form only shows the fields for this superclass, not for the specific subclass answer types. And it doesn't appear (based on my searches) that it's possible to create an inline formset with multiple model types. Is this functionality possible?

(It occurs to me that it might be possible by essentially manually rolling a formset by creating a list of individual forms for every Answer, but this doesn't seem like a very elegant solution.)

3
  • If you are using CBV's check django-extra-views includes inline formsets (Create and Update View).
    – petkostas
    Jul 22, 2014 at 15:05
  • The issue isn't the lack of a CBV for inline formsets; it's that inline formsets aren't getting the job done. Jul 22, 2014 at 15:12
  • I sorry but I don't see any kind of code (model related) in order to be more clear, if I am right you have an Abstract Answer model class and from there you implement a concrete? if yes then again a ModelForm for each answer and inlines could be the solution, in order to avoid DRY I would check the extra views classes and override them to inject the different models.
    – petkostas
    Jul 22, 2014 at 19:10

1 Answer 1

0

if i understood correct: you can create dynamic inline for each model:

def get_inline_by_model(m):
    return type(
        'YourInline', 
        (admin.StackedInline, ), 
        {'model' : m, 'extra' : 0,'form' : YourAdminForm,'max_num' : 1,'fields' :('key','value')} 
    ) 

and in your admin model:

inlines = [
        get_inline_by_model(models.YourModel),
    ]

and in this way you can use the same inline form for multiple models

1
  • What I'm trying to create isn't in the admin. It's just in a normal view. Jul 22, 2014 at 15:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.