13

I'm using django:

I'm trying to pass a list of tuples from views.py to a dropdown box form but I get this attribute error

forms.py

import logging                                                                   

from django import forms                                                         

log = logging.getLogger(__name__)                                                

class TestForm(forms.Form):                                                    

    def __init__(self, *args, **kwargs):                                         
        testlist = kwargs.pop('testlist',None)                               
        log.info(regionlist)                                                     
        self.fields['testlist'] = forms.ChoiceField(choices=testlist)        
        super(TestForm, self).__init__(*args, **kwargs) 

views.py

form = forms.RegionForm(regionlist=data)     

Am I using the right method to pass variables between views.py and forms.py?

Jalcock501
  • 389
  • 2
  • 6
  • 18

1 Answers1

32

You need to call super first, so that the superclass sets up the fields attribute.

def __init__(self, *args, **kwargs):                                         
    testlist = kwargs.pop('testlist', None)
    log.info(regionlist)
    super(TestForm, self).__init__(*args, **kwargs)
    self.fields['testlist'] = forms.ChoiceField(choices=testlist)        
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • 1
    This is a GREAT answer that I had to dig to find so I'm going to add some keywords to make it easier to find. To dynamically add fields to a form regardless of the form class parent (in other words, NO MODEL FORM and no need for save), this ^ allows the option to **pass in named arguments** to make **dynamic fields**. After form is instantiated (super) you can call any class functions on those variables passed in and set them to self.fields dynamically. Thus you have dynamic fields in a form that can be passed in at instantiation time. – MarMar Mar 16 '22 at 17:32
  • This answer solved a form reload problem I had where the dynamic fields kept the choices from the last run. I was querying elastic search for filters that would be given back dynamically and would change, the data and the form.fields and form.base_fields were being set correctly but the cache of the form didn't seem to be When it would render it would have the old fields and wouldn't update right though I passed in the filters (new dynamic fields) to the form. Now that I pass in the dynamic fields this way and recreate the form with the request and filters it works great! Thank you Daniel. – MarMar Mar 16 '22 at 17:33