Last active
February 27, 2025 20:11
-
-
Save mick88/a29f3dd675c2c7a4ea6e549b707189a6 to your computer and use it in GitHub Desktop.
Django: Lazy view
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from typing import Callable | |
| from django.utils.module_loading import import_string | |
| from django.views import View | |
| class LazyView: | |
| """ | |
| Wrapper for view class that can be used for urls to avoid loading the view class at the import time. | |
| The view is imported at first access and cached. | |
| To use in urls.py, just instantiate `LazyView` with class path argument and use as a normal view: | |
| ```python | |
| url(r'^/view$', LazyView('path.to.ViewClass').as_view(), name="url-name"), | |
| ``` | |
| """ | |
| def __init__(self, view_cls_path: str) -> None: | |
| super().__init__() | |
| self.view_cls_path = view_cls_path | |
| def view_func(self, *args, **kwargs): | |
| if not hasattr(self, 'view'): | |
| view_cls: type[View] = import_string(self.view_cls_path) | |
| self.view: Callable = view_cls.as_view(**self.initkwargs) | |
| return self.view(*args, **kwargs) | |
| def as_view(self, **initkwargs): | |
| self.initkwargs = initkwargs | |
| return self.view_func |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's another update that fixes the
csrf_exemptissue for me, without needing to manually configure the LazyView class.This version lazily copies the view's dispatch method attributes over to the LazyView's function wrapper's attributes. The dispatch method attributes are updated by the
from django.views.decorators.csrf.csrf_exemptdecorator on the view's dispatch method, for example.