How to define a variable in Django TemplateView?

I created a Django project and prepared 3 html pages. By the way, my English is not good, I apologize in advance.

Here is the views.py file example;

class HomePageView(TemplateView):
     template_name = 'home.html'

class LoginPageView(TemplateView):
     template_name = 'login.html'

class NotFoundPageView(TemplateView):
     template_name = 'login.html'

I want to add a variable to the home.html file. How do I define it here? Thanks in advance for your help.

Upvotes: 2

Views: 1259

Answers (1)

Alasdair
Alasdair

Reputation: 308939

For static data you can set extra_context on the view (Django 2.0+)

class HomePageView(TemplateView):
    template_name = 'home.html'

    extra_context = {'page_name': 'home'}

For dynamic data or older versions of Django, you can override get_context_data.

import random

class HomePageView(TemplateView):
    template_name = 'home.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['number'] = random.randrange(1, 100)
        return context

Upvotes: 5

Related Questions