【问题标题】:CBV Django Form View set data for ChoiceFieldChoiceField 的 CBV Django 表单视图集数据
【发布时间】:2013-03-01 16:07:31
【问题描述】:

我正在使用 Django 表单视图,我想将每个用户的自定义选项输入到我的 Choicefield

我该怎么做?

我可以使用get_initial 函数吗? 我可以覆盖该字段吗?

【问题讨论】:

    标签: django django-forms django-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
    

    【讨论】:

      猜你喜欢
      • 2017-08-31
      • 2017-04-10
      • 2022-01-01
      • 1970-01-01
      • 2014-07-11
      • 1970-01-01
      • 1970-01-01
      • 2019-06-21
      • 1970-01-01
      相关资源
      最近更新 更多