如何创建django表单中的字段列表 [英] How to create a list of fields in django forms

查看:114
本文介绍了如何创建django表单中的字段列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使一个django表单类实际上拥有一个字段数组?我有一个数据库,将提出一个可变的问题,以询问用户,每个问题将知道如何定义它的小部件...等等,我似乎无法挂钩到django表单。



我尝试过:

  class MyForm(forms.Form):
question = []
questions = Question.objects.all()
在问题中的q:
question.append(forms.CharField(max_length = 100,label = q.questionText))

但是,当我创建一个新的<$ c实例时,这似乎没有暴露我的问题列表$ C> MyForm的。有没有办法使用django表单获取可变数量的表单域,或者这超出了它可以做什么的范围?

解决方案

您可以使用 formets (如果您的表单为相同(包括他们的标签)。例如



问题:__________________

问题:__________________

问题:__________________



等。我假设每个表单只包含一个字段(问题字段)。在这个例子中有三种形式。






如果您需要一个动态数量的单一 form,那么你可以使用 __ init __ 来实现你想要的(注意:未经测试的代码!):

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

而你'd创建一个类似于

  form = MyForm(questions = your_list_of_questions)

你会发现这篇文章很有用: http://jacobian.org/writing/dynamic-form-generation/


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?

解决方案

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/

这篇关于如何创建django表单中的字段列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆