user3408132
user3408132

Reputation: 55

how to specify a page title in a django views.py file using a context variable?

I am trying to specify a page title that shows up in the browser tab within a views.py file for a class based view. I am working with a file that uses a base template html page for many different pages where I am trying specify the title using something such as:

{% block title %}{{ view.build_page_title }}{% endblock %}

in the views.py file I am trying something like this:

class ExampleReportView(BaseReportView):

    def build_page_title(self):
        return 'Example Page Title'

This does not seem to be working. I am an absolute beginner in Django Python. Thanks for any help!

Upvotes: 1

Views: 3671

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599630

You don't pass values to the template by defining arbitrary methods on your view class; the template has no access to the view at all.

Instead, the view class will call its own get_context_data to determine the values to pass to the template; you can override that and add your own value.

class ExampleReportView(BaseReportView):

    def get_context_data(self, *args, **kwargs):
        data = super(ExampleReportView, self).get_context_data(*args, **kwargs)
        data['build_page_title'] = 'Example Page Title'
        return data

Of course, you can add as many values as you like inside that method.

Upvotes: 4

Related Questions