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:
Example function-based view
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
<!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:
Adding context in class-based views
For function-based views pass a dict to create_js_context_data()
to add
context data:
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
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:
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
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.