1

I'm working on a Django 1.6 project that allows users to create mailing lists for their legislature. So a user goes to the page, clicks some check boxes next to the legislators they want in their list, and the form compiles the mailing list for them.

My problem: my form's fields are dynamic. I'm pulling a list of legislators fresh from a RESTful API each time the form is loaded. I'm not using Django's form class, because I don't want to specify the form fields in advance. My view looks like this:

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})

Each list is displayed like this:

    <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>

Generally, I would use the Django forms class to check the data and process the form. What I want is to put together a list of all the boxes checked. Is there a way to process this in Django, or some way to handle a form without specifying it's fields in advance?

indigochild
  • 350
  • 1
  • 5
  • 21

1 Answers1

1

This answer:

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

links to this blog post:

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

With this example:

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)
voy
  • 1,568
  • 2
  • 17
  • 28