为什么我们需要 Django 表单中 Meta class 中的字段值?

Why do we need fields value in Meta class in Django forms?

如果我的表单 class 中有 3 个字段,而在 fields 中我只设置了一个字段,在我的 html 页面上仍然是 3 个字段。

示例:

class CategoryForm(forms.ModelForm):
    name = forms.CharField(max_length=128,
                           help_text='Please enter the category name.')
    views = forms.IntegerField(initial=0)
    likes = forms.IntegerField(initial=0)
    slug = forms.CharField(widget=forms.HiddenInput(), initial=0)

    class Meta:
        model = Category
        fields = ('name',)

所以 fields 变量没有隐藏任何东西?

"The generated Form class will have a form field for every model field specified, in the order specified in the fields attribute."

如果要隐藏字段,请使用

exclude = ('views','likes','slug')

我强烈建议您看一下文档:

https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/#selecting-the-fields-to-use