Acy
Acy

Reputation: 659

Django: putting more context in get_context_data in class-based-view

I do know that to put more context in a listview in django, we can just something like:

def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        b = 9
        context['num'] = b
        return context

and with that, we can use num in our template file.

But let's say I want to variables to be placed in the context, what do I do?

b = 9
a = 10 
context['a', 'b'] = a, b

and then I refered to this in my html template by directly calling {{a}} or {{b}}, no errors shows up, but nothing shows up either.

I think I have some misconception about a basic dictionary, and django adds confusion to it because it seems like you can't use () or [] inside of {{}}, by the way can someone answer why we can't use () or [] inside of the html code inside of {{}}?

Upvotes: 1

Views: 870

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477749

context is just a dictionary, so you can write it like:

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    b = 9
    a = 10
    context['a'] = a
    context['b'] = b
    return context

or you can use a .update(..) call, and add the elements in a single function call:

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    b = 9
    a = 10
    context.update(a=a, b=b)
    return context

why we can't use () or [] inside of the html code inside of {{ }}?

Because Django templates are deliberately limited, to prevent people from writing business logic in templates. Jinja however is a template processor that allows to make function calls and subscripting. But typically if you need these in a template, then this is a sign that something might be wrong with the design.

Upvotes: 6

Related Questions