file storage django
Step 1: Import necessary modules
from django.core.files.storage import FileSystemStorage
Step 2: Create a FileSystemStorage instance
fs = FileSystemStorage()
Step 3: Save a file to the storage
filename = fs.save('file.txt', content)
Step 4: Get the URL of the saved file
url = fs.url(filename)
Step 5: Delete a file from the storage
fs.delete('file.txt')
Step 6: Check if a file exists in the storage
exists = fs.exists('file.txt')
Step 7: Open and read a file from the storage
with fs.open('file.txt', 'r') as file:
file_content = file.read()
Step 8: List all files in a specific directory in the storage
files = fs.listdir('path/to/directory')
Step 9: Customize storage location during initialization
custom_fs = FileSystemStorage(location='/path/to/custom/directory')
Step 10: Specify the base URL for file access
custom_fs_with_base_url = FileSystemStorage(base_url='/custom/url/')
Step 11: Use a custom file naming function during saving
def custom_file_naming(instance, filename):
return 'custom_prefix_' + filename
custom_fs_with_naming = FileSystemStorage(
location='/path/to/directory',
file_naming=custom_file_naming
)