Passing Python Values to JS in Wagtail

Kevin howbrook
2 min readJun 25, 2019

--

I was trying to figure out a way to call a JavaScript function using values from the request object. It turns out, Django has a built-in template filter for this…

As an example, I’m going to add some data by overriding the get_context() method on a basic HomePage model (line 19, my_info):

from django.db import models

from wagtail.core.models import Page
from wagtail.admin.edit_handlers import FieldPanel


class HomePage(Page):
publication_date = models.DateTimeField(null=True, blank=True)
updated_date = models.DateTimeField("Modified date", blank=True, null=True)

content_panels = Page.content_panels + [
FieldPanel("publication_date"),
FieldPanel("updated_date"),
]

def get_context(self, request, *args, **kwargs):
context = super().get_context(request, *args, **kwargs)

my_info = {
"username": request.user.username,
"page_title": self.title,
"fbi_agent": "Fox Mulder",
}

context.update(my_info=my_info)

return context

In the home_page.html template, we would normally use this like {{ my_info }} or loop over it depending on what we needed. But if we use the json_script filter, we can safely output this value as JSON…

{{ my_info|json_script:"my-info" }}

Our data is now ready for use with JavaScript. Check the DOM:

Our data has been added as JSON, wrapped in a script tag, and we can see the data. We can now use this value by looking it up in JavaScript like so:

info = JSON.parse(document.getElementById(‘my-info’).textContent); 

As a bonus… here is an image of the Django rugby team, passing some data to the JavaScript rugby team:

Photo by Quino Al on Unsplash

--

--