Technical
Custom Frappe App for ERPNext: DocTypes, Hooks and Safe Upgrades
A practical guide to building a custom Frappe app for ERPNext: bench new-app, DocTypes, hooks.py, when to use Server Scripts instead of Python, and how to keep your customisations working after every upgrade.
Kalvyai Engineering · · Updated · 6 min read

On this page
When ERPNext doesn't do what your business needs, you have three options:
- Customise it in the UI (Customize Form, Custom Fields, Client Scripts, Server Scripts).
- Put your changes in a custom Frappe app.
- Edit the ERPNext or Frappe source directly.
The third option works until the next bench update. Then your changes conflict with upstream code, and someone has to re-apply them by hand. This post covers the second option: how to build a custom app, where each kind of change belongs, and how to keep it working across upgrades.
When a custom app is the right choice
UI customisation is fine for a few extra fields or a simple validation. Move to a custom app when:
- You need new DocTypes with real business logic.
- You have more than a handful of Server Scripts and nobody remembers what they all do.
- You run more than one site (staging, production, other companies) and need the same changes on all of them.
- You want code review, version history and automated tests.
- You integrate with an outside system: a payment gateway, a shop or an API.
A custom app is a Python package that sits next to frappe and erpnext in your bench. It goes in git, you install it per site, and it upgrades on its own schedule.
Step 1: Create the app with bench new-app
From your bench directory on a development machine:
cd ~/frappe-bench
bench new-app kv_custom
bench --site dev.localhost install-app kv_custombench new-app asks for a title, description, publisher, email and licence. The exact prompts depend on your bench version. Pick an app name with a short prefix (here kv_) so it is unlikely to clash with another app's module or DocType names.
Next, turn on developer mode for the development site. Without it, the DocTypes you create are not written to files in your app.
bench --site dev.localhost set-config developer_mode 1
bench --site dev.localhost clear-cacheNever enable developer mode on production.
The generated app looks roughly like this. Details vary between Frappe versions:
apps/kv_custom/
pyproject.toml
kv_custom/
__init__.py
hooks.py
modules.txt
patches.txt
config/
public/
templates/
kv_custom/ <- the default module folderRecent bench versions create a git repository for you. If yours didn't, run git init in apps/kv_custom and push to your own remote before you write any real code.
Step 2: Build your DocTypes
Create a new DocType from the Desk as usual, with two settings that matter:
- Module: set it to your app's module (for example
KV Custom). - Custom: leave it unchecked.
With developer mode on and Custom unchecked, Frappe writes the DocType to your app folder as files:
kv_custom/kv_custom/doctype/equipment_inspection/
equipment_inspection.json <- fields, permissions, settings
equipment_inspection.py <- server-side controller
equipment_inspection.js <- form script
test_equipment_inspection.pyIf you tick Custom, the DocType lives only in that site's database. It won't be in git and won't reach your other sites. That is the most common reason a customisation "disappears" after a site migration.
Writing the controller
The .py file holds a class that extends Document. Override the lifecycle methods you need:
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.utils import getdate
class EquipmentInspection(Document):
def validate(self):
if self.next_due_date and self.inspection_date:
if getdate(self.next_due_date) <= getdate(self.inspection_date):
frappe.throw(_("Next due date must be after the inspection date."))
def on_submit(self):
frappe.db.set_value("Asset", self.asset, "kv_last_inspection", self.name)Common methods are validate, before_insert, after_insert, before_save, on_update, on_submit, on_cancel and on_trash. Use getdate when comparing dates, because field values can arrive as strings.
Adding fields to ERPNext's own DocTypes
You can't edit Sales Invoice.json in ERPNext. You add Custom Fields instead, and ship them with your app in one of two ways.
Option A: fixtures. Create the fields in the UI, set their Module to your app, then export them (see the hooks section below).
Option B: create them in code. This is easier to review in a pull request:
# kv_custom/install.py
from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
def after_install():
create_custom_fields({
"Sales Invoice": [
{
"fieldname": "kv_inspection",
"label": "Inspection",
"fieldtype": "Link",
"options": "Equipment Inspection",
"insert_after": "customer",
}
]
})Pick one approach per field and stick to it. Defining the same field both ways makes it hard to tell which definition wins.
Step 3: Wire it up in hooks.py
hooks.py is how your app plugs into Frappe and ERPNext without touching their code. A typical file for a business app:
app_name = "kv_custom"
app_title = "KV Custom"
app_publisher = "Your Company"
app_description = "Inspection tracking for ERPNext"
app_license = "mit"
required_apps = ["erpnext"]
after_install = "kv_custom.install.after_install"
# Run your code on events of other apps' DocTypes
doc_events = {
"Sales Invoice": {
"validate": "kv_custom.events.sales_invoice.validate",
"on_submit": "kv_custom.events.sales_invoice.on_submit",
}
}
# Add form scripts to standard DocTypes
doctype_js = {
"Sales Invoice": "public/js/sales_invoice.js",
}
# Background jobs
scheduler_events = {
"daily": ["kv_custom.tasks.flag_overdue_inspections"],
}
# Records exported with the app and synced on migrate
fixtures = [
{"dt": "Custom Field", "filters": [["module", "=", "KV Custom"]]},
{"dt": "Property Setter", "filters": [["module", "=", "KV Custom"]]},
]A doc_events handler receives the document and the event name:
# kv_custom/events/sales_invoice.py
import frappe
from frappe import _
def validate(doc, method=None):
if doc.kv_inspection:
status = frappe.db.get_value("Equipment Inspection", doc.kv_inspection, "docstatus")
if status != 1:
frappe.throw(_("Linked inspection must be submitted first."))Export fixtures from your development site with:
bench --site dev.localhost export-fixtures --app kv_customFixtures are synced into each site when you run bench migrate. Scheduled jobs only run if the scheduler is enabled on that site (bench --site <site> enable-scheduler).
doc_events vs override_doctype_class
override_doctype_class lets you replace a standard DocType's controller with your own subclass. It is powerful, but only one app can override a given class cleanly, and your subclass breaks if upstream renames or changes a method you override. Use doc_events whenever you are adding behaviour. Use overrides only when you really have to change existing behaviour, and call super() so the original logic still runs.
Server Scripts vs Python in your app
Server Scripts are written in the Desk and stored in the database. They run in a restricted Python environment: no imports, and only a whitelisted set of frappe functions. On recent versions they are disabled until you run:
bench set-config -g server_script_enabled 1A typical Server Script (type: DocType Event, Before Save, on Sales Invoice):
if doc.additional_discount_percentage and doc.additional_discount_percentage > 15:
frappe.throw("Discounts above 15% need manager approval.")Here's how the two compare:
| Server Script | Python in a custom app |
|---|---|---|
Where it lives | Site database | Git repository |
Deploy | Edit in the Desk | Code deploy + |
Imports and libraries | Not allowed | Anything you install |
Tests | None built in | |
Code review | Hard | Normal pull requests |
Works on every site | Only if copied or exported | Yes, once installed |
Our rule of thumb:
- Server Script: a short validation or a small API endpoint, owned by an admin, on one site, when you can't deploy code quickly. Write down what each script does and why it exists.
- Custom app: anything with business rules that matter, anything touching money or stock, any integration, and anything you'd want tested.
When a Server Script grows past a screen of code or starts needing helper functions, move it into the app.
Keeping customisations upgrade-safe
Most upgrade pain comes from a few avoidable habits. These are the rules we follow.
- Never edit
apps/frappeorapps/erpnext. Local changes either blockbench updateor get lost when someone resets the repo. If you need a core fix, contribute it upstream and carry a workaround in your app until it is merged. - Add, don't replace. Prefer
doc_events, Custom Fields anddoctype_jsover class overrides and overridden whitelisted methods. The less upstream code you replace, the less can break. - Prefix your fieldnames. Use a prefix like
kv_for fields you create in code. Recent Frappe versions add acustom_prefix to fields created through Customize Form. Prefixes stop your fields from colliding with fields ERPNext adds later. - Change data with patches, not by hand. Add a module to
patches.txtand Frappe runs it once per site duringbench migrate:
[pre_model_sync]
[post_model_sync]
kv_custom.patches.v1_0.backfill_inspection_status# kv_custom/patches/v1_0/backfill_inspection_status.py
import frappe
def execute():
frappe.db.sql("""
UPDATE `tabEquipment Inspection`
SET status = 'Passed'
WHERE status IS NULL AND docstatus = 1
""")Patches in [post_model_sync] run after DocType schema changes are applied, so new columns already exist.
- Match branches to ERPNext versions. Keep a branch of your app per major version (for example
version-15) and install the matching branch. Don't run yourversion-14branch against ERPNext 15 and hope for the best. - Write tests for the logic that matters. Enable tests on a dedicated test site and run them before every upgrade:
bench --site test.localhost set-config allow_tests true
bench --site test.localhost run-tests --app kv_custom- Rehearse upgrades on staging. Restore a recent production backup to a staging site, run
bench update, runbench migrate, run your tests, then click through your key flows: create, submit and cancel the documents your app touches. - Keep an inventory of UI customisations. List every Server Script, Client Script and Property Setter that is not in your app. That list is what breaks silently during upgrades.
Deploying to production
On a self-hosted bench, a first install looks like this:
bench get-app https://github.com/your-org/kv_custom --branch version-15
bench --site erp.example.com install-app kv_custom
bench --site erp.example.com migrate
bench build --app kv_custom
bench restartLater releases are git pull (or bench update), then bench migrate, bench build and bench restart. Take a backup first with bench --site erp.example.com backup. If you use managed hosting, the steps for private apps are different: follow your hosting provider's documentation for deploying private apps.
How Kalvyai can help
We build and maintain custom Frappe apps for ERPNext: new DocTypes, integrations, payment flows and AI agents that run inside ERPNext with human approvals and an audit trail. We can also review an existing site, move scattered Server Scripts and core edits into a proper app, and set up a staging upgrade routine. See our ERPNext services, browse the ERPNext apps we publish at store.kalvyai.com, or contact us to talk through your project.
Last updated 20 Nov 2026
- ERPNext
- Frappe
- Custom App
- hooks.py
- DocTypes
- Server Scripts
- Upgrades
Kalvyai Engineering · Engineering team
The engineers who build, connect and fix business systems at Kalvyai: Odoo, ERPNext, Shopify and AI agents that work inside them with approvals, budgets and an audit trail.



Comments
No comments yet. Questions and corrections are welcome.
Rate this post or leave a comment