def get_sorted_fields(doctype, custom_fields):
 fields_dict = frappe.get_meta(doctype).get(u'fields')
 standard_fields_count = frappe.db.sql(u'select count(name) from `tabDocField`\n DCTB  DCTB where parent=%s', doctype)[0][0]
 newlist = []
 pending = [d.fieldname for d in fields_dict]
 maxloops = (len(custom_fields) + 20)
 while (pending and (maxloops > 0)):
  maxloops -= 1
  for fieldname in pending[:]:
   if ((fieldname in custom_fields) and (len(newlist) >= standard_fields_count)):
    for n in newlist:
     if (n == custom_fields.get(fieldname)):
      newlist.insert((newlist.index(n) + 1), fieldname)
      pending.remove(fieldname)
      break
   else:
    newlist.append(fieldname)
    pending.remove(fieldname)
 if pending:
  newlist += pending
 return newlist

def get_sorted_fields ( doctype , custom_fields ) : fields_dict = frappe . get_meta ( doctype ) . get ( u'fields' ) standard_fields_count = frappe . db . sql ( u'select count(name) from `tabDocField`\n DCTB  DCTB where parent=%s' , doctype ) [ 0 ] [ 0 ] newlist = [ ] pending = [ d . fieldname for d in fields_dict ] maxloops = ( len ( custom_fields ) + 20 ) while ( pending and ( maxloops > 0 ) ) : maxloops -= 1 for fieldname in pending [ : ] : if ( ( fieldname in custom_fields ) and ( len ( newlist ) >= standard_fields_count ) ) : for n in newlist : if ( n == custom_fields . get ( fieldname ) ) : newlist . insert ( ( newlist . index ( n ) + 1 ) , fieldname ) pending . remove ( fieldname ) break else : newlist . append ( fieldname ) pending . remove ( fieldname ) if pending : newlist += pending return newlist
sort on basis of insert_after .