Google Cloud Storage (GCS) + Django - File Upload, Download, List, and Delete Example
To integrate Google Cloud Storage (GCS) with a Django application for file upload, download, list, and delete operations, follow these steps:
1. Set Up Google Cloud Storage
Create a Google Cloud Project:
- Visit the Google Cloud Console and create a new project or use an existing one.
Enable the Cloud Storage API:
- Navigate to APIs & Services > Library, search for "Cloud Storage," and enable it.
Create a GCS Bucket:
- Go to Storage > Browser in the console.
- Click Create Bucket, choose a globally unique name, configure settings, and create it.
Set Up a Service Account:
- Go to IAM & Admin > Service Accounts, create a service account, and assign the Storage Admin role.
- Generate a key (JSON) for the service account and download it to your local machine.
2. Configure Django for GCS
Install Required Libraries: Install the Google Cloud Storage and Django libraries:
Set Up the Django Storage Backend: Add the
storages
app to your Django project:Configure Django Settings: Add the following configuration in your
settings.py
:Prepare Your Bucket:
- Make your bucket publicly accessible for media files (optional) or set up IAM permissions to allow authenticated access.
3. Django Views for File Operations
Here’s an example of how to implement file upload, list, download, and delete operations:
Upload File
Create a form and view for uploading files:
List Files
Download File
Delete File
4. Django Templates
Upload File Form
upload.html
:
List Files
list_files.html
:
5. URLs
Configure the URLs for the views:
6. Run and Test
- Start your Django development server:
- Navigate to
/upload/
to upload files. - Navigate to
/files/
to list, download, or delete files.
7. Key Points
- Replace
your-bucket-name
andpath/to/your-service-account-key.json
with the correct values. - Ensure proper IAM permissions for file operations (e.g.,
storage.objectAdmin
for the service account). - For production, consider using a private bucket and serve files via signed URLs or a CDN.
This setup integrates Google Cloud Storage with Django, providing a seamless way to manage files in your application.