1

我正在尝试ChoiceField在 django 中初始化一个包含 a 的表单。我有以下代码:

# in file models.py
class Locality(models.Model):
    locality = models.CharField(primary_key=True, unique=True, max_length=36)
    def __unicode__(self):
        return self.locality

# in file forms.py
class RegisterForm(forms.Form): 
    def __init__(self, *args, **kwargs):
        self.username = forms.CharField(required=True)
        self.email = forms.EmailField(required=True)
        self.locality = forms.ChoiceField(widget=forms.Select())
        self.fields['locality'].choices = [l.locality for l in Locality.objects.all()]

但是在外壳上,一旦我尝试实例化:

r = RegisterForm(username="toto", email="a@b.com")

我收到'RegisterForm' object has no attribute 'fields' error。这是因为物体还没有形成吗?我怎样才能访问ChoiceField

任何帮助表示赞赏。

4

2 回答 2

5

您没有以Form良好的方式使用该对象。该fields属性是由 BaseForm__init__方法(参见源代码)(的父类forms.Form)初始化的,但是您已经重新定义了它,因此您破坏了该过程。

__init__因此,您应该在方法中调用父级__init__,如下所示:

class RegisterForm(forms.Form): 
    username = forms.CharField(required=True)
    email = forms.EmailField(required=True)
    locality = forms.ChoiceField(widget=forms.Select())

    def __init__(self, *args, **kwargs):
         super(forms.Form, self).__init__(*args, **kwargs)
         self.fields['locality'].choices = [(l.id, l.locality) for l in Locality.objects.all()]

我已将每个*Field声明移到 之外__init__,因为这是常见的方式。它的问题与上一个问题非常相似:Override defaults attributes of a Django form

于 2013-08-30T11:44:11.450 回答
2

尝试:

def __init__(self, *args, **kwargs):
     super(forms.Form, self).__init__(*args, **kwargs)
     self.fields['locality'].choices = [(l.id, l.locality) for l in Locality.objects.all()]
于 2013-08-30T11:50:06.707 回答