How to create a "fill in the blanks" form in Django

I want to create a space filling widget in Django.

Example question: "Put your answers __ and __."

So basically, I need an output that would replace the __ fields with input fields.

In addition, I want the input fields to have the same name. Example:

<input id="id_1" type="text" name="blank[]" />
<input id="id_2" type="text" name="blank[]" />

The number of empty fields (maybe) is infinite. How to do it with django.forms?

Thank.

+5
source share
1 answer

You have a list of fields on which you need to visualize the quiz, as I understand it. So, the list is as follows:

questions = (
  ('Place your 1 answers %s and %s.', ('field_1_1', 'field_2_2')),
  ('Place your 2 answers %s and %s.', ('field_2_1', 'field_2_2')),
)

You can create a form for each field, for example:

class QuizzForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(QuizzForm, self).__init__(*args, **kwargs)
        for question in questions:
            for field in question[1]:
                self.fields[field] = forms.ChoiceField()

And access the fields after a message similar to this:

if form.is_valid():
    for question in questions:
        for field in question[1]:
            answer = form.cleanded_data.get(field)
0
source

All Articles