Back to all posts

Frappe & ERPNext Journey ยท Episode 6

Building a Custom DocType in Frappe: The Mixing Plan, Step by Step

#Frappe#ERPNext#Frappe Framework#DocType#Custom DocType#Child Table#Python#frappe create doctype#frappe custom doctype tutorial#frappe child table#frappe naming series#frappe developer mode#bench new-app#frappe fetch_from#frappe submittable doctype#frappe doctype json#erpnext customization#erpnext textile
Building a Custom DocType in Frappe: The Mixing Plan, Step by Step
November 20, 20268 min read

In a spinning mill, nobody spins yarn from a single type of cotton. The blowroom mixes several cotton lots in exact ratios, say 50% Brazilian, 30% American, 20% local, to hit a target yarn strength at the lowest cost. That recipe is the Mixing Plan, and getting it wrong wastes tonnes of cotton.

ERPNext has nothing like it. So I built it: a brand-new DocType, from scratch, inside our own app. This episode walks through exactly how, and what Frappe does for you behind the scenes when you click Save on a new DocType.

The Mixing Plan form: a parent DocType with a child table of cotton lots

Keywords

  • DocType: Frappe's core building block. One DocType = a database table + a form + list view + permissions + logic.
  • App: The Python package your DocTypes live in (mill_erp).
  • Module: A folder inside the app that groups DocTypes (Mill Production).
  • Developer mode: The setting that makes Frappe write DocTypes to files you can commit.
  • Child DocType: A DocType marked Is Child Table. Its rows live inside a parent document.
  • Submittable: A DocType with Draft โ†’ Submitted โ†’ Cancelled states (docstatus 0/1/2).
  • Naming rule: How each new document gets its name (its primary key).
  • fetch_from: Copies a value from a linked document automatically.

Character Mapping

  • DocType: A printed form template in the mill office.
  • Fields: The boxes on that form.
  • Child table: The ruled lines at the bottom of the form, one line per cotton lot.
  • Naming rule: The serial-number stamp on each new form.
  • Developer mode: Saving the template to the master file, not just the photocopier.

1. Set Up: An App and Developer Mode

Step 1: Create your app and install it on the site

bash
cd ~/frappe/frappe-bench
bench new-app mill_erp
bench --site mill.localhost install-app mill_erp

Step 2: Turn on developer mode (from Episode 4: per site, or bench-wide with -g)

bash
bench --site mill.localhost set-config developer_mode 1
bench restart   # or stop and re-run bench start

Without developer mode, Frappe saves your DocType only in the database. It works, but there's no file to commit, review or deploy. With developer mode on, every save writes the DocType's JSON into your app.

โš ๏ธ When creating the DocType, make sure "Custom?" is unchecked. A Custom DocType lives only in the database (handy for quick, site-only forms). A standard DocType belongs to a module in your app and gets real files.


2. Design the Child Table First: "Mixing Plan Item"

Search "New DocType" in the desk. Set Module = Mill Production, tick Is Child Table, and add fields:

FieldTypeNotes
cotton_lotLink โ†’ Batcheach cotton lot is a Batch (more in Episode 7)
blend_percentagePercentrequired
micronaireFloatFetch From cotton_lot.micronaire, read only
staple_lengthFloatFetch From cotton_lot.staple_length, read only
allocated_weight_kgFloatread only, calculated by the controller

fetch_from is a small superpower: when the user picks a lot, Frappe copies that lot's micronaire into the row automatically, with no JavaScript needed. (micronaire and staple_length are custom fields we added to Batch.)


3. Design the Parent: "Mixing Plan"

New DocType again, Module = Mill Production, and this time tick Is Submittable and Track Changes.

FieldTypeNotes
naming_seriesSelectoptions: MP-.YYYY.-
companyLink โ†’ Company
mixing_dateDatedefault: Today
target_yarnLink โ†’ Iteme.g. 30s Combed
blowroom_lineSelectLine 1 / Line 2 / Line 3
total_mixing_weight_kgFloatrequired
cotton_itemsTable โ†’ Mixing Plan Itemthe child table
predicted_micronaireFloatread only

Choosing a Naming Rule

Frappe offers several naming options: set by user, autoincrement, by fieldname (field:), by naming series, an expression like MP-.YYYY.-.#####, random, UUID, or by script (an autoname method in the controller).

We used an expression, so documents get names like MP-2026-00042: a readable prefix, the year, and a counter. Avoid the old brace style (MP-{YYYY}-{#####}): the docs mark it as deprecated.


4. What Frappe Creates When You Click Save

Files written to your app, and tables created in the site database

Files in your app

text
mill_erp/mill_erp/mill_production/doctype/
โ”œโ”€โ”€ mixing_plan/
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ mixing_plan.json       # the schema: every field and setting
โ”‚   โ”œโ”€โ”€ mixing_plan.py         # server-side controller
โ”‚   โ”œโ”€โ”€ mixing_plan.js         # client-side form script
โ”‚   โ””โ”€โ”€ test_mixing_plan.py    # test boilerplate
โ””โ”€โ”€ mixing_plan_item/
    โ”œโ”€โ”€ mixing_plan_item.json
    โ””โ”€โ”€ mixing_plan_item.py

Commit all of these. The .json is the source of truth. On another site, bench migrate reads it and creates or updates the tables.

Tables in the database

Frappe prefixes table names with tab, so you get `tabMixing Plan` and `tabMixing Plan Item`. Every table automatically gets standard columns: name (the primary key), owner, creation, modified, modified_by, docstatus and idx. This is classic relational design (see System Design Episode 9: SQL vs NoSQL).

How child rows find their parent

parent, parentfield and parenttype link each child row back to its document

Child rows carry three extra columns: parent (the document's name), parenttype (Mixing Plan) and parentfield (cotton_items). idx keeps the row order. Child rows have no permissions of their own: whoever can read the Mixing Plan can read its rows.


5. A First Controller and a Console Test

The generated mixing_plan.py is an empty class. Add the one rule the mill can't live without:

python
# mixing_plan.py
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.utils import flt


class MixingPlan(Document):
    def validate(self):
        total = sum(flt(row.blend_percentage) for row in self.cotton_items)
        if round(total, 2) != 100:
            frappe.throw(_("Blend must total exactly 100%. Current total: {0}%").format(total))

        weighted_mic = 0
        for row in self.cotton_items:
            row.allocated_weight_kg = flt(self.total_mixing_weight_kg) * flt(row.blend_percentage) / 100
            weighted_mic += flt(row.micronaire) * flt(row.blend_percentage) / 100
        self.predicted_micronaire = round(weighted_mic, 2)

Then try it from bench --site mill.localhost console:

python
mp = frappe.new_doc("Mixing Plan")
mp.company = "Spinning Mill Ltd"
mp.mixing_date = frappe.utils.today()
mp.total_mixing_weight_kg = 5000
mp.append("cotton_items", {"cotton_lot": "LOT-BR-0007", "blend_percentage": 50})
mp.append("cotton_items", {"cotton_lot": "LOT-US-0012", "blend_percentage": 30})
mp.append("cotton_items", {"cotton_lot": "LOT-BD-0031", "blend_percentage": 20})
mp.insert()          # runs validate โ†’ allocates kg, predicts micronaire
mp.submit()          # docstatus 0 โ†’ 1
frappe.db.commit()   # the console doesn't auto-commit
print(mp.name, mp.predicted_micronaire)

self.cotton_items is just a list of row objects, and append() adds one. Episode 8 goes much deeper into validate, on_submit, on_cancel and the rest of the document lifecycle.


Field Types You'll Use Most

TypeUse it forMill example
DataShort textLot code from the supplier
LinkPointer to another DocTypecotton_lot โ†’ Batch
SelectFixed optionsBlowroom Line 1/2/3
Float / Currency / PercentNumbersWeight, rate, blend %
Date / DatetimeDatesMixing date
TableChild rowsCotton items
CheckYes/no"Recycled waste included"
Section / Column / Tab BreakLayout only, no column in the DBGrouping the form

๐Ÿ• Explain It Like You're 5

Your teacher gives you a blank worksheet with boxes: "Name", "Date", and a table at the bottom with lines for each crayon you used.

Making a DocType is like designing that worksheet. Once it's designed, everyone can fill in their own copy, and each copy gets a number stamped on top so nobody's mixes up.

The lines at the bottom are the child table, and the stamp is the naming rule!


๐ŸŽฏ Debugging Cheat Sheet

SymptomLikely causeFix
No files appeared in my appDeveloper mode off, or "Custom?" tickedTurn on developer mode; untick Custom; save again
DocType works locally, missing on stagingJSON not committed, or no migrateCommit the folder; run bench --site <site> migrate
My form changes vanished after deployEdited on a server without developer modeAlways edit in dev, commit, deploy
Child DocType shows up in the search bar"Is Child Table" not tickedTick it (child tables aren't standalone)
fetch_from field stays emptySource field name typo, or Link not setCheck cotton_lot.micronaire exists on Batch
Name stays new-mixing-plan-1Document not saved yetNames are assigned on insert
Console changes disappearNo commit in consolefrappe.db.commit()

Key Takeaways for Interviews

  1. A DocType is schema + UI + permissions + logic in one JSON file, and Frappe builds the table from it.
  2. Developer mode + a standard (non-Custom) DocType gives you files you can commit and deploy with bench migrate.
  3. Child tables link back with parent, parenttype, parentfield and keep order with idx, sharing the parent's permissions.
  4. Pick naming deliberately: an expression like MP-.YYYY.-.##### is readable and sortable.
  5. Use fetch_from and controllers to keep data correct at entry time, not in a report later.

๐Ÿ“š Official Sources

Everything here is checked against Frappe's own documentation:

Next episode, back to ERPNext modules: Buying and Stock, where cotton bales arrive as Batches, pass a Quality Inspection, and get valued with FIFO or Moving Average.

Enjoyed this article? Share it: