DEV Community

Cover image for Convert Django website to PWA
Rachit Khurana
Rachit Khurana

Posted on

Convert Django website to PWA

We can convert a Django website to a PWA (Progressive web app) very easily.
PWA are web apps that look like a normal native app on the phone or PC. I consider it to be a shortcut for making cross-platform applications
PWA logo

We will be using django-pwa package for the same.

Installation

  • Installing the django-pwa package
pip install django-pwa
Enter fullscreen mode Exit fullscreen mode
  • Add pwa to your list of INSTALLED_APPS in settings.py:
# project/settings.py
INSTALLED_APPS = [
    ...
    'pwa',
    ...
]
Enter fullscreen mode Exit fullscreen mode

Configuration

  • Adding PWA settings to settings.py file
# project/settings.py

PWA_APP_NAME = 'My App'
PWA_APP_DESCRIPTION = "My app description"
PWA_APP_THEME_COLOR = '#0A0302'
PWA_APP_BACKGROUND_COLOR = '#ffffff'
PWA_APP_DISPLAY = 'standalone'
PWA_APP_SCOPE = '/'
PWA_APP_ORIENTATION = 'any'
PWA_APP_START_URL = '/'
PWA_APP_STATUS_BAR_COLOR = 'default'
PWA_APP_ICONS = [
    {
        'src': '/static/images/my_app_icon.png',
        'sizes': '160x160'
    }
]
PWA_APP_ICONS_APPLE = [
    {
        'src': '/static/images/my_apple_icon.png',
        'sizes': '160x160'
    }
]
PWA_APP_SPLASH_SCREEN = [
    {
        'src': '/static/images/icons/splash-640x1136.png',
        'media': '(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)'
    }
]
PWA_APP_DIR = 'ltr'
PWA_APP_LANG = 'en-US'
Enter fullscreen mode Exit fullscreen mode

Making it compatible with Django 4

Currently django-pwa version 1.0.10 is not compatible with Django 4. So if you are using an earlier version of Django or this package has received updates, you can skip these steps (marked with *).

  • *Make a new folder in the base directory*

I named it pwa1

  • *Make a new file urls.py with the following content*
from django.urls import re_path as url

from .views import manifest, service_worker, offline

# Serve up serviceworker.js and manifest.json at the root
urlpatterns = [
    url(r'^serviceworker\.js$', service_worker, name='serviceworker'),
    url(r'^manifest\.json$', manifest, name='manifest'),
    url('^offline/$', offline, name='offline')
]
Enter fullscreen mode Exit fullscreen mode
  • Add the following to your project's urls.py file
...
urlpatterns=[
    ...
    path('', include('pwa.urls')),
    # if you used the above method for compatibility then use the following code instead
    #path('', include('pwa1.urls')),
    ...
    ]
Enter fullscreen mode Exit fullscreen mode
  • Make a serviceworker.js file in your static folder with the following content.
// Base Service Worker implementation.  To use your own Service Worker, set the PWA_SERVICE_WORKER_PATH variable in settings.py

var staticCacheName = "django-pwa-v" + new Date().getTime();
var filesToCache = [
    '/offline',
    '/css/django-pwa-app.css',
    '/images/icons/icon-72x72.png',
    '/images/icons/icon-96x96.png',
    '/images/icons/icon-128x128.png',
    '/images/icons/icon-144x144.png',
    '/images/icons/icon-152x152.png',
    '/images/icons/icon-192x192.png',
    '/images/icons/icon-384x384.png',
    '/images/icons/icon-512x512.png',
    '/static/images/icons/splash-640x1136.png',
    '/static/images/icons/splash-750x1334.png',
    '/static/images/icons/splash-1242x2208.png',
    '/static/images/icons/splash-1125x2436.png',
    '/static/images/icons/splash-828x1792.png',
    '/static/images/icons/splash-1242x2688.png',
    '/static/images/icons/splash-1536x2048.png',
    '/static/images/icons/splash-1668x2224.png',
    '/static/images/icons/splash-1668x2388.png',
    '/static/images/icons/splash-2048x2732.png'
];

// Cache on install
self.addEventListener("install", event => {
    this.skipWaiting();
    event.waitUntil(
        caches.open(staticCacheName)
            .then(cache => {
                return cache.addAll(filesToCache);
            })
    )
});

// Clear cache on activate
self.addEventListener('activate', event => {
    event.waitUntil(
        caches.keys().then(cacheNames => {
            return Promise.all(
                cacheNames
                    .filter(cacheName => (cacheName.startsWith("django-pwa-")))
                    .filter(cacheName => (cacheName !== staticCacheName))
                    .map(cacheName => caches.delete(cacheName))
            );
        })
    );
});

// Serve from Cache
self.addEventListener("fetch", event => {
    event.respondWith(
        caches.match(event.request)
            .then(response => {
                return response || fetch(event.request);
            })
            .catch(() => {
                return caches.match('offline');
            })
    )
});
Enter fullscreen mode Exit fullscreen mode
  • Load PWA meta in templates Add the following tags in your base.html file.
{% load pwa %}

<head>
    ...
    {% progressive_web_app_meta %}
    ...
</head>
Enter fullscreen mode Exit fullscreen mode

That's All 🎉

You can now see an option to install your site as an app in your supported browser on mobile as well as PC

Discussion (0)