Wizard
Wizard

Reputation: 22043

How to create an instance created from class-based views

I am learning Django's class-based views. I don't understand what's the instance created from class Views

For example:

from django.http import HttpResponse
from django.views import View

# views.py
class MyView(View):
    def get(self, request):
        # <view logic>
        return HttpResponse('result')
# urls.py
from django.conf.urls import url
from myapp.views import MyView

urlpatterns = [
    url(r'^about/$', MyView.as_view()),
]

What's the instance of class 'MyView' during this request-and-respond process?

Upvotes: 0

Views: 78

Answers (1)

John Moutafis
John Moutafis

Reputation: 23134

Although your question is not very clear, I think that I get what you are asking:

Take a look at the source code of url() method:

def url(regex, view, kwargs=None, name=None):
      if isinstance(view, (list, tuple)):
          # For include(...) processing.
          urlconf_module, app_name, namespace = view
          return RegexURLResolver(
              regex, urlconf_module, kwargs, 
              app_name=app_name, namespace=namespace
          )
      ...

And a look at the as_view() method documentation:

Returns a callable view that takes a request and returns a response:

response = MyView.as_view()(request)

The returned view has view_class and view_initkwargs attributes.
When the view is called during the request/response cycle, the HttpRequest is assigned to the view’s request attribute.

Therefore because you are passing in the url method the MyView.as_view() argument you are giving the instruction to instantiate the MyView class when a request object gets passed to the url() method.

Upvotes: 1

Related Questions