kitchen800
kitchen800

Reputation: 227

Passing a context variable through a class in Django

how can i pass a context variable in a class. i know that i would use the render if i was showing my template from a function. and then i could just pass my context variable as part of the render. But how do i pass a context variable to html if i am using a class to show the template.

i have tried putting a function into my class but it has not worked.

views.py

class hithere(ListView):
model = Datadata
template_name = 'index.html'

def whatsup(request):
    context = {}
    context['my_string'] = "this is my sring"
    return render(request, context)

Index.html

<h1>  {{ my_string }} </h1>

Upvotes: 1

Views: 1264

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477794

You can override the .get_context_data(…) method [Django-doc]:

class hithere(ListView):
    model = Datadata
    template_name = 'index.html'

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        context['my_string'] = 'this is my string'
        return context

But perhaps more convenient is to define a method:

class hithere(ListView):
    model = Datadata
    template_name = 'index.html'

    def my_string(self):
        return 'this is my string'

and render this with:

{{ view.my_string }}

Note: normally a Django models, just like all classes in Python are given a name in PerlCase, not snake_case, so it should be: HitHereView instead of hithere.

Upvotes: 2

Related Questions