About Dynamic Model Forms

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 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 4.x Django 3.2 Django 2.2 django-crispy-forms