Attach Image on Save

Good day everyone! I am working on generating barcode for Sales Order using PyBarcode library in Python. It was creating correct image but is stuck in auto attaching it and showing it in print. Can anybody help on how to auto attach image on save with correct file path? Thank you very much.

This is what I have done so far but returning an error : “Server Error: Please check your server logs or contact tech support.”

import frappe
import barcode
from barcode.writer import ImageWriter


def on_save(doc, method):
    # create barcode for docname
    barcode_class = barcode.get_barcode_class('code39')
    ean = barcode_class(doc.name, ImageWriter(), add_checksum=False)
    barcode_path = frappe.get_site_path()+'/public/files/'
    ean.save(barcode_path+doc.name+'.png')
    save_image(frappe.get_site_path(),doc.name + '.png')
    img_path = "/files/" + doc.name + ".png"
    frappe.db.sql("""Update `tabSales Order` set barcode_image = %s
        where name = %s""", (img_path, doc.name))
    frappe.db.commit()

def save_image(path, name):
    # save barcode image to file table
    attach_image = frappe.get_doc({
        "doctype": "File",
        "file_name": name,
        "file_url": path + name,
    })
    attach_image.insert()

Could you paste the error message you are getting from your /frappe-bench/logs directory?

Hello @Pawan. Thanks for you reply. I have already checked and it shows I needed to fill in a field in File doctype. I did and it went through. Thanks a lot for your help.