Day 12 Dev Notes
Just some tweaking of the PostHog integration this evening. Yesterday, I added the PostHog configuration and set it up so that the API key is loaded from the environment variables. But silly me - I forgot to add the environment variables to the Docker configuration, so they weren't being loaded into the app.
Today, I added the JavaScript integration to the Bus Times app. Still not sure what value it will add, but it's interesting to play with this stuff. Adding the JavaScript snippet posed a new challenge - I needed to include the API key in the JavaScript code, but I didn't want to hard code this in the template, and I didn't want to modify all the views to pass the key in the context. So with some help from my AI friends, I created a context processor, which isn't something I've used before in Django.
Here are the steps I followed:
- Created a file called
context_processors.py
in my Bus Times app directory. - Used the following code to return the PostHog API key and the host, both of which are configurable.
"""Context processors for the bustimes_app app."""
from django.conf import settings
from django.http import HttpRequest
def bustimes_context(_: HttpRequest) -> dict:
"""Add the PostHog API key and host to the context."""
return {
"POSTHOG_APIKEY": settings.POSTHOG_APIKEY,
"POSTHOG_HOST": settings.POSTHOG_HOST,
}
A couple of interesting notes about this... I'm not sure if this is the best way to do this, since I had conflicting and mixed recommendations from my AI friends. But this is the simplest approach I came up with after considering the advice. The only argument in the
bustimes_context
method is the request object, which is apparently a requirement for context processors. But sincerequest
isn't accessed in this function, I renamed it to_
to indicate that it's not needed in the function, and this prevents the IDE from giving warnings about it not being accessed.
Added
"bustimes_app.context_processors.bustimes_context"
to thecontext_processors
section in theTEMPLATES
configuration in the project settings.Then I can access the values in my template files like this:
posthog.init('{{ POSTHOG_APIKEY }}',{api_host:"{{ POSTHOG_HOST }}"})
That all seemed to work pretty well for now, but it reminded me that I really need to investigate context processors further to understand what they can do and how/when to use them.