Alan Alan - 1 month ago 7
Python Question

Does Django used the same instance of class views per request?

In django, when using class based views, it is commonplace to set class-level variables such as

template_name


class MyView(View):

template_name = 'index.html'

def get(self, request):
...


I am wondering if modifying these variables during runtime

class MyView(View):

template_name = 'index.html'

def get(self, request):
if some_contrived_nonce_function(): # JUST SO IT ONLY RUNS ONCE
self.template_name = 'something.html'
...


will last only for that request (a new instance of
MyView
is created per request), or will it last for all subsequent requests (the same instance of
MyView
is used)

Answer

Modifying this as:

self.template_name = 'something.html'

will definitely only last for that request.

Modifying it as:

type(self).template_name = 'something.html'

will cause new instances to inherit your changes.

Comments