V
V
Vasily2015-11-06 19:06:49
Django
Vasily, 2015-11-06 19:06:49

Why can't access the parent variable in the class?

Good afternoon, for example, we have such a CBV

class Post_Detail(TemplateView):
    template_name = 'blog/post_detail.html'

Why can't I access template_name but can only override it? Why is it like this
class Post_Detail(TemplateView):
    template_name = super().template_name

can't get through to her? How to contact the parent?
PS super without parameters, we mean that we have the 3rd version of python, it also does not work with parameters

Answer the question

In order to leave comments, you need to log in

3 answer(s)
O
Oscar Django, 2015-11-07
@winordie

There is a get_template_names method where you can get the current template_name by self.template_name. Override this method.
Example:

class CategoryView(TemplateView):
    template_folder = 'build'
    template_name = 'build/category.html'
    ...
    def get_template_names(self):
        template = self.template_name
        category_template = '{folder}/{slug}/category.html'.format(folder=self.template_folder, slug=self.category.slug)
        return [category_template, template]
    ...

R
Roman Kitaev, 2015-11-06
@deliro

1) TemplateView doesn't have template_name variable defined
2) Do it in a method.

class A(object):
    x = 5

class B(A):
    x = 6
    def foo(self):
        return super().x  # вернёт 5

V
Vladislav Sklyar, 2015-11-07
@VladSkliar

self.template_name

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question