When working on a large Django application, forms can become repetitive very quickly. Many forms need the same things: excluding system fields, configuring widgets, handling foreign keys, applying permissions, and making sure submitted values are actually allowed for the current user.
If every developer handles these things separately, the same logic ends up being repeated across many forms.
Horilla CRM takes a different approach with HorillaModelForm. It provides a common base for model forms and handles many of these requirements automatically.
This makes individual forms smaller, more consistent, and easier to maintain.
Why Not Just Use Django’s ModelForm?
Django’s ModelForm is already powerful. It can generate fields from a model and take care of standard validation and saving.
But a CRM usually needs more than that.
For example, many Horilla forms need to deal with fields such as:
- company
- created_by
- updated_by
- created_at
- updated_at
- is_active
These are internal fields and normally shouldn’t be edited by users.
There are also other common requirements. Foreign keys may contain thousands of records, so loading everything into a normal HTML dropdown isn’t practical. Users may also have different permissions for different records, which means simply hiding an option in the browser isn’t enough.
If every form implements these requirements separately, the code quickly becomes repetitive.
HorillaModelForm brings this common behavior into one place.
Where HorillaModelForm Comes From
You can import it from Horilla’s generic forms package:
from horilla.contrib.generics.forms import HorillaModelForm
The base form is built using two main components.
HorillaFormMixin contains the common form functionality, while HorillaModelForm combines that mixin with Django‘s ModelForm.
At its core, it looks like this:
class HorillaModelForm(HorillaFormMixin, forms.ModelForm):
“””Base model form class with enhanced field configuration and validation.”””
This means forms that inherit from HorillaModelForm automatically get the common behavior provided by the mixin.
System Fields Don’t Need to Be Repeatedly Excluded
One of the first things you notice when working with Horilla forms is that common system fields don’t have to be excluded manually in every form.
Fields such as company, created_at, updated_at, created_by, updated_by, and additional_info are normally managed internally by the application.
HorillaFormMixin handles their exclusion when a form class is created.
It uses __init_subclass__ to update the form’s Meta configuration:
class HorillaFormMixin:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
meta = cls.__dict__.get("Meta")
if meta is None:
return
apply_horilla_form_meta_exclude(meta)
So when you create a new form, you don’t need to keep writing the same list of system fields.
There are also ways to customize this behavior when a particular form needs something different.
Meta.keep_on_form can be used when a normally excluded field needs to be shown, while Meta.exclude can be used to add additional fields to the exclusion list.
Many Forms Can Stay Very Small
Because the base class handles so much of the common setup, a simple form can contain little more than its model and fields.
For example:
class FieldRequirementForm(HorillaModelForm):
class Meta:
model = FieldRequirement
fields = ["content_type", "field_name", "is_required"]
That’s enough for a basic create/edit form.
There’s no need to manually configure the common widgets or repeat the standard system-field exclusions.
This is particularly useful in a large CRM where many models need similar forms.
Foreign Keys Get Searchable Dropdowns
A normal Django ModelForm generally renders a ForeignKey as a regular HTML select field.
That can become a problem when the related model contains thousands of records.
Imagine a CRM with 20,000 contacts. Loading all of those contacts into a dropdown every time a form opens isn’t a good user experience.
HorillaModelForm handles this by configuring ForeignKey and ManyToMany fields with Horilla’s Select2-based widgets.
The form initialization checks the fields and applies the appropriate configuration:
def __init__(self, *args, **kwargs):
self._pop_form_options(kwargs)
super().__init__(*args, **kwargs)
...
The resulting widget can use server-side searching and pagination through the generics:model_select2 endpoint.
It also carries information such as the data URL and initial values needed by the Select2 component.
Instead of loading every related record at once, users can search for the record they need.
Date and Time Fields Are Handled Too
The same idea is applied to date and time fields.
Instead of leaving them as ordinary text inputs, Horilla can configure them as appropriate HTML5 inputs such as:
date
datetime-local
time
The corresponding input formats are also configured so the values submitted by the browser are handled correctly.
This keeps date and time fields consistent across different forms in the application.
Permission Checks Don’t Stop at the Browser
Permissions are especially important in a CRM.
Suppose a user can edit a form but doesn’t have permission to modify a particular field. The UI can hide or disable that field, but that alone isn’t enough.
A user can open browser developer tools and modify the request before submitting it.
That’s why HorillaModelForm handles permissions at both the UI and server levels.
A form can receive field permissions like this:
form = LeadSingleForm(
field_permissions=field_permissions,
request=request,
)
Fields marked as hidden can be removed from the form, while readonly fields can be displayed without allowing normal editing.
But the important part happens during validation.
Readonly Fields Are Checked Again During Validation
HorillaModelForm doesn’t simply trust what was displayed in the browser.
During clean(), readonly fields can be compared against their original database values. If someone has modified a readonly value in the submitted request, the form can reject it.
This provides an important second layer of protection.
The same idea applies to relationship fields.
For example, suppose a user can assign a lead to certain employees. Even if the browser only displays those employees, someone could manually submit another employee’s ID.
Horilla can re-check ForeignKey, ManyToMany, and choice fields against a fresh queryset based on the current user’s permissions.
So the server doesn’t simply trust the values that were originally rendered in the form.
Creating Your Own Form
Creating a custom Horilla form is still straightforward.
You inherit from HorillaModelForm, define the model and fields, and then add any behavior specific to your form.
For example:
class LeadStatusForm(HorillaModelForm):
field_order = ["name", "probability", "order", "is_final"]
class Meta:
model = LeadStatus
fields = "__all__"
exclude = ["color"]
If the form needs some HTMX behavior, you can add it without losing any of the functionality provided by the base class.
For example:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if "is_final" in self.fields:
self.fields["is_final"].widget.attrs.update({
"hx-post": reverse_lazy("leads:toggle_order_field"),
"hx-target": "#order_container",
"hx-swap": "outerHTML",
"hx-trigger": "change",
})
Here, the custom code only handles the behavior that is specific to LeadStatusForm.
The standard Horilla functionality continues to come from HorillaModelForm.
A Few More Features Built In
HorillaModelForm also includes several smaller features that are useful when building CRM forms.
Phone Fields
Horilla can detect commonly used phone field names such as phone, mobile, and contact_number and configure them using its phone field handling.
The behavior can also be customized through the phone_fields attribute.
Time Zone Defaults
If a form contains a time_zone field, Horilla can use the requesting user’s or company’s configured timezone instead of always falling back to UTC.
File Handling with HTMX
File uploads can be tricky when a form is re-rendered as an HTMX partial after validation.
Horilla keeps track of uploaded, existing, and cleared file states so that information isn’t unnecessarily lost when the form is rendered again.
Fieldsets
Forms can use get_fieldsets() to organize fields for the template.
This also makes it easier for extension apps to add fields to existing field groups without having to modify the underlying HTML template.
Conditional Fields
Forms can also support condition-based interfaces using options such as:
condition_fields
condition_model
This is useful for features that need rule-builder-style conditions alongside the normal model fields.
Why This Approach Helps
The biggest advantage of HorillaModelForm isn’t one particular feature.
It’s the consistency it brings to the application.
Without a shared base form, every developer has to remember to configure widgets, exclude system fields, validate permissions, handle date fields, and deal with related objects.
With HorillaModelForm, those common requirements are handled centrally.
A developer can focus on the behavior that is unique to the feature instead of rewriting the same form infrastructure.
That becomes especially valuable as a CRM grows and the number of models and forms increases.
HorillaModelForm builds on Django’s ModelForm and adds the functionality that is commonly needed in a CRM application.
It takes care of things like system-field exclusions, searchable relationship fields, date and time inputs, field-level permissions, server-side validation, file handling, and field organization.
For a simple form, the implementation can be very small. When a form needs custom behavior, you can still extend it normally without losing the features provided by the base class.
For developers working on Horilla CRM, starting with HorillaModelForm instead of Django’s plain ModelForm helps keep forms consistent while reducing repeated code across the application.