I've just started using class-based views in django. But there's an issue that is confusing for me. I ran the following code snippet with django 1.4.1 with multithreaded development server.
class TestView(TemplateView):
template_name = 'test.html'
count = 0
mylist = [1, ]
def get(self, request, *args, **kwargs):
self.count += 1
self.mylist.append(self.mylist[-1] +1)
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
def get_context_data(self, **kwargs):
context = super(TestView, self).get_context_data(**kwargs)
context['count'] = self.count
context['mylist'] = self.mylist
return context
The template just outputs the context variables count and mylist. When this view is called e.g. up to 5 times the output will look like this:
count: 1
mylist: [1, 2, 3, 4, 5, ]
And now I'm confused. The django docs says, that each request has its own individual class instance.
So how it is possible to extend mylist over several requests? Why the count variable was not incremented?
Class variables are shared across all objects while instance variables are for data unique to each instance.
Default Values of Instance Variables in Java: The first property is that instance variables are by default public. This means that any class in your application can access them. You can, however, make an instance variable private, which would restrict access to it only to the class in which it is declared.
Instance Variable: It is basically a class variable without a static modifier and is usually shared by all class instances. Across different objects, these variables can have different values.
Instance variables have a default value based on the type. For any non-primitive, including String, that type is a reference to null. Option B is correct.
If you need something available over several requests, you need to add it to the session. An ivar is not the place for that. For thread-safety, the as_view
method returns a brand new instance of the class each time, which is not effected by anything else that happens on any other instances of the same class. This is by design and you'd have numerous problems if it wasn't the case.
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