An admin opens Settings, adds a “Preferred Contact Time” field to Leads, and it shows up straight away in forms, list columns, filters, reports, and exports. No developer ran makemigrations, and no server restarted. This post explains how Horilla CRM‘s field_management app does this, and why the design avoids monkey-patching.

Two ways to add a field

Model extension (_inherit_model)Custom field (field_management)
Created byA developer, in codeAn admin, in the UI
StorageA real database columnA row in CustomFieldValue
Needs a migrationYesNo
In Model._metaYesNo
NameNormal field namecf_<id>, for example cf_1

A model-extension field is an ordinary column, so every feature that reads _meta (mail templates, field permissions, reports, exports, conditions) shows it automatically. A custom field has no _meta entry, so each of those features needs a way to ask “are there extra fields I should know about?”. That is the design problem this app solves.

The data model

Two models, both extending HorillaCoreModel, so both are company-scoped.

CustomFieldDefinition has one row per custom field per model:

  • content_type: the target model.
  • name: the label the admin sees.
  • field_type: small_text, large_text, number, choice (multiple), single_choice, date or datetime.
  • is_required, choices (comma-separated options), order and is_full_width.

CustomFieldValue has one row per definition and record. It stores the record’s content_type and object_id, plus typed value columns:

  • value_text: text, and choices stored as a JSON list.
  • value_number: a decimal.
  • value_date: a date.
  • value_datetime: a timezone-aware datetime, stored in UTC.

Using a typed column per type means filters and rule engines compare real values rather than strings. set_value() writes the column that matches the definition’s type and clears the others. Dates are always stored in Gregorian form, even when the Jalali calendar picker is used. Display goes through Horilla’s DateTimeFormatter, so each user sees their own date format, timezone, and calendar.

Because a custom field is just a row, creating, renaming or deleting one needs no schema change.

Opt-in per model

Not every model should accept custom fields. The app registers a feature with auto_register_all=False:

register_feature(
    "custom_fields",
    "custom_fields_models",
    auto_register_all=False,
)

The False matters. Many CRM models call register_model_for_feature(…, all=True), and without this gate, every one of them would become configurable. A model opts in from its own app’s registration.py:

from horilla.registry.feature import register_model_for_feature


register_model_for_feature(
    app_label="leads",
    model_name="Lead",
    features=["custom_fields_models"],
)

In this codebase, Leads, Accounts, Contacts, Campaigns and Opportunities opt in. The field_management app never imports any of them. It reads FEATURE_REGISTRY[“custom_fields_models”] at compose time and registers its extensions for whatever it finds.

The hook-and-extension pattern

Core Horilla code exposes small, generic hooks, such as setup_form_extension_fields, get_group_field and get_virtual_fields. The hook names carry no custom-field wording, so any app could use them for fields that aren’t columns. field_management overrides them with extensions built on Horilla’s extension framework (FormExtension, ListExtension, ViewExtension and others). Each extension registers itself at import time through __init_subclass__, and no Horilla class is patched.

Here is how the main surfaces plug in.

SurfaceExtension typeWhat it does
Create and edit formsFormExtensionAdds cf_* form fields
List viewsListExtensionAdds values and columns
Detail view and inline editDetailExtensionShows and edits values
Filters and quick filtersFilterExtension, ListExtensionMakes fields filterable
Kanban, Group By and ChartListExtension, KanbanExtensionLets Single Choice fields group
Reports and dashboardsViewExtension on ReportFieldProviderExposes virtual fields
Conditions (automations, approvals and more)ViewExtension on ConditionFieldProviderEvaluates cf_* conditions
Mail and notification templatesViewExtensionAdds fields to “Insert Fields”

Example 1: forms

Each concrete form needs its own extension, so the app discovers them. It scans each opted-in model’s app for {app}.forms modules, finds HorillaModelForm and HorillaMultiStepForm subclasses whose Meta.model opted in, and registers one FormExtension per form. It does this from a pre-compose hook, because CRM apps opt in during their own ready(), which may run after this app’s.

When the form is built, setup_form_extension_fields adds a widget for each visible cf_* definition. After the instance is saved, the values are written to CustomFieldValue through save_m2m. Hooking there is more reliable than wrapping the view’s form_valid.

The multi-step wizard needs special handling. The wizard auto-assigns unlisted fields to the last step, but only real model fields. A cf_* name raises FieldDoesNotExist and is skipped. So the app appends the cf_* names to step_fields itself. It copies step_fields per instance rather than mutating it, because that dict is class-level and shared across companies and forms.

Example 2: list views

Every list view inherits from HorillaListView, so one registration covers them all:

class CustomFieldListContextExtension(ListExtension):
    _inherit_list = "horilla.contrib.generics.views.list.HorillaListView"


    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        attach_custom_fields_to_list_context(self, context)
        return context

Registering on each concrete list view would force this app to know every list view in advance. Instead, the resolver checks for an exact class match first and then walks each base class in the MRO. A registration on the base class therefore applies to LeadListView, OpportunityListView, and any future list view. If attaching the values fails, the exception is logged and the page still renders.

Example 3: conditions

Automations, approvals, workflows, cadences, duplicate rules, scoring, and forecasting all evaluate conditions on fields. ConditionFieldProvider is the seam. The custom-field extension implements:

  • owns(field_name): returns true for cf_<id>.
  • get_choices(model): returns (“cf_<id>”, label) pairs for the dropdowns.
  • get_value(field_name, instance): returns the stored value as text.
  • build_condition_q(…): builds a Q(pk__in=…) from CustomFieldValue for queryset-based engines.

Rule engines call the generic helpers (evaluate_extension_condition, get_extension_condition_q), so one implementation serves every engine.

Example 4: reports

The report engine supports computed virtual fields built with queryset.annotate(). The extension returns each visible custom field as a VirtualField named cf_<id>, whose annotation is a Subquery on CustomFieldValue. It resolves per request and caches the result on the request. Created, renamed, and deleted fields, company scoping, and field permissions therefore apply immediately in every worker process, and there is no process-wide registry to refresh.

Field permissions

Field permissions (hidden and readonly) apply to custom fields like any other field, keyed by cf_<id>.

  • Hidden: The definition is dropped for that user. The field disappears from forms, detail, list columns, bulk edit, export, quick filters, grouping, reports and dashboards.
  • Readonly: The form field is disabled and not required; bulk edit does not allow it, and inline edit is refused.

Mail templates

The “Insert Fields” modal lists custom fields and inserts a template filter:

{{ instance|extension_field:”cf_1″ }}

The filter asks the condition-field provider for the value. It works wherever a template renders with an instance: mail, notifications, automations, and workflows.

Custom field or model extension?

Use a custom field when an admin needs to add data per company without a deploy. Use a model extension when the field is part of the product, needs constraints or heavy querying, or must be a real column.

The field_management app shows how to add dynamic data to a framework that expects fixed columns. Values live in typed rows. Core exposes generic hooks. One extension per surface fills them in. A feature gate keeps the capability limited to models that opt in. The result is an admin-editable field system with no migrations and no patching of core classes.

Share this article