我正在尝试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
?
任何帮助表示赞赏。