0

When override the attributes of class view, it comes with:

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

I assume it should be:

class IndexView(generic.ListView):
    def __init__(self, *args, **kwargs):
        super().__init__(self, *args, **kwargs):
        template_name = 'polls/index.html'
        context_object_name = 'latest_question_list'

How Django achieve it by assign variable directly?

Alasdair
  • 298,606
  • 55
  • 578
  • 516
AbstProcDo
  • 19,953
  • 19
  • 81
  • 138

2 Answers2

1

The first case you show is an example of setting class variables. In the second case, you are actually defining local variables, but I assume you meant to assign instance variables like this:

def __init__(self, *args, **kwargs):
    super().__init__(self, *args, **kwargs):
    self.template_name = 'polls/index.html'
    self.context_object_name = 'latest_question_list'

Check out and the answers to this stack overflow post and this other one for some discussion of the difference.

RishiG
  • 2,790
  • 1
  • 14
  • 27
1

I didn't take a look at the source code of Django GenericView, variables that you point out are variables that we can call class Variables, these are variables of the class ListView. Basically, they are class variables shared by all instances.
Whereas inside __init__ they're called instance variable Unique to each instance

A small example (Not good enough):

class MyView:
    template_name = 'default_name.html' # class variable shared by all instances

    def __init__(self,name):
        self.name = name  # instance variable unique to each instance

    def get_template_name(self):
        return self.name
Lemayzeur
  • 8,297
  • 3
  • 23
  • 50