Search code examples
pythondjangoformsdropdownbox

Django 'TestForm' object has no attribute 'fields'


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?


Solution

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