Can we run an python script before a file is deleted? [SOLVED]

Hi,
I am looking for controlling file deletion for specific doctype.
Therefore, I am thinking of running a python script before a file gets deleted?

Just wanted to know, how to achieve it via hooks or some other way around?

Regards
Ruchin Sharna

1 Like

Hi @ruchin78,
Do you want to control the file deletion of uploaded file?
FIY, for managing the files on the server there is a specific doctype as File. You can also have look on file_manger.py for more insights.

hook on_trash method.

1 Like

Hi @saurabh6790

I hope, on_trash will run once the gets deleted but I want to run something before the file gets deleted.

Regards
Ruchin Sharma

1 Like

when you hook a method, in execution system first executes hooked custom method then calls its own methods.

In your case system first, executes you code hooked via the on_trash method and then executes on_trash code from a file.py

@saurabh6790

Thanks for the clarification, it made my life more easier.

Regards
Ruchin Sharma

@saurabh6790
Don’t know but I just tried with a single

frappe.message 

and I noticed that, message appread after the file got deleted from the document.

Regards
Ruchin Sharma

on_trash is still what you should hook to if you are after document deletion and not file deletion.
Change the frappe.message to frappe.throw and that will show you the message and stop the doc from being deleted. That should give you the confirmation you are after :slight_smile:

@azzadeen
I actually want to stop the user before the file gets deleted (which is already attached with a document).

Regards
Ruchin Sharma

@azzadeen @saurabh6790 @ManasSolanki

Many thanks for your inputs, I am able to do this now.

Here is my code

def check_doc_status(doc, method=None):
	if doc.attached_to_doctype == "Item":
		doc_m = frappe.get_doc("Item", doc.attached_to_name)
		if doc_m.workflow_state == "Approved":
			frappe.throw("You cannot delete this document/file since the item is in Approved State")

Regards
Ruchin Sharma

2 Likes