0

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”])
Condado
  • 83
  • 7

2 Answers2

2

There is missing some information what exactly are you trying to achieve as the example doesnt exactly make sense - why are you trying to define Buffalo as class property in Leopard?

But generally you can define the items somewhere outside the class and then reuse them in both views:

def get_animals():
    return {
        "Elephant": Rhinoceros,
        "Giraffe": Eagle,
    }

class Lion(ListView):
   
    def get_context_data(self, **kwargs):
        context = super().get_context_data()
        context.update(get_animals())
        return context

class Leopard(ListView):
    def get(self, *args, **kwargs):
        # assuming you dont want to have that as a property
        animals = get_animals()
        Buffalo = Lion.get_context_data(animals[“Elephant”])
yedpodtrzitko
  • 9,035
  • 2
  • 40
  • 42
1

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):
    ...
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268