user3595632
user3595632

Reputation: 5730

Django: can't store variable in self.xxx in Generic View?

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

Answers (1)

Alex Paramonov
Alex Paramonov

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

Related Questions