Search code examples
djangodjango-viewsdjango-class-based-viewsdjango-context

Django: How to reference a context variable created in one class-based view from another class-based view


In the simplified example below, how do I reference the context variable "Elephant" (created in the class Lion) from inside the class Leopard?

I have researched and tried a number of ways, including the last line below which results in a KeyError for "Elephant".

views.py

class Lion(ListView):
   
    def get_context_data(self, **kwargs):
        context super().get_context_data()
        context[“Elephant”] = Rhinoceros 
        context["Giraffe"] = Eagle
        return context

class Leopard(ListView):
    Buffalo = Lion.get_context_data(context[“Elephant”])

Solution

  • One option is to create your own ListView super class:

    class AnimalListView(ListView):
        def get_context_data(self, *args, **kwargs):
            super().get_context_data(*args, **kwargs)
            return {
                "Elephant": Rhinoceros,
                "Giraffe": Eagle,
            }
    

    Now your other list views can inherit this instead of inheriting form ListView directly:

    class LionList(AnimalListView):
        ...
    
    class LeopartList(AnimalListView):
        ...
    

    Alternatively, you can make the class a mixin:

    class AnimalContextMixin:
        def get_context_data(self, *args, **kwargs):
            super().get_context_data(*args, **kwargs)
            return {
                "Elephant": Rhinoceros,
                "Giraffe": Eagle,
            }
    

    And then your list views should inherit from both ListView and this mixin:

    class LionList(AnimalContextMixin, ListView):
        ...
    
    class LeopartList(AnimalContextMixin, ListView):
        ...