Django: Adding Context Data to Class Based Views Using Properties

When using Class-Based Views in Django, we normally add additional context data to the view by implementing the get_context_data() method:

class MyDetailView(DetailView):

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['foo'] = 'bar'

        return context

This works well. But I am very fond of using another approach, so as to not pollute the get_context_data method. We can achieve this using properties:

class MyDetailView(DetailView):

    @property
    def foo(self):
        return 'bar'

And in the template:

<p>Foo: {{ view.foo }}</p>

Notice how this context that is added as a Python property is accessed through view in the template.

✅ The cool thing about this is that we can also easily cache these properties using Django's @cached_property decorator.

django

Comments

comments powered by Disqus