About Dynamic Model Forms

You can display the fields of model forms dynamically by modifying the fields attribute and the crispy forms layout:

# content/forms.py
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms import layout
from .models import Post

NOTHING = layout.HTML("")

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = "__all__"

    def __init__(self, config, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if not config.show_subtitle:
            del self.fields["subtitle"]
        if not config.show_slug:
            del self.fields["slug"]

        self.helper = FormHelper()
        self.helper.layout = layout.Layout(
            layout.Field("title"),
            layout.Field("subtitle") if config.show_subtitle else NOTHING,
            layout.Field("slug") if config.show_slug else NOTHING,
            layout.Field("body"),
        )

Tips and Tricks Programming Django 5.x Django 4.2 Django 3.2 django-crispy-forms