#NEWLINE# def delete_file_if_needed( instance , filefield_name ) : #NEWLINE# #INDENT# 'Delete file from database only if needed.\n\n    When editing and the filefield is a new file,\n    deletes the previous file (if any) from the database.\n    Call this function immediately BEFORE saving the instance.\n    ' #NEWLINE# if instance . id : #NEWLINE# #INDENT# model_class = type ( instance ) #NEWLINE# if model_class . objects . filter ( pk = instance . pk ) . exclude ( ** { #NEWLINE# #INDENT# ( '%s__isnull' % filefield_name ) : True , #NEWLINE# #UNINDENT# } ) . exclude ( ** { #NEWLINE# #INDENT# ( '%s__exact' % filefield_name ) : '' , #NEWLINE# #UNINDENT# } ) . exists ( ) : #NEWLINE# #INDENT# old_file = getattr ( model_class . objects . only ( filefield_name ) . get ( pk = instance . id ) , filefield_name ) #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# old_file = None #NEWLINE# #UNINDENT# if old_file : #NEWLINE# #INDENT# if ( ( old_file . name == getattr ( instance , filefield_name ) ) is False ) : #NEWLINE# #INDENT# DatabaseFileStorage ( ) . delete ( old_file . name )