Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

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)

like image 552
AlanSTACK Avatar asked Oct 26 '16 04:10

AlanSTACK


2 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.

like image 99
Soviut Avatar answered Oct 12 '22 10:10

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.

like image 45
donkopotamus Avatar answered Oct 12 '22 11:10

donkopotamus