Is it possible to set instance variables in a Django based class view?

I am trying to view Django classes (CBV).

class BlahView(TemplateView): template_name = 'blah/blah.html' def get_context_data(self, **kwargs): #code... def get(self, request, **kwargs): #more code... 

Now I know that I can get request parameters from self.request. Now say that I want to analyze these query parameters and save them in the class. Can I save them in self.xxx ? Now, obviously, based on how classes work, this seems simple.

But I can't figure out the control flow by looking at the definition of View (superclass from TemplateView ). The source mentions as_view() as the "entry point"

I thought about setting my instance variables at the beginning of get_context_data() , but it doesn't seem to have the right to do initialization there.

Can I define __init__() for my CBV? If so, will there be problems with streams or something that can work with multiple instances of pages with a global instance of my analyzed data?

I know this sounds a bit messy, but I'm a little confused about the code stream in CBV.

+17
python django django-class-based-views
Jul 12 '12 at 9:20
source share
2 answers

According to django.views.generic.base.View.as_view source :

  • when django is started , as_view () returns a view function that is not called
  • upon request , view() is called , it creates an instance of the class and calls dispatch()
  • class instance is thread safe

According to the source django.views.generic.base.View.__init__ the request object is currently out of scope, so you cannot parse it in your constructor overload.

However, you can parse the request and set the class instance attributes when overloading django.views.generic.base.View.dispatch , this is safe according to the source :

 class YourView(SomeView): def dispatch(self, request, *args, **kwargs): # parse the request here ie. self.foo = request.GET.get('foo', False) # call the view return super(YourView, self).dispatch(request, *args, **kwargs) 
+35
Jul 12 2018-12-12T00:
source share
โ€” -

@jpic gave a great answer. Inspired by this, I would like to link to the next blog post , where the author claims that:

... We cannot override the view, as this will require an override of as_view (). Overriding submission () is attractive (and what I did initially when I introduced this conversation), because it offers one simple place for this, but it does not match the submission () logic. Instead, it's best to call set_account () in the override as get () and post () ....

Therefore, you can override the get or post methods and set any self.whatever variables. It feels somehow cleaner.

+1
Oct 18 '16 at 2:59
source share



All Articles