'sort on basis of insert_after'

def sort_fields(self):

    custom_fields = sorted(self.get_custom_fields(), key=(lambda df: df.idx))
    if custom_fields:
        newlist = []
        for c in list(custom_fields):
            if (not c.insert_after):
                newlist.append(c)
                custom_fields.pop(custom_fields.index(c))
        newlist += [df for df in self.get(u'fields') if (not df.get(u'is_custom_field'))]
        newlist_fieldnames = [df.fieldname for df in newlist]
        for i in range(2):
            for df in list(custom_fields):
                if (df.insert_after in newlist_fieldnames):
                    cf = custom_fields.pop(custom_fields.index(df))
                    idx = newlist_fieldnames.index(df.insert_after)
                    newlist.insert((idx + 1), cf)
                    newlist_fieldnames.insert((idx + 1), cf.fieldname)
            if (not custom_fields):
                break
        if custom_fields:
            newlist += custom_fields
        for (i, f) in enumerate(newlist):
            f.idx = (i + 1)
        self.fields = newlist
