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)
Each request creates a new instance of that class, handles the request, and destroys it. The reason for class-based views is not to maintain instances, it's to allow inheritance and mixin composition. This makes it substantially easier to create reusable functionality that spans multiple views.
You can change variables at any point in the class' lifetime. The only point that these variables become important is when the request is handled, specifically during the dispatch()
method, which other HTTP action methods like get()
and post()
wrap.
I strongly encourage you to bookmark the Classy Class-based Views site because it offers an incredibly thorough overview of how class-based views are composed and how they inherit. The most appropriate way to change the template names in a class based view is to override the get_template_names()
method on a TemplateView
.
class MyView(TemplateView):
def get_template_names(self):
if some_contrived_nonce_function():
return 'something.html'
else:
return super(MyView, self).get_template_names()
The above assumes your view either inherits from TemplateView
or implements TemplateResponseMixin
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With