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

Question:

In Django, when using class based views, it is commonplace to setup 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 will persist across multiple requests or just the current one.

class MyView(View):
      template_name = 'index.html'

      def get(self, request):
          if only_returns_true_once_function():
             self.template_name = 'something.html'
          ...
Asked By: AlanSTACK

||

Answers:

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.

Answered By: Soviut

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.

Answered By: donkopotamus
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.