Integrating Firebase with Django

In the dynamic realm of web development, the appetite for real-time web applications has surged to unprecedented levels. Users now anticipate dynamic and responsive interactions that react instantly to their actions. In pursuit of meeting these heightened expectations, developers frequently seek out solutions tailored to real-time functionality. Firebase emerges as a prominent player in this domain. In this Answer, we embark on a journey to delve into the synergy between Firebase and Django, a Python-based back-end framework.

To harness the Cloud Storage capabilities of Firebase within a Django project, we can seamlessly integrate the two by leveraging the Python library known as Pyrebase. Pyrebase offers a straightforward and user-friendly means of interfacing with Google Firebase services directly from our Python applications.

Let's explore the process of configuring a Django project to work seamlessly with Firebase.

Setting up Firebase

To commence our journey of integrating Firebase with Django, the first essential step is to set up Firebase. Navigate to the Firebase Console and sign in using your Google account credentials.

Once you've successfully logged in, you'll be all set to configure Firebase for your Django project. Follow along with the slides below for detailed guidance.

canvasAnimation-image
1 of 10

Great, now that we have completed the Firebase setup, we can proceed to work on our Django project files.

Configuring Firebase in Django

Configuring Firebase within Django involves a series of steps to seamlessly connect and interact with Firebase services. Here's how you can set up Firebase in your Django project:

  1. Install Pyrebase: Begin by installing the Pyrebase library using pip3. Open your terminal or command prompt and execute the following command:

pip3 install pyrebase
Shell command to install Pyrebase
  1. Import Pyrebase in views.py: Navigate to the main folder of your Django project and open the views.py file. Import the Pyrebase library at the top of the file with the following statement:

import pyrebase
Importing Pyrebase in views.py
  1. Create a Firebase configuration object: Define a configuration object (config) that contains the necessary settings to establish a connection with Firebase. Replace the placeholders ("XXXXXXXXXXXXXXXXXXXX") with your actual Firebase project configurations, which you should have saved earlier during the Firebase setup:

config = {
"apiKey": "XXXXXXXXXXXXXXXXXXXX",
"authDomain": "XXXXXXXXXXXXXXXXXXXX",
"projectId": "XXXXXXXXXXXXXXXXXXXX",
"storageBucket": "XXXXXXXXXXXXXXXXXXXX",
"messagingSenderId": "XXXXXXXXXXXXXXXXXXXX",
"appId": "XXXXXXXXXXXXXXXXXXXX",
"databaseURL":""
}
Object to specify configurations for Firebase
  1. Initialize Firebase: Create an instance of Firebase within your application using Pyrebase:

firebase = pyrebase.initialize_app(config)
storage = firebase.storage()
Establish connection with Firebase resources
  • firebase stores a connection to Firebase services, with Pyrebase handling the required configurations.

  • storage holds an instance of Firebase storage, which you will use to manage data storage.

  1. Upload data: To upload data to Firebase storage, you can use the following command:

storage.child(destination_path).put(local_file_path)
Command to put data in our Firebase storage
  • destination_path refers to the storage path where you want to store your data.

  • local_file_path is the path to the file you wish to upload to Firebase storage.

  1. Fetch data: To retrieve data from Firebase storage, use the following command:

file_url = storage.child(file_path).get_url(None)
Fetch data from Firebase storage
  • storage.child(file_path) creates a reference to a specific file in Firebase Cloud Storage.

  • get_url(None) retrieves the URL of the specified file. The None parameter signifies that no authentication token is needed for access. Firebase allows setting security rules for storage, and if they allow public access, an authentication token isn't required.

These steps set the stage for integrating Firebase storage with your Django project. You can now seamlessly manage data upload and retrieval using Firebase's robust Cloud Storage capabilities within your Django application.

A hands-on application

Now, let's put our Firebase and Django integration into practice by using a hands-on application. In this example, we have a Django application that allows users to upload files to Firebase Cloud Storage. Here's how the frontend of this application will look like:

Layout of the application
Layout of the application

Here's how the application works:

  1. Users land on a home page where they encounter a "Choose file" button.

  2. When the user clicks the "Choose file" button, they can select a file from their local desktop.

  3. After selecting a file, the name of the chosen file will be displayed in a field labeled "No file chosen."

  4. To initiate the upload process, the user simply clicks the "Submit" button.

Ensure that you have configured your Firebase storage settings in the views.py file, which can be found in the "main" folder.

Note: To access and use the running application, click the link provided after the text "Your app can be found at:".

"""
Django settings for dj_firebase project.

Generated by 'django-admin startproject' using Django 3.1.5.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""

from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '!lkxhb+59!5e9+@hrz(l72hob9o6%prq61)h0=6#439y*bcbd7'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['{{EDUCATIVE_LIVE_VM_URL}}'.replace('https://',''), '0.0.0.0']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'main',
    'corsheaders'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'dj_firebase.urls'

CORS_ALLOWED_ORIGINS = [
    "{{EDUCATIVE_LIVE_VM_URL}}",  # Replace with your actual domain
    "http://0.0.0.0",
]



CORS_ALLOW_CREDENTIALS = True

CORS_ORIGIN_ALLOW_ALL = True

CORS_ALLOW_CREDENTIALS = True


CSRF_TRUSTED_ORIGINS = ['{{EDUCATIVE_LIVE_VM_URL}}']

CSRF_COOKIE_DOMAIN = ['{{EDUCATIVE_LIVE_VM_URL}}'.replace('https://','')]

CORS_ORIGIN_WHITELIST = (
    '{{EDUCATIVE_LIVE_VM_URL}}',
    '{{EDUCATIVE_LIVE_VM_URL}}'.replace('https://',''),
)

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates/'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'dj_firebase.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Kuala_Lumpur'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
A simple app to store images on Firebase

After receiving a pop-up confirming the successful file upload, we can validate its successful upload by following the steps outlined in the slides below in our Firebase console.

Front-end view
Front-end view
1 of 2

In the first slide, we observe our application's user interface, enabling file uploads from the desktop. Upon successful submission, a message reassuring the user of the successful upload is displayed. In the subsequent slide, we confirm the file's successful transmission to Firebase.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved