When a user fills in a form, a related record they need may not exist yet. For example, a salesperson creating an Opportunity may find that the Stage they want isn’t defined. Horilla CRM handles this with a dynamic create icon: a “+” button beside a ForeignKey or ManyToMany field. It opens a small form in a modal, saves the new record, and selects it in the field, so the user never leaves the page.

This post shows how to add the icon to a field in your own form view.

Prerequisites

  • A form view that extends HorillaSingleFormView or HorillaMultiStepFormView.
  • A field on the model that is a ForeignKey or ManyToManyField. Other field types are ignored.
  • A user with the add permission on the related model (for example, opportunities.add_opportunitystage).

Step 1: List the Fields in dynamic_create_fields

On your form view, set dynamic_create_fields to the names of the fields that should show the icon.

@method_decorator(htmx_required, name="dispatch")
class OpportunityMultiStepFormView(LoginRequiredMixin, HorillaMultiStepFormView):
    form_class = OpportunityFormClass
    model = Opportunity
    total_steps = 3
    fullwidth_fields = ["description"]
    dynamic_create_fields = ["stage"]

That is enough to show the icon. Horilla looks up the related model of stage and builds the create URL for it. It uses the generic route generics:dynamic_create, which takes the app label and model name.

Step 2: Let the Form Accept the Generic Arguments

Horilla passes dynamic_create_fields, full_width_fields, and hidden_fields into the form’s constructor. If your form class doesn’t inherit from Horilla’s base form, remove them in __init__ so Django doesn’t reject them.

def __init__(self, *args, **kwargs):
    self.request = kwargs.pop("request", None)


    generic_attrs = [
        "full_width_fields",
        "dynamic_create_fields",
        "hidden_fields",
    ]
    for attr in generic_attrs:
        kwargs.pop(attr, None)


    super().__init__(*args, **kwargs)

Step 3: Customise the Popup with dynamic_create_field_mapping

By default, the popup shows every field of the related model. To change that, add a dynamic_create_field_mapping dictionary keyed by field name.

dynamic_create_field_mapping = {
    "stage": {
        "fields": [
            "name",
            "order",
            "probability",
            "stage_type",
            "is_final",
        ],
        "full_width_fields": ["description"],
        "initial": {
            "order": OpportunityStage.get_next_order_for_company,
        },
        "permission": "opportunities.add_opportunitystage",
    },
}

Each key controls a different part of the popup configuration.

KeyWhat it does
fieldsLimits the popup to these fields of the related model.
full_width_fieldsFields that span the full width of the popup.
initialDefault values for the new record. A value can be a callable. If an active company is set, it is called with the company; otherwise, it is called without arguments. This is useful for generating the next order number.
permissionA string or a list of permissions that overrides the default <app>.add_<model> permission. The icon is shown if the user has any one of the specified permissions.

Every key is optional. You can leave out the mapping completely or provide only the settings you need.

For example, to make the description field span the full width without changing the other defaults:

dynamic_create_field_mapping = {
    "stage": {
        "full_width_fields": ["description"],
    },
}

Step 4: Check the Result

  1. Open the form as a user with the add permission on the related model. The “+” icon should appear next to the field.
  2. Click the icon. The create form for the related model should open in a modal with the configured fields and default values.
  3. Save the new record. It should be selected in the original field, while the rest of the form retains its values.
  4. Log in as a user without the required permission. The icon should not appear because Horilla filters dynamic_create_fields through get_filtered_dynamic_create_fields() before rendering.

Troubleshooting

  • The icon doesn’t appear. Check that the field is a ForeignKey or ManyToManyField, its name is spelled correctly in dynamic_create_fields, and the user has the required add permission. Fields that fail these checks are skipped without an error.
  • The popup shows too many fields. Add a fields list to the mapping.
  • A default value is wrong or missing. A callable in initial that raises an exception is skipped silently. Test the callable independently.
  • The popup’s custom form is rejected. Check that the form’s __init__ method removes the generic arguments, as shown in Step 2.

To add a dynamic create icon, list the field in dynamic_create_fields. To customise the popup, add an entry in dynamic_create_field_mapping for that field. Horilla handles URL generation, permission checks, and field configuration through this feature.

The implementation discussed here is based on form_mixin.py and single_form_view.html under horilla/contrib/generics/, along with the Opportunities form views.

Share this article