Streamline Astra
Streamline Astra

Reputation: 317

Django views as_view()

Example views.py:
from django.http import HttpResponse
from django.views import View

class MyView(View):

    def get(self, request, *args, **kwargs):
        return HttpResponse('Hello, World!')

Example urls.py:
from django.urls import path
from myapp.views import MyView

urlpatterns = [
    path('mine/', MyView.as_view(), name='my-view'),
]



classmethod as_view(**initkwargs)¶

What happens when a request from the user is received? Is the view returned from ClassView.as_view() called? Or is an instance of Class View created?

Upvotes: 5

Views: 3582

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476624

The urls.py will call the callable that is passed to the path(..). Here .as_view() will thus return a function that is called. You can find the source code for this in the GitHub repositiory:

@classonlymethod
def as_view(cls, **initkwargs):
    """Main entry point for a request-response process."""
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))

    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.setup(request, *args, **kwargs)
        if not hasattr(self, 'request'):
            raise AttributeError(
                "%s instance has no 'request' attribute. Did you override "
                "setup() and forget to call super()?" % cls.__name__
            )
        return self.dispatch(request, *args, **kwargs)
    view.view_class = cls
    view.view_initkwargs = initkwargs

    # take name and docstring from class
    update_wrapper(view, cls, updated=())

    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

It will thus return the view function that it constructs in the as_view() method. When the view() method is then called when you "trigger" the view, it will construct a View instance with the optional **initkwargs you passed to the as_view() method. This thus means that each HTTP request, will construct a new View object.

Next it will "setup" the obect by adding the request, the args and the kwargs to the instance. Finally it will call self.dispatch(..) this method will take a look at the request method (GET, POST, PUT, PATCH, DELETE, …), look if it is part of the acceptable methods, and in that case trigger the corresponding .get(..), .post(..), .put(..), … method, and return the result of that method.

Upvotes: 7

Related Questions