2013-03-01 29 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