views:

306

answers:

2

A form will be spitting out an unknown number of questions to be answered. each question contains a prompt, a value field, and a unit field. The form is built at runtime in the formclass's init method.

edit: each questions receives a unique prompt to be used as a label, as well as a unique list of units for the select element.

this seems a case perfect for iterable form fieldsets, which could be easily styled. but since fieldsets - such as those in django-form-utils are defined as tuples, they are immutable... and I can't find a way to define them at runtime. is this possible, or perhaps another solution?

Edit:

formsets with initial_data is not the answer - initial_data merely enables the setting of default values for the form fields in a formset. a list of items can't be sent to the choicefield constructor by way of initial_data.

...unless I'm wrong.

+2  A: 

Check out formsets. You should be able to pass in the data for each of the N questions as initial data. Something along these lines:

question_data = []
for question in your_question_list:
    question_data.append({'prompt': question.prompt, 
                          'value': question.value, 
                          'units': question.units})
QuestionFormSet = formset_factory(QuestionForm, extra=2)
formset = QuestionFormSet(initial=question_data)
istruble
initial data is for giving default values to a form element, not for providing data for form construction in a formset.
Cody
A: 

Cody,

First of all Hi, I think we met at DjangoCon last year.

I used the trick below to create a dynamic formset. Call the create_dynamic_formset() function from your view.

def create_dynamic_formset(name_filter):

"""
-Need to create the classess dynamically since there is no other way to filter
"""
class FormWithFilteredField(forms.ModelForm):
    type = forms.ModelChoiceField(queryset=SomeType.objects.filter(name__icontains=name_filter))

    class Meta:
        model=SomeModelClass

return modelformset_factory(SomeModelClass,
                          form=FormWithFilteredField)
Dimitri Gnidash