How to discover which variables are available in a Django template

In our Rome office it often happens that we work in a team on a Django project and that we need to decouple the backend from the frontend.
One of the problems that often arises is the possibility of finding out which variables are available in the template. The frontend developer is sometimes dependent on the backend developer, who can tell him what parameters he can find in the context.
Fortunately Django solves this need in a very simple way.
How to do it
-
If the URLs are served by the Class Based View we can access the context data in a very simple way.
Imagine we have a template and we want to find out what variables are available.
For example, we could write:
index.hml
{{ view.get_context_data.view }}
This is possible only thanks to ContextMixin, defined here. This mixin is used by almost all Django View and, as you can see, is added to the context given also the reference to the calling view.
class ContextMixin:
"""
A default context mixin that passes the keyword arguments received by
get_context_data() as the template context.
"""
extra_context = None
def get_context_data(self, **kwargs):
kwargs.setdefault('view', self)
if self.extra_context is not None:
kwargs.update(self.extra_context)
return kwargs
So, in the template what we get with the call {{ view.get_context_data }} will be something like this:
{'foo': 'bar', 'example_variable': True, 'view': <web.views.HomeView object at 0x1105a9f98>}
Nothing could be easier to simplify the life of frontend developers.
-
Another extremely simple way is to use django-debug-toolbar.
You can inspect everything, including the template, as you can see from the following image:
We use this process and these tools in all our projects, that we initialize through django-uwisgi-template: a very light and simple boilerplate for the quick Launch of Django projects.