Django 'TestForm' 对象没有属性 'fields'

Django 'TestForm' object has no attribute 'fields'

我正在使用 django:

我试图将元组列表从 views.py 传递到下拉框表单,但我收到此属性错误

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)     

我在 views.pyforms.py 之间传递变量的方法是否正确?

您需要先调用super,以便超类设置fields属性。

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)