带有动态字段的Django表单

时间:2014-12-24 02:54:26

标签: django forms

我正在开发一个允许用户为其立法机构创建邮件列表的Django 1.6项目。因此,用户转到该页面,单击他们希望列表中的立法者旁边的一些复选框,然后该表单为他们编译邮件列表。

我的问题:我的表单字段是动态的。每次加载表单时,我都会从RESTful API中提取新的立法者列表。我没有使用Django的表单类,因为我不想提前指定表单字段。我的观点如下:

def klissRequest(url):
    with urllib.request.urlopen(url) as query:
        response = json.loads(query.read().decode())
    return response['content']

def newList(request):
    # Create list of all legislators
    allLegislators = klissRequest('http://www.kslegislature.org/li/api/v6/rev-1/members/')

    masterlist = []
    kpids = []

    for i in allLegislators.keys():
        for j in allLegislators[i]:
            masterlist.append(j)
            kpids.append(j['KPID'])

    # Create committee lists - House, Senate, and Joint
    masterComs = klissRequest('http://www.kslegislature.org//li/api/v5/rev-1/ctte/')
    senateComs = []
    houseComs = []
    specialComs = []

    for i in masterComs['house_committees']:
        houseComs.append(i)
    for i in masterComs['senate_committees']:
        senateComs.append(i)
    for i in masterComs['special_committees']:
        specialComs.append(i)

    return render(request, 'newList.html', {'kpids':kpids, 'masterlist':masterlist, 'senateComs':senateComs, 'houseComs':houseComs, 'specialComs':specialComs})

每个列表都显示如下:

    <div> Individual Legislators </div>
    <ul>
        <div>
            {% for i in masterlist %}
            <li><input type="checkbox" name="selected[]" value="{{i.NAME}}" /><label for="{{i.NAME}}">{{i.NAME}}</label></li>
            {% endfor %}
        </div>
    </ul>
    </div>

通常,我会使用Django表单类来检查数据并处理表单。我想要的是整理所有选中框的列表。有没有办法在Django中处理这个,或者某种方式处理表单而没有预先指定它的字段?

1 个答案:

答案 0 :(得分:1)

这个答案:

https://stackoverflow.com/a/5478634/1338790

此博客文章的链接:

https://twigstechtips.blogspot.com/2011/10/django-dynamic-forms-with-dynamic.html

通过这个例子:

class ExampleDynamicForm(forms.Form):
  normal_field = forms.CharField()
  choice_field = forms.CharField(widget = forms.Select(choices = [ ('a', 'A'), ('b', 'B'), ('c', 'C') ]))

  def __init__(self, user, *args, **kwargs):
    # This should be done before any references to self.fields
    super(ExampleDynamicForm, self).__init__(*args, **kwargs)

    self.user = user
    self.id_list = []

    # Some generic loop condition to create the fields
    for blah in Blah.objects.for_user(user = self.user):
      self.id_list.append(blah.id)

      # Create and add the field to the form
      field = forms.ChoiceField(label = blah.title, widget = forms.widgets.RadioSelect(), choices = [('accept', 'Accept'), ('decline', 'Decline')])
      self.fields["blah_%s" % blah.id] = field

    # Change the field options
    self.fields['choice_field'].widget.choices = [ ('d', 'D'), ('e', 'E'), ('f', 'F') ] 


# to use the form:
form = ExampleDynamicForm(request.user)