All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.py.rules.python.S6559.html Maven / Gradle / Ivy

There is a newer version: 4.23.0.17664
Show newest version

This rule discourages the use of exclude or __all__ with ModelForm in Django and suggests using fields instead.

Why is this an issue?

In Django, when creating a ModelForm, it is common to use exclude to remove fields from the form. It is also possible to set the fields value to __all__ to conveniently indicate that all the model fields should be included in the form. However, this can lead to security issues when new fields are added to the model, as they will automatically be included in the form, which may not be intended. Additionally, exclude or __all__ can make it harder to maintain the codebase by hiding the dependencies between the model and the form.

How to fix it

Developers should use the "fields" attribute instead of "exclude" or "all" when creating ModelForms in Django. This ensures that all fields are explicitly listed and makes it clear what fields are included in the form.

Code examples

Noncompliant code example

from django import forms

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        exclude = ['field1', 'field2']  # Noncompliant


class MyOtherForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = '__all__'  # Noncompliant

Compliant solution

from django import forms

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ['field3', 'field4']

Resources

Documentation

Django ModelForm documentation Django form fields documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy