Skip to content

User Guide

Basic setup

Once django-gesha has been installed it can be enabled by configuring the views and templates you would like to use it with.

Configure views

django-gesha requires you to add some context data to your views to work. See the following examples for class-based views and function-based views.

Example class-based view

Add gesha.JSContextMixin to your class-based view, and add JavaScript context data by extending its get_js_context_data() method:

import gesha
from django.views.generic import TemplateView


class HomeView(gesha.JSContextMixin, TemplateView):
    template_name = "myapp/home.html"

    def get_js_context_data(self, **kwargs) -> dict:
        context = super().get_js_context_data(**kwargs)
        context.update({"myNumber": 5, "myString": "this is my string"})
        return context
1
2
3
4
5
6
from django.urls import path
from myapp import views

urlpatterns = [
    path("", views.HomeView.as_view(), name="home"),
]

Example function-based view

import gesha
from django.http import HttpRequest, HttpResponse
from django.shortcuts import render


def home(request: HttpRequest) -> HttpResponse:
    context = {}
    context.update(
        gesha.create_js_context_data(
            {"myNumber": 5, "myString": "this is my string"}
        )
    )
    return render(request, "myapp/home.html", context=context)
1
2
3
4
5
6
from django.urls import path
from myapp import views

urlpatterns = [
    path("", views.home, name="home"),
]

Configure templates

To use django-gesha's JavaScript API, load the script in your template, and load the context using the {% jscontext %} template tag:

{% load gesha static %}

{% jscontext %}

<script src="{% static 'gesha/dist/js/django-gesha.bundle.min.js' %}"></script>
Example of a whole template
myapp/templates/myapp/home.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Home</title>
  </head>
  <body>
    {% load gesha static %}

    {% jscontext %}

    <script src="{% static 'gesha/dist/js/django-gesha.bundle.min.js' %}">
    </script>
  </body>
</html>

Test JavaScript API

You can test that the JavaScript API is available by opening the console on your browser:

>> console.log(window.django.context.myNumber)
   5

>> console.log(window.django.context.myString)
   "this is my string"

Using the JavaScript API

Add context

Any context data added using the methods below must be JSON serializable.

Adding context in class-based views

For class-based views override get_js_context_data() to add context data:

class HomeView(gesha.JSContextMixin, TemplateView):
    template_name = "myapp/home.html"

    def get_js_context_data(self, **kwargs) -> dict:
        context = super().get_js_context_data(**kwargs)
        context.update({"myNumber": 5, "myString": "this is my string"})
        return context

Adding context in class-based views

For function-based views pass a dict to create_js_context_data() to add context data:

def home(request):
    context = {}
    context.update(
        gesha.create_js_context_data(
            {"myNumber": 5, "myString": "this is my string"}
        )
    )
    return render(request, "myapp/home.html", context=context)

Reverse URLs

Reverse URLs in JavaScript using the following function:

window.django.urls.reverse(name: string, kwargs?: ReverseKwargs): string

  • name: string – The namespaced URL name.
  • kwargs?: { [argName: string]: number | string } – URL arguments.

Examples of URL reversing

>> window.django.urls.reverse("myapp:home")
"/"

>> window.django.reverse("myapp:page", { page: 5 })
"/page/5/"
Equivalent code in Django
In Python
from django.urls import reverse

reverse("myapp:page", kwargs={"page": 5})
In templates
{% url 'myapp:page' page=5 %}

Tip

To set the URLs available for reversing configure the GESHA_ALLOWED_URL_NAMES setting.

These patterns can also be set in class-based views by overriding the get_allowed_url_patterns() method, for example:

class HomeView(gesha.JSContextMixin, TemplateView):
    ...

    def get_allowed_url_patterns(self):
        return ["myapp:home", "otherapp:*"]

Tip

window.django.urls.reverse() is aliased to window.django.reverse()

Custom converters

If you have registered custom path converters in your Django project, you can also register them using the JavaScript API, for example:

Example path converter registration

1
2
3
const fourDigitYearConverter = new window.django.urls.Converter("yyyy", /[0-9]{4}/);

window.django.urls.converters.register(fourDigitYearConverter);
1
2
3
4
5
6
7
8
class FourDigitYearConverter:
    regex = "[0-9]{4}"

    def to_python(self, value):
        return int(value)

    def to_url(self, value):
        return "%04d" % value

Handling errors

window.django.reverse() will throw a window.django.urls.NoReverseMatch error if:

  • The name provided does not match any known URLs.
  • The URL requires args, but none were provided.
  • The URL received args, but their values failed validation.
Example JavaScript code which handles NoReverseMatch
try {
  window.django.urls.reverse("missing:path")
}
catch(err) {
  if (err.name === "NoReverseMatch") {
    console.log("handle NoReverseMatch");
  } else {
    console.log("handle different error")
  }
}