2013-03-01 32 views

回答

1

当我想改变某些形式的东西,如标签文本,添加必需的字段或过滤选择列表等。我遵循一个模式,我使用ModelForm并添加一些实用方法,它包含我的首要代码(这有助于保持__init__整洁)。然后从__init__调用这些方法来覆盖默认值。

class ProfileForm(forms.ModelForm): 
    class Meta: 
     model = Profile 
     fields = ('country', 'contact_phone',) 

    def __init__(self, *args, **kwargs): 
     super(ProfileForm, self).__init__(*args, **kwargs) 

     self.set_querysets() 
     self.set_labels() 
     self.set_required_values() 
     self.set_initial_values() 

    def set_querysets(self): 
     """Filter ChoiceFields here.""" 
     # only show active countries in the ‘country’ choices list 
     self.fields["country"].queryset = Country.objects.filter(active=True) 

    def set_labels(self): 
     """Override field labels here.""" 
     pass 

    def set_required_values(self): 
     """Make specific fields mandatory here.""" 
     pass 

    def set_initial_values(self): 
     """Set initial field values here.""" 
     pass 

如果ChoiceField是你要被定制的唯一的事情,这是所有你需要:

class ProfileForm(forms.ModelForm): 
    class Meta: 
     model = Profile 
     fields = ('country', 'contact_phone',) 

    def __init__(self, *args, **kwargs): 
     super(ProfileForm, self).__init__(*args, **kwargs) 

     # only show active countries in the ‘country’ choices list 
     self.fields["country"].queryset = Country.objects.filter(active=True) 

然后,您可以让您的FormView控件使用这种形式,像这样:

class ProfileFormView(FormView): 
    template_name = "profile.html" 
    form_class = ProfileForm