How to add/remove column(field) to doctype in codes?

I created an App, and I want to modify ERPNext’s fields of doctypes after installing the App. So how to add or remove field in codes?

You have directly remove fields from Customise Form by using hide option and also add from their by using Add new row.
Go to Customise Form-> select perticular doctype , open field hide option will be their.

yeah, I know how to operate on that, I wanna know how to code…

OK I found this works.

def add_field(*, doctype, field_label, field_name, field_type, options=None, default=None):
    dt = frappe.get_doc('DocType', doctype)
    df = frappe.new_doc('DocField')

    df.label = field_label
    df.fieldname = field_name
    df.fieldtype = field_type
    df.parent = doctype
    df.parentfield = 'fields'
    df.parenttype = 'DocType'
    df.parent_doc = dt

    if options:
        df.options = options
    if default:
        df.default = default

even though I dont know if it’s the right way to do that.

@nnylyj always add Custom Field instead of DocField, unless they are permanent.

Where should I place this code?

What do you mean? You already created your doctype?
You should:
1)create doctype in your application,
2) Find the doctype/<your_doctypes_name>/<your_doctypes_name>.json file and after that you understood, that you should do :slight_smile:

If it will be so hard for you you can also use UI for creating custom fields:
If you already use existable doctype you should find this doctype there and press on Menu >`Customize’> After that you will understand, that you should do

Yeah, I want to add field to erpnext existing form like Stock > Item form through code.

Maybe you do not understand my question.

@nnylyj, You can refer below link