Friday, November 17, 2017

Retrieve the instance created by class_based_view

Leave a Comment

Django documentation specify as_view method in class-based-views

as_view() class method creates an instance of the class and calls its dispatch() method.

I attempt to print the instance. For illustration:

 # urls.py from django.conf.urls import url from myapp.views import MyView  urlpatterns = [     url(r'^about/$', MyView.as_view()), ]   #views.py from django.http import HttpResponse from django.views import View  class MyView(View):     def get(self, request):         # <view logic>         return HttpResponse('result') 

I added a print statement to views.py:

class MyView(View):     print(self)     def get(self, request):         # <view logic>         return HttpResponse('result') 

It reports NameError.

How can I print the instance created by class 'View'?

4 Answers

Answers 1

You can use __repr__ or __str__ method of the view (those methods are by default inherited by every python class). There are 2 options:

  1. Get the representation (__repr__ do you get it yet? :D) every time a REST method gets called:

    class MyView(View):     def get(self, request):         # <view logic>         print(self.__repr__())         return HttpResponse(result) 

    or return it in the HttpResponse:

    class MyView(View):     def get(self, request):         # <view logic>         result['self_repr'] = self.__repr__()         return HttpResponse(result) 
  2. Get the representation of the class each time it gets instantiated:

    class MyView(View):     def __init__(self, *args, **kwargs):         super().__init__(*args, **kwargs)         print(self.__repr__()) 

The end result though will be something like this:

<my_app.views.MyView object at 0x7f63b5e05668> 

which is not very helpful. You can override the __str__() method to return something more specific but that is up to you!

Answers 2

You're trying to access self outside its scope

class MyView(View):     def __init__(self, *args, **kwargs):         super(MyView, self).__init__(*args, **kwargs)         print self      def get(self, request):         # <view logic>         return HttpResponse('result') 

Answers 3

Something like that will not print much usefulness like:

<app.views.MyView object at 0x000001720304E128> 

Of course you can make it better by defining:

def __str__(self):     return self.attibutehere 

However I get the feeling that you are looking for the implementation details of the class. This is done by a process called "introspection".

As an example amongst other powerful commands there is a dir() command which could be used like this from the command line:

project location>python manage.py shell >>>from polls.views import IndexView >>>iv=IndexView() >>>dir(iv) ['__class__', ...whole bunch of interesting stuf here... , 'template_name_suffix'] >>> iv.__class__ <class 'polls.views.IndexView'> 

Answers 4

try:

class MyView(View):     print(self)     def get(self, request):         print('self:', self)         return HttpResponse('result') 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment