Tutorial | Django LiveView

Welcome to the Tutorial guide. Here you will learn how to create your first real-time SPA using Django LiveView. I assume you have a basic understanding of Django and Python.

All the steps are applied in a minimalist template.

Step 1: Installation

pip install django-liveview

Step 2: Configure Django

Add to your settings.py:

# settings.py
INSTALLED_APPS = [
    "daphne",  # Must be first for ASGI support
    "channels",
    "liveview",
    # ... your other apps
]

# ASGI configuration
ASGI_APPLICATION = "your_project.asgi.application"

# Configure Channels with Redis
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("127.0.0.1", 6379)],
        },
    },
}

Step 3: Setup ASGI routing

Create or update asgi.py:

# asgi.py
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator
from liveview.routing import get_liveview_urlpatterns

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project.settings")

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(
                get_liveview_urlpatterns()
            )
        )
    ),
})

Step 4: Add JavaScript to your base template

<!-- templates/base.html -->
{% load static %}
<!DOCTYPE html>
<html lang="en" data-room="{% if request.user.is_authenticated %}{{ request.user.id }}{% else %}anonymous{% endif %}">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}My Site{% endblock %}</title>
</head>
<body data-controller="page">
    {% block content %}{% endblock %}

    <!-- Django LiveView JavaScript -->
    <script src="{% static 'liveview/liveview.min.js' %}" defer></script>
</body>
</html>

Step 5: Create your first LiveView handler

Create app/liveview_components/hello.py:

# app/liveview_components/hello.py
from liveview import liveview_handler, send
from django.template.loader import render_to_string

@liveview_handler("say_hello")
def say_hello(consumer, content):
    """Handle 'say_hello' function from client"""
    name = content.get("form", {}).get("name", "World")

    html = render_to_string("hello_message.html", {
        "message": f"Hello, {name}!"
    })

    send(consumer, {
        "target": "#greeting",
        "html": html
    })

Create the template templates/hello_message.html:

<h1>{{ message }}</h1>

Step 6: Use it in your page

<!-- templates/hello_page.html -->
{% extends "base.html" %}

{% block content %}
<div>
    <input type="text" name="name" placeholder="Enter your name">
    <button
        data-liveview-function="say_hello"
        data-action="click->page#run">
        Say Hello
    </button>

    <div id="greeting">
        <h1>Hello, World!</h1>
    </div>
</div>
{% endblock %}

Step 7: Run your project

# Run Django with Daphne (ASGI server)
python manage.py runserver

That's it! Click the button and see real-time updates. 🎉

You can also interact with the online demo.

Congratulations! You have created your first real-time SPA using Django LiveView.