Built-in class-based views API
Class-based views API reference. For introductory material, see the基于类的视图 topic guide.
- 基础视图
- Generic display views
- Generic editing views
- 通用日期视图
- Class-based views mixins
- Class-based generic views - flattened index
Specification
Each request served by a class-based view has an independent state; therefore,it is safe to store state variables on the instance (i.e., self.foo = 3
isa thread-safe operation).
A class-based view is deployed into a URL pattern using theas_view()
classmethod:
- urlpatterns = [
- path('view/', MyView.as_view(size=42)),
- ]
Thread safety with view arguments
Arguments passed to a view are shared between every instance of a view.This means that you shouldn't use a list, dictionary, or any othermutable object as an argument to a view. If you do and the shared objectis modified, the actions of one user visiting your view could have aneffect on subsequent users visiting the same view.
Arguments passed into as_view()
willbe assigned onto the instance that is used to service a request. Using theprevious example, this means that every request on MyView
is able to useself.size
. Arguments must correspond to attributes that already exist onthe class (return True
on a hasattr
check).
Base vs Generic views
Base class-based views can be thought of as parent views, which can beused by themselves or inherited from. They may not provide all thecapabilities required for projects, in which case there are Mixins whichextend what base views can do.
Django's generic views are built off of those base views, and were developedas a shortcut for common usage patterns such as displaying the details of anobject. They take certain common idioms and patterns found in viewdevelopment and abstract them so that you can quickly write common views ofdata without having to repeat yourself.
Most generic views require the queryset
key, which is a QuerySet
instance; see 执行查询 for more information about QuerySet
objects.