Reputation: 5730
views.py
class MyView(View):
def get(self, request, *args, **kwargs):
self.foo = "hi"
def post(self, request, *args, **kwargs):
print(self.foo)
GET
request works but POST
request doesn't work.
It occurs errors,
AttributeError: 'MyView' object has no attribute 'foo'
Can't I save variable in self.xxx
in views.py
?
Upvotes: 0
Views: 349
Reputation: 2720
get
& post
methods are working independently and Django creates a new MyView
instance on every request, that means when you first run GET
request an instance of MyView
class gets created, foo
is assigned a value and after request has completed - MyView
gets destroyed. When you make POST
request - a new instance of MyView
gets created again and it does not have that foo
attribute anymore.
To keep some value between requests you have to use Sessions:
class MyView(View):
def get(self, request, *args, **kwargs):
request.session['foo'] = "hi"
def post(self, request, *args, **kwargs):
print(request.session.get('foo', "default value"))
Upvotes: 1