Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 660
Jalcock501 Avatar asked Apr 26 '18 11:04

Jalcock501


1 Answers

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)        
like image 189
Daniel Roseman Avatar answered Sep 19 '22 16:09

Daniel Roseman