Skip to content

[DJ06] Do not use exclude with ModelForm, use fields instead

Rocio Aramberri edited this page May 23, 2020 · 3 revisions

When using a ModelForm it is possible to specify the fields that you want to exclude from the form by using the exclude attribute within the form's inner Meta.

Even though it is practical to use the exclude attribute, it is not recommended due to security concerns. Any new field that is added to the model will be automatically exposed for modification.

Use the fields attribute instead to specify the exact fields that you want to expose on the form.

Don't

class PostForm(ModelForm):
    class Meta:
        model = Post
        exclude = ['author']

Do

from django.forms import ModelForm

class PostForm(ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'content']

Reference

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