How to create a list of fields in django forms

ⅰ亾dé卋堺 提交于 2019-12-20 10:41:44

问题


Is there any way to make a django forms class that actually holds an array of fields? I have a database that will pull up a variable number of questions to ask the user and each question will know how to define it's widget...etc, I just can't seem to hook this up to django forms.

I tried this:

class MyForm(forms.Form):
    question = []
    questions = Question.objects.all()
    for q in questions:
        question.append(forms.CharField(max_length=100, label=q.questionText))

But this doesn't seem to expose my questions list when I create a new instance of MyForm. Is there any way to get a variable number of form fields using django forms, or is this beyond the scope of what it can do?


回答1:


You may be able to use formsets if your forms are identical (including their labels). e.g.

Question: __________________
Question: __________________
Question: __________________

etc. I'm assuming each form contains only one field here (the 'Question' field). There are three forms in this example.


If you need a dynamic number of fields in a single form, then you can use __init__ to achieve what you want (note: untested code!):

class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        questions = kwargs.pop('questions')
        super(MyForm, self).__init__(*args, **kwargs)
        counter = 1
        for q in questions:
            self.fields['question-' + str(counter)] = forms.CharField(label=question)
            counter += 1

And you'd create the form with something like:

form = MyForm(questions=your_list_of_questions)

You'll find this article useful: http://jacobian.org/writing/dynamic-form-generation/




回答2:


Of course you can!

class MyForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        for i, q in enumerate(Question.objects.all()):
            self.fields['%s_field' % i] = forms.CharField(max_length=100, label=q.questionText)

Note: make sure your questions are ordered between calls.. as the field list will be repopulated upon form submission, receipt, etc.

If the data is ordered and static, it won't be a problem.

Also you may want to look into FormSets, a list of forms which may be more fitting in your case.



来源:https://stackoverflow.com/questions/17159567/how-to-create-a-list-of-fields-in-django-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!