0

I want to add to template the media values so in the view I get the value in the get_queryset and then add them to template with get_context, but something is wrong :

class LaLista(ListView):

   def get_queryset(self, **kwargs): 
        qs = super(LaLista, self).get_queryset()
        media = qs.aggregate(Avg('A_U'), Max('A_U'), Min('A_U'))
        return qs, media

   def get_context_data(self, **kwargs):
        context = super(LaLista, self).get_context_data(**kwargs)
        context['media'] = media
        return context

in the template I have given:

{{ media }}

and this will return:

NameError: global name 'media' is not defined

1 Answer 1

1

You are using a variable media in function get_context_data, but you don't have the variable defined in the function. Python variables are bound within function scope so you cannot use it without defining it first.

You shouldn't query for media in function get_queryset, because get_queryset is meant to get the queryset that ListView will iterate in the template, so it should return only ONE result. If you want extra context, do it in function get_context_data:

def get_context_data(self, **kwargs):
    context = super(LaLista, self).get_context_data(**kwargs)
    # if you didn't define anything special, object_list is the default queryset name
    qs = kwargs['object_list']
    media = qs.aggregate(Avg('A_U'), Max('A_U'), Min('A_U'))
Sign up to request clarification or add additional context in comments.

1 Comment

Just changed kwargs to self.object_list and work fine.Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.