django学习笔记——基于类的通用视图(reference)

Class-based generic views

New in Django 1.3:  Please, see the release notes

Note

Prior to Django 1.3, generic views were implemented as functions. The function-based implementation has been deprecated in favor of the class-based approach described here.

For details on the previous generic views implementation, see the topic guide and detailed reference.

Writing Web applications can be monotonous, because we repeat certain patterns again and again. Django tries to take away some of that monotony at the model and template layers, but Web developers also experience this boredom at the view level.

A general introduction to class-based generic views can be found in the topic guide.

This reference contains details of Django’s built-in generic views, along with a list of the keyword arguments that each generic view expects. Remember that arguments may either come from the URL pattern or from the extra_context additional-information dictionary.

Most generic views require the queryset key, which is a QuerySet instance; see Making queries for more information aboutQuerySet objects.

Mixins|混合类型

A mixin class is a way of using the inheritance capabilities of classes to compose a class out of smaller pieces of behavior. Django’s class-based generic views are constructed by composing mixins into usable generic views.|混合类就是使用类的继承的特性。django基于类的通用视图就是将一些mixin合成为有用的通用视图

For example, the DetailView is composed from:|例如 detailView就是从下列一些mixin合成而来:

  • View, which provides the basic class-based behavior   |  View,提供了一些基本的类属性
  • SingleObjectMixin, which provides the utilities for retrieving and displaying a single object    |   SingleObjectMixin,提供一些提取和显示single object的有用的utility.
  • SingleObjectTemplateResponseMixin, which provides the tools for rendering a single object into a template-based response.   |   提供了将single object渲染为一个template-based ressponse的工具

When combined, these mixins provide all the pieces necessary to provide a view over a single object that renders a template to produce a response. | 当combine以后,这些mixin就可以一起提供将single object 渲染为一个template的所有所需要的功能。

Django provides a range of mixins. If you want to write your own generic views, you can build classes that compose these mixins in interesting ways. Alternatively, you can just use the pre-mixed Generic views that Django provides. | django 提供了很多mixin, 如果你想要写你自己的generic views, 你可以按照你感兴趣的方法来重新合成这些mixin,当然你也可以使用django提供的预混合的Generic views.

Note

When the documentation for a view gives the list of mixins, that view inherits all the properties and methods of that mixin.

Simple mixins|简单的 mixins

TemplateResponseMixin

class  TemplateResponseMixin
template_name

The path to the template to use when rendering the view.|需要渲染的模板的路径

response_class

The response class to be returned by render_to_response method. Default is TemplateResponse. The template and context ofTemplateResponse instances can be altered later (e.g. in template response middleware)

render_to_response方法所返回的 response类。默认是TemplateResponse. templateResponse实例的模板和context都可以在之后被修改和改变。 

If you need custom template loading or custom context object instantiation, create a TemplateResponse subclass and assign it to response_class.

如果你需要自定义模板或者context,创建一个templateResponse子类然后将她赋给response_class. 

render_to_response( context**response_kwargs)

Returns a self.response_class instance.

返回一个self.response_class实例 

If any keyword arguments are provided, they will be passed to the constructor of the response class.

一旦提供了任何参数,他就可以生成一个response class. 

Calls get_template_names() to obtain the list of template names that will be searched looking for an existent template.

调用get_template_names()获得模板名字,然后在其中搜索存在的模板 

get_template_names()

Returns a list of template names to search for when rendering the template.

return一组模板路径用来给render_to_response搜索 

If TemplateResponseMixin.template_name is specified, the default implementation will return a list containingTemplateResponseMixin.template_name (if it is specified).

如果template_name有指定,get_template_name()返回的模板组中就会包含此路径 

Single object mixins

SingleObjectMixin

class  SingleObjectMixin
model

The model that this view will display data for. Specifying model = Foo is effectively the same as specifyingqueryset = Foo.objects.all().

视图用来显示数据的模型。model = Foo 相当于model = Foo.objects.all() 

queryset

QuerySet that represents the objects. If provided, the value of SingleObjectMixin.queryset supersedes the value provided for SingleObjectMixin.model.

返回一个查询实例, 

slug_field

The name of the field on the model that contains the slug. By default, slug_field is 'slug'.

 模型中包含这个slug的field的名字

context_object_name

Designates the name of the variable to use in the context.

在context中标记变量的名字 

get_object( queryset=None)

Returns the single object that this view will display. If queryset is provided, that queryset will be used as the source of objects; otherwise, get_queryset() will be used. get_object() looks for a pk argument in the arguments to the view; if pk is found, this method performs a primary-key based lookup using that value. If no pk argument is found, it looks for a slugargument, and performs a slug lookup using the SingleObjectMixin.slug_field.

返回一个view需要显示的single object.如果提供了queryset,queryset就会作为原始的objects;否则就会调用get_queryset().get_object()会搜索view中的pk参数;如果查询到pk,此方法就会使用此值,否则他会按照slug参数进行查询,slug会依照singleobjectmixin.slug_field提供的值

get_queryset()

Returns the queryset that will be used to retrieve the object that this view will display. By default, get_queryset() returns the value of the queryset attribute if it is set, otherwise it constructs a QuerySet by calling the all() method on the modelattribute’s default manager.

返回查询Object的queryset。当queryset有设定时,get_queryset()默认会返回queryset,否则他会返回foo.objects.all() 

get_context_object_name( obj)

Return the context variable name that will be used to contain the data that this view is manipulating. If context_object_nameis not set, the context name will be constructed from the object_name of the model that the queryset is composed from. For example, the model Article would have context object named 'article'.

返回context变量名,此变量名包含view需要处理和操作的数据。如果context_object_name没有设定,context name就会从object_name生成一个Ojbect_name例如,会从模型Article得到context object name 'article' 

get_context_data( **kwargs)

Returns context data for displaying the list of objects.

返回context data 

Context

  • object: The object that this view is displaying. If context_object_name is specified, that variable will also be set in the context, with the same value as object.

SingleObjectTemplateResponseMixin

class  SingleObjectTemplateResponseMixin

A mixin class that performs template-based response rendering for views that operate upon a single object instance. Requires that the view it is mixed with provides self.object, the object instance that the view is operating on. self.objectwill usually be, but is not required to be, an instance of a Django model. It may be None if the view is in the process of constructing a new instance.

Extends

  • TemplateResponseMixin
template_name_field

The field on the current object instance that can be used to determine the name of a candidate template. If eithertemplate_name_field or the value of the template_name_field on the current object instance is None, the object will not be interrogated for a candidate template name.

template_name_suffix

The suffix to append to the auto-generated candidate template name. Default suffix is _detail.

get_template_names()

Returns a list of candidate template names. Returns the following list:

  • the value of template_name on the view (if provided)
  • the contents of the template_name_field field on the object instance that the view is operating upon (if available)
  • /.html

Multiple object mixins

MultipleObjectMixin

class  MultipleObjectMixin

A mixin that can be used to display a list of objects.

If paginate_by is specified, Django will paginate the results returned by this. You can specify the page number in the URL in one of two ways:

  • Use the page parameter in the URLconf. For example, this is what your URLconf might look like:

    (r'^objects/page(?P[0-9]+)/$', PaginatedView.as_view()) 
  • Pass the page number via the page query-string parameter. For example, a URL would look like this:

    /objects/?page=3

These values and lists are 1-based, not 0-based, so the first page would be represented as page 1.

For more on pagination, read the pagination documentation.

As a special case, you are also permitted to use last as a value for page:

/objects/?page=last

This allows you to access the final page of results without first having to determine how many pages there are.

Note that page must be either a valid page number or the value last; any other value for page will result in a 404 error.

allow_empty

A boolean specifying whether to display the page if no objects are available. If this is False and no objects are available, the view will raise a 404 instead of displaying an empty page. By default, this is True.

model

The model that this view will display data for. Specifying model = Foo is effectively the same as specifyingqueryset = Foo.objects.all().

queryset

QuerySet that represents the objects. If provided, the value of MultipleObjectMixin.queryset supersedes the value provided for MultipleObjectMixin.model.

paginate_by

An integer specifying how many objects should be displayed per page. If this is given, the view will paginate objects withMultipleObjectMixin.paginate_by objects per page. The view will expect either a page query string parameter (via GET) or apage variable specified in the URLconf.

paginator_class

The paginator class to be used for pagination. By default, django.core.paginator.Paginator is used. If the custom paginator class doesn't have the same constructor interface as django.core.paginator.Paginator, you will also need to provide an implementation for MultipleObjectMixin.get_paginator().

context_object_name

Designates the name of the variable to use in the context.

get_queryset()

Returns the queryset that represents the data this view will display.

paginate_queryset( querysetpage_size)

Returns a 4-tuple containing (paginatorpageobject_listis_paginated).

Constructed by paginating queryset into pages of size page_size. If the request contains a page argument, either as a captured URL argument or as a GET argument, object_list will correspond to the objects from that page.

get_paginate_by( queryset)

Returns the number of items to paginate by, or None for no pagination. By default this simply returns the value ofMultipleObjectMixin.paginate_by.

get_paginator( querysetper_pageorphans=0allow_empty_first_page=True)

Returns an instance of the paginator to use for this view. By default, instantiates an instance of paginator_class.

get_allow_empty()

Return a boolean specifying whether to display the page if no objects are available. If this method returns False and no objects are available, the view will raise a 404 instead of displaying an empty page. By default, this is True.

get_context_object_name( object_list)

Return the context variable name that will be used to contain the list of data that this view is manipulating. If object_listis a queryset of Django objects and context_object_name is not set, the context name will be the object_name of the model that the queryset is composed from, with postfix '_list' appended. For example, the model Article would have a context object named article_list.

get_context_data( **kwargs)

Returns context data for displaying the list of objects.

Context

  • object_list: The list of objects that this view is displaying. If context_object_name is specified, that variable will also be set in the context, with the same value as object_list.
  • is_paginated: A boolean representing whether the results are paginated. Specifically, this is set to False if no page size has been specified, or if the available objects do not span multiple pages.
  • paginator: An instance of django.core.paginator.Paginator. If the page is not paginated, this context variable will be None.
  • page_obj: An instance of django.core.paginator.Page. If the page is not paginated, this context variable will be None.

MultipleObjectTemplateResponseMixin

class  MultipleObjectTemplateResponseMixin

A mixin class that performs template-based response rendering for views that operate upon a list of object instances. Requires that the view it is mixed with provides self.object_list, the list of object instances that the view is operating on.self.object_list may be, but is not required to be, a Queryset.

Extends

  • TemplateResponseMixin
template_name_suffix

The suffix to append to the auto-generated candidate template name. Default suffix is _list.

get_template_names()

Returns a list of candidate template names. Returns the following list:

  • the value of template_name on the view (if provided)
  • /.html

Editing mixins

FormMixin

class  FormMixin

A mixin class that provides facilities for creating and displaying forms.

initial

A dictionary containing initial data for the form.

form_class

The form class to instantiate.

success_url

The URL to redirect to when the form is successfully processed.

get_initial()

Retrieve initial data for the form. By default, returns initial.

get_form_class()

Retrieve the form class to instantiate. By default form_class.

get_form( form_class)

Instantiate an instance of form_class using get_form_kwargs().

get_form_kwargs()

Build the keyword arguments required to instantiate the form.

The initial argument is set to get_initial(). If the request is a POST or PUT, the request data (request.POST and request.FILES) will also be provided.

get_success_url()

Determine the URL to redirect to when the form is successfully validated. Returns success_url by default.

form_valid( form)

Redirects to get_success_url().

form_invalid( form)

Renders a response, providing the invalid form as context.

get_context_data( **kwargs)

Populates a context containing the contents of kwargs.

Context

  • form: The form instance that was generated for the view.

Note

Views mixing FormMixin must provide an implementation of form_valid() and form_invalid().

ModelFormMixin

class  ModelFormMixin

A form mixin that works on ModelForms, rather than a standalone form.

Since this is a subclass of SingleObjectMixin, instances of this mixin have access to the model and queryset attributes, describing the type of object that the ModelForm is manipulating. The view also provides self.object, the instance being manipulated. If the instance is being created, self.object will be None

Mixins

  • django.views.generic.forms.FormMixin
  • django.views.generic.detail.SingleObjectMixin
success_url

The URL to redirect to when the form is successfully processed.

success_url may contain dictionary string formatting, which will be interpolated against the object's field attributes. For example, you could use success_url="/polls/%(slug)s/" to redirect to a URL composed out of the slug field on a model.

get_form_class()

Retrieve the form class to instantiate. If FormMixin.form_class is provided, that class will be used. Otherwise, a ModelForm will be instantiated using the model associated with the queryset, or with the model, depending on which attribute is provided.

get_form_kwargs()

Add the current instance (self.object) to the standard FormMixin.get_form_kwargs().

get_success_url()

Determine the URL to redirect to when the form is successfully validated. Returns FormMixin.success_url if it is provided; otherwise, attempts to use the get_absolute_url() of the object.

form_valid()

Saves the form instance, sets the current object for the view, and redirects to get_success_url().

form_invalid()

Renders a response, providing the invalid form as context.

ProcessFormView

class  ProcessFormView

A mixin that provides basic HTTP GET and POST workflow.

get( request*args**kwargs)

Constructs a form, then renders a response using a context that contains that form.

post( request*args**kwargs)

Constructs a form, checks the form for validity, and handles it accordingly.

The PUT action is also handled, as an analog of POST.

DeletionMixin

class  DeletionMixin

Enables handling of the DELETE http action.

success_url

The url to redirect to when the nominated object has been successfully deleted.

get_success_url( obj)

Returns the url to redirect to when the nominated object has been successfully deleted. Returns success_url by default.

Date-based mixins

YearMixin

class  YearMixin

A mixin that can be used to retrieve and provide parsing information for a year component of a date.

year_format

The strftime format to use when parsing the year. By default, this is '%Y'.

year

Optional The value for the year (as a string). By default, set to None, which means the year will be determined using other means.

get_year_format()

Returns the strftime format to use when parsing the year. Returns YearMixin.year_format by default.

get_year()

Returns the year for which this view will display data. Tries the following sources, in order:

  • The value of the YearMixin.year attribute.
  • The value of the year argument captured in the URL pattern
  • The value of the year GET query argument.

Raises a 404 if no valid year specification can be found.

MonthMixin

class  MonthMixin

A mixin that can be used to retrieve and provide parsing information for a month component of a date.

month_format

The strftime format to use when parsing the month. By default, this is '%b'.

month

Optional The value for the month (as a string). By default, set to None, which means the month will be determined using other means.

get_month_format()

Returns the strftime format to use when parsing the month. Returns MonthMixin.month_format by default.

get_month()

Returns the month for which this view will display data. Tries the following sources, in order:

  • The value of the MonthMixin.month attribute.
  • The value of the month argument captured in the URL pattern
  • The value of the month GET query argument.

Raises a 404 if no valid month specification can be found.

get_next_month( date)

Returns a date object containing the first day of the month after the date provided. Returns None if mixed with a view that sets allow_future = False, and the next month is in the future. If allow_empty = False, returns the next month that contains data.

get_prev_month( date)

Returns a date object containing the first day of the month before the date provided. If allow_empty = False, returns the previous month that contained data.

DayMixin

class  DayMixin

A mixin that can be used to retrieve and provide parsing information for a day component of a date.

day_format

The strftime format to use when parsing the day. By default, this is '%d'.

day

Optional The value for the day (as a string). By default, set to None, which means the day will be determined using other means.

get_day_format()

Returns the strftime format to use when parsing the day. Returns DayMixin.day_format by default.

get_day()

Returns the day for which this view will display data. Tries the following sources, in order:

  • The value of the DayMixin.day attribute.
  • The value of the day argument captured in the URL pattern
  • The value of the day GET query argument.

Raises a 404 if no valid day specification can be found.

get_next_day( date)

Returns a date object containing the next day after the date provided. Returns None if mixed with a view that setsallow_future = False, and the next day is in the future. If allow_empty = False, returns the next day that contains data.

get_prev_day( date)

Returns a date object containing the previous day. If allow_empty = False, returns the previous day that contained data.

WeekMixin

class  WeekMixin

A mixin that can be used to retrieve and provide parsing information for a week component of a date.

week_format

The strftime format to use when parsing the week. By default, this is '%U'.

week

Optional The value for the week (as a string). By default, set to None, which means the week will be determined using other means.

get_week_format()

Returns the strftime format to use when parsing the week. Returns WeekMixin.week_format by default.

get_week()

Returns the week for which this view will display data. Tries the following sources, in order:

  • The value of the WeekMixin.week attribute.
  • The value of the week argument captured in the URL pattern
  • The value of the week GET query argument.

Raises a 404 if no valid week specification can be found.

DateMixin

class  DateMixin

A mixin class providing common behavior for all date-based views.

date_field

The name of the DateField or DateTimeField in the QuerySet's model that the date-based archive should use to determine the objects on the page.

allow_future

A boolean specifying whether to include "future" objects on this page, where "future" means objects in which the field specified in date_field is greater than the current date/time. By default, this is False.

get_date_field()

Returns the name of the field that contains the date data that this view will operate on. Returns DateMixin.date_field by default.

get_allow_future()

Determine whether to include "future" objects on this page, where "future" means objects in which the field specified indate_field is greater than the current date/time. Returns DateMixin.date_field by default.

BaseDateListView

class  BaseDateListView

A base class that provides common behavior for all date-based views. There won't normally be a reason to instantiateBaseDateListView; instantiate one of the subclasses instead.

While this view (and it's subclasses) are executing, self.object_list will contain the list of objects that the view is operating upon, and self.date_list will contain the list of dates for which data is available.

Mixins

  • DateMixin
  • MultipleObjectMixin
allow_empty

A boolean specifying whether to display the page if no objects are available. If this is False and no objects are available, the view will raise a 404 instead of displaying an empty page. By default, this is True.

get_dated_items():

Returns a 3-tuple containing (date_listlatestextra_context).

date_list is the list of dates for which data is available. object_list is the list of objects extra_context is a dictionary of context data that will be added to any context data provided by the MultipleObjectMixin.

get_dated_queryset( **lookup)

Returns a queryset, filtered using the query arguments defined by lookup. Enforces any restrictions on the queryset, such as allow_empty and allow_future.

get_date_list( querysetdate_type)

Returns the list of dates of type date_type for which queryset contains entries. For example, get_date_list(qs, 'year') will return the list of years for which qs has entries. See dates() for the ways that the date_type argument can be used.

Generic views

Simple generic views

View

class  View

The master class-based base view. All other generic class-based views inherit from this base class.

Each request served by a View has an independent state; therefore, it is safe to store state variables on the instance (i.e.,self.foo = 3 is a thread-safe operation).

A class-based view is deployed into a URL pattern using the as_view() classmethod:

urlpatterns = patterns('',         (r'^view/$', MyView.as_view(size=42)),     ) 

Any argument passed into as_view() will be assigned onto the instance that is used to service a request. Using the previous example, this means that every request on MyView is able to interrogate self.size.

Thread safety with view arguments

Arguments passed to a view are shared between every instance of a view. This means that you shoudn't use a list, dictionary, or any other variable object as an argument to a view. If you did, the actions of one user visiting your view could have an effect on subsequent users visiting the same view.

dispatch( request*args**kwargs)

The view part of the view -- the method that accepts a request argument plus arguments, and returns a HTTP response.

The default implementation will inspect the HTTP method and attempt to delegate to a method that matches the HTTP method; a GET will be delegated to get(), a POST to post(), and so on.

The default implementation also sets requestargs and kwargs as instance variables, so any method on the view can know the full details of the request that was made to invoke the view.

http_method_not_allowed( request*args**kwargs)

If the view was called with HTTP method it doesn't support, this method is called instead.

The default implementation returns HttpResponseNotAllowed with list of allowed methods in plain text.

TemplateView

class  TemplateView

Renders a given template, passing it a {{ params }} template variable, which is a dictionary of the parameters captured in the URL.

Mixins

  • django.views.generic.base.TemplateResponseMixin
template_name

The full name of a template to use.

get_context_data( **kwargs)

Return a context data dictionary consisting of the contents of kwargs stored in the context variable params.

Context

  • params: The dictionary of keyword arguments captured from the URL pattern that served the view.

RedirectView

class  RedirectView

Redirects to a given URL.

The given URL may contain dictionary-style string formatting, which will be interpolated against the parameters captured in the URL. Because keyword interpolation is always done (even if no arguments are passed in), any "%" characters in the URL must be written as "%%" so that Python will convert them to a single percent sign on output.

If the given URL is None, Django will return an HttpResponseGone (410).

url

The URL to redirect to, as a string. Or None to raise a 410 (Gone) HTTP error.

permanent

Whether the redirect should be permanent. The only difference here is the HTTP status code returned. If True, then the redirect will use status code 301. If False, then the redirect will use status code 302. By default, permanent is True.

query_string

Whether to pass along the GET query string to the new location. If True, then the query string is appended to the URL. IfFalse, then the query string is discarded. By default, query_string is False.

get_redirect_url( **kwargs)

Constructs the target URL for redirection.

The default implementation uses url as a starting string, performs expansion of % parameters in that string, as well as the appending of query string if requested by query_string. Subclasses may implement any behavior they wish, as long as the method returns a redirect-ready URL string.

Detail views

DetailView

class  BaseDetailView
class  DetailView

A page representing an individual object.

While this view is executing, self.object will contain the object that the view is operating upon.

BaseDetailView implements the same behavior as DetailView, but doesn't include the SingleObjectTemplateResponseMixin.

Mixins

  • django.views.generic.detail.SingleObjectMixin
  • django.views.generic.detail.SingleObjectTemplateResponseMixin

List views

ListView

class  BaseListView
class  ListView

A page representing a list of objects.

While this view is executing, self.object_list will contain the list of objects (usually, but not necessarily a queryset) that the view is operating upon.

BaseListView implements the same behavior as ListView, but doesn't include the MultipleObjectTemplateResponseMixin.

Mixins

  • django.views.generic.list.MultipleObjectMixin
  • django.views.generic.list.MultipleObjectTemplateResponseMixin

Editing views

FormView

class  BaseFormView
class  FormView

A view that displays a form. On error, redisplays the form with validation errors; on success, redirects to a new URL.

BaseFormView implements the same behavior as FormView, but doesn't include the TemplateResponseMixin.

Mixins

  • django.views.generic.edit.FormMixin
  • django.views.generic.edit.ProcessFormView

CreateView

class  BaseCreateView
class  CreateView

A view that displays a form for creating an object, redisplaying the form with validation errors (if there are any) and saving the object.

BaseCreateView implements the same behavior as CreateView, but doesn't include the TemplateResponseMixin.

Mixins

  • django.views.generic.edit.ModelFormMixin
  • django.views.generic.edit.ProcessFormView

UpdateView

class  BaseUpdateView
class  UpdateView

A view that displays a form for editing an existing object, redisplaying the form with validation errors (if there are any) and saving changes to the object. This uses a form automatically generated from the object's model class (unless a form class is manually specified).

BaseUpdateView implements the same behavior as UpdateView, but doesn't include the TemplateResponseMixin.

Mixins

  • django.views.generic.edit.ModelFormMixin
  • django.views.generic.edit.ProcessFormView

DeleteView

class  BaseDeleteView
class  DeleteView

A view that displays a confirmation page and deletes an existing object. The given object will only be deleted if the request method is POST. If this view is fetched via GET, it will display a confirmation page that should contain a form that POSTs to the same URL.

BaseDeleteView implements the same behavior as DeleteView, but doesn't include the TemplateResponseMixin.

Mixins

  • django.views.generic.edit.DeletionMixin
  • django.views.generic.detail.BaseDetailView

Notes

  • The delete confirmation page displayed to a GET request uses a template_name_suffix of '_confirm_delete'.

Date-based views

Date-based generic views (in the module django.views.generic.dates) are views for displaying drilldown pages for date-based data.

ArchiveIndexView

class  BaseArchiveIndexView
class  ArchiveIndexView

A top-level index page showing the "latest" objects, by date. Objects with a date in the future are not included unless you set allow_future to True.

BaseArchiveIndexView implements the same behavior as ArchiveIndexView, but doesn't include theMultipleObjectTemplateResponseMixin.

Mixins

  • django.views.generic.dates.BaseDateListView
  • django.views.generic.list.MultipleObjectTemplateResponseMixin

Notes

  • Uses a default context_object_name of latest.
  • Uses a default template_name_suffix of _archive.

YearArchiveView

class  BaseYearArchiveView
class  YearArchiveView

A yearly archive page showing all available months in a given year. Objects with a date in the future are not displayed unless you set allow_future to True.

BaseYearArchiveView implements the same behavior as YearArchiveView, but doesn't include theMultipleObjectTemplateResponseMixin.

Mixins

  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.dates.YearMixin
  • django.views.generic.dates.BaseDateListView
make_object_list

A boolean specifying whether to retrieve the full list of objects for this year and pass those to the template. If True, the list of objects will be made available to the context. By default, this is False.

get_make_object_list()

Determine if an object list will be returned as part of the context. If False, the None queryset will be used as the object list.

Context

In addition to the context provided by django.views.generic.list.MultipleObjectMixin (viadjango.views.generic.dates.BaseDateListView), the template's context will be:

  • date_list: A DateQuerySet object containing all months that have objects available according to queryset, represented asdatetime.datetime objects, in ascending order.
  • year: The given year, as a four-character string.

Notes

  • Uses a default template_name_suffix of _archive_year.

MonthArchiveView

class  BaseMonthArchiveView
class  MonthArchiveView

A monthly archive page showing all objects in a given month. Objects with a date in the future are not displayed unless you set allow_future to True.

BaseMonthArchiveView implements the same behavior as MonthArchiveView, but doesn't include theMultipleObjectTemplateResponseMixin.

Mixins

  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.dates.YearMixin
  • django.views.generic.dates.MonthMixin
  • django.views.generic.dates.BaseDateListView

Context

In addition to the context provided by MultipleObjectMixin (via BaseDateListView), the template's context will be:

  • date_list: A DateQuerySet object containing all days that have objects available in the given month, according to queryset, represented as datetime.datetime objects, in ascending order.
  • month: A datetime.date object representing the given month.
  • next_month: A datetime.date object representing the first day of the next month. If the next month is in the future, this will be None.
  • previous_month: A datetime.date object representing the first day of the previous month. Unlike next_month, this will never be None.

Notes

  • Uses a default template_name_suffix of _archive_month.

WeekArchiveView

class  BaseWeekArchiveView
class  WeekArchiveView

A weekly archive page showing all objects in a given week. Objects with a date in the future are not displayed unless you set allow_future to True.

BaseWeekArchiveView implements the same behavior as WeekArchiveView, but doesn't include theMultipleObjectTemplateResponseMixin.

Mixins

  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.dates.YearMixin
  • django.views.generic.dates.MonthMixin
  • django.views.generic.dates.BaseDateListView

Context

In addition to the context provided by MultipleObjectMixin (via BaseDateListView), the template's context will be:

  • week: A datetime.date object representing the first day of the given week.

Notes

  • Uses a default template_name_suffix of _archive_week.

DayArchiveView

class  BaseDayArchiveView
class  DayArchiveView

A day archive page showing all objects in a given day. Days in the future throw a 404 error, regardless of whether any objects exist for future days, unless you set allow_future to True.

BaseDayArchiveView implements the same behavior as DayArchiveView, but doesn't include theMultipleObjectTemplateResponseMixin.

Mixins

  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.dates.YearMixin
  • django.views.generic.dates.MonthMixin
  • django.views.generic.dates.DayMixin
  • django.views.generic.dates.BaseDateListView

Context

In addition to the context provided by MultipleObjectMixin (via BaseDateListView), the template's context will be:

  • day: A datetime.date object representing the given day.
  • next_day: A datetime.date object representing the next day. If the next day is in the future, this will be None.
  • previous_day: A datetime.date object representing the previous day. Unlike next_day, this will never be None.
  • next_month: A datetime.date object representing the first day of the next month. If the next month is in the future, this will be None.
  • previous_month: A datetime.date object representing the first day of the previous month. Unlike next_month, this will never be None.

Notes

  • Uses a default template_name_suffix of _archive_day.

TodayArchiveView

class  BaseTodayArchiveView
class  TodayArchiveView

A day archive page showing all objects for today. This is exactly the same as archive_day, except the year/month/dayarguments are not used,

BaseTodayArchiveView implements the same behavior as TodayArchiveView, but doesn't include theMultipleObjectTemplateResponseMixin.

Mixins

  • django.views.generic.dates.DayArchiveView

DateDetailView

class  BaseDateDetailView
class  DateDetailView

A page representing an individual object. If the object has a date value in the future, the view will throw a 404 error by default, unless you set allow_future to True.

BaseDateDetailView implements the same behavior as DateDetailView, but doesn't include the SingleObjectTemplateResponseMixin.

Mixins

  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.dates.YearMixin
  • django.views.generic.dates.MonthMixin
  • django.views.generic.dates.DayMixin
  • django.views.generic.dates.BaseDateListView

转载于:https://www.cnblogs.com/rdRoad/archive/2012/02/01/2335162.html

你可能感兴趣的:(django学习笔记——基于类的通用视图(reference))