覆盖django中ChoiceField的初始化

时间:2013-08-30 11:36:42

标签: python django django-forms

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

# 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

任何帮助表示感谢。

2 个答案:

答案 0 :(得分:5)

您没有以良好的方式使用Form对象。 fields属性初始化by the __init__ method of BaseForm (see the source code)(父类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

答案 1 :(得分: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()]