如何在视图中指定要使用表单的字段?

时间:2014-11-07 15:12:25

标签: django django-forms

我有模特:

class ModelA(models.Model):
    field_1 = models.CharField(blank=True, null=True)
    field_2 = models.CharField(blank=True, null=True)
    field_3 = models.CharField(blank=True, null=True)
    field_4 = models.CharField(blank=True, null=True)
    field_5 = models.CharField(blank=True, null=True)

我必须生成三种形式:

class Form1(forms.ModelForm):

    class Meta:
        model = ModelA
        fields = ['field_1', 'field_2', 'field_3']


class Form2(forms.ModelForm):

    class Meta:
        model = ModelA
        fields = ['field_1', 'field_2', 'field_4']


class Form3(forms.ModelForm):

    class Meta:
        model = ModelA
        fields = ['field_1', 'field_2', 'field_5']

如何将其转换为一种形式并影响视野中的“字段”?我在一个模板中显示所有这些表单。

1 个答案:

答案 0 :(得分:0)

您使用的是基于类的视图吗?我建议使用CreateView / UpdateView来执行此操作。自从类处理该表单以来,您根本不需要创建表单,并且您可以在视图中为该特定视图所需的任何字段指定fields属性。 django doc有一个非常好的例子:https://docs.djangoproject.com/en/1.6/topics/class-based-views/generic-editing/#model-forms

class AuthorUpdate(UpdateView):
    model = Author
    fields = ['name']

因此,对于您的示例,它可能是:

class View1(CreateView):
   model= ModelA
   fields = ['field_1', 'field_2', 'field_3']

class View2(CreateView):
   model= ModelA
   fields = ['field_1', 'field_2', 'field_4']

class View3(CreateView):
   model= ModelA
   fields = ['field_1', 'field_2', 'field_5']