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

Custom Frappe App for ERPNext: DocTypes, Hooks and Safe Upgrades (cover)
On this page

When ERPNext doesn't do what your business needs, you have three options:

  1. Customise it in the UI (Customize Form, Custom Fields, Client Scripts, Server Scripts).
  2. Put your changes in a custom Frappe app.
  3. 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:

Bash
cd ~/frappe-bench
bench new-app kv_custom
bench --site dev.localhost install-app kv_custom

bench 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.

Bash
bench --site dev.localhost set-config developer_mode 1
bench --site dev.localhost clear-cache

Never enable developer mode on production.

The generated app looks roughly like this. Details vary between Frappe versions:

Plain text
apps/kv_custom/
  pyproject.toml
  kv_custom/
    __init__.py
    hooks.py
    modules.txt
    patches.txt
    config/
    public/
    templates/
    kv_custom/        <- the default module folder

Recent 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:

Plain text
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.py

If 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:

Python
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:

Python
# 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:

Python
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:

Python
# 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:

Bash
bench --site dev.localhost export-fixtures --app kv_custom

Fixtures 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:

Bash
bench set-config -g server_script_enabled 1

A typical Server Script (type: DocType Event, Before Save, on Sales Invoice):

Python
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 + bench migrate

Imports and libraries

Not allowed

Anything you install

Tests

None built in

bench run-tests

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.

  1. Never edit apps/frappe or apps/erpnext. Local changes either block bench update or 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.
  2. Add, don't replace. Prefer doc_events, Custom Fields and doctype_js over class overrides and overridden whitelisted methods. The less upstream code you replace, the less can break.
  3. Prefix your fieldnames. Use a prefix like kv_ for fields you create in code. Recent Frappe versions add a custom_ prefix to fields created through Customize Form. Prefixes stop your fields from colliding with fields ERPNext adds later.
  4. Change data with patches, not by hand. Add a module to patches.txt and Frappe runs it once per site during bench migrate:
INI / config
[pre_model_sync]

[post_model_sync]
kv_custom.patches.v1_0.backfill_inspection_status
Python
# 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.

  1. 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 your version-14 branch against ERPNext 15 and hope for the best.
  2. Write tests for the logic that matters. Enable tests on a dedicated test site and run them before every upgrade:
Bash
bench --site test.localhost set-config allow_tests true
bench --site test.localhost run-tests --app kv_custom
  1. Rehearse upgrades on staging. Restore a recent production backup to a staging site, run bench update, run bench migrate, run your tests, then click through your key flows: create, submit and cancel the documents your app touches.
  2. 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:

Bash
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 restart

Later 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.

Share this article

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

Your rating (optional)
Not rated

Comments appear after an editor approves them. See our privacy notice.

Read next

ERPNext Bank Reconciliation: Import, Match and Clear Transactions (cover)Technical
Kalvyai EngineeringERPNext

ERPNext Bank Reconciliation: Import, Match and Clear Transactions

A practical guide to bank reconciliation in ERPNext: setting up bank accounts, importing statements, matching Payment Entries and Journal Entries in the Bank Reconciliation Tool, and dealing with transactions that don't match.

8 min read

Newsletter

Get new guides in your inbox.

Practical notes on Odoo, ERPNext, Shopify and AI agents, written by the engineers who build them. No spam, and you can ask to stop at any time.

Prefer a feed? Subscribe by RSS. We use your email only to send new articles. See our privacy policy.