From c4c7fbcc0d9264beb931b45969fc0d8d655c4f83 Mon Sep 17 00:00:00 2001 From: Jannis Leidel Date: Mon, 11 Jun 2012 10:34:00 +0200 Subject: Fixed #18451 -- Vastly improved class based view documentation. Many thanks to Daniel Greenfeld, James Aylett, Marc Tamlyn, Simon Williams, Danilo Bargen and Luke Plant for their work on this. --- docs/ref/class-based-views.txt | 1367 -------------------- docs/ref/class-based-views/base.txt | 224 ++++ docs/ref/class-based-views/generic-date-based.txt | 273 ++++ docs/ref/class-based-views/generic-display.txt | 86 ++ docs/ref/class-based-views/generic-editing.txt | 78 ++ docs/ref/class-based-views/index.txt | 59 + docs/ref/class-based-views/mixins-date-based.txt | 256 ++++ docs/ref/class-based-views/mixins-editing.txt | 183 +++ .../class-based-views/mixins-multiple-object.txt | 175 +++ docs/ref/class-based-views/mixins-simple.txt | 60 + .../ref/class-based-views/mixins-single-object.txt | 124 ++ docs/ref/class-based-views/mixins.txt | 14 + docs/ref/index.txt | 2 +- 13 files changed, 1533 insertions(+), 1368 deletions(-) delete mode 100644 docs/ref/class-based-views.txt create mode 100644 docs/ref/class-based-views/base.txt create mode 100644 docs/ref/class-based-views/generic-date-based.txt create mode 100644 docs/ref/class-based-views/generic-display.txt create mode 100644 docs/ref/class-based-views/generic-editing.txt create mode 100644 docs/ref/class-based-views/index.txt create mode 100644 docs/ref/class-based-views/mixins-date-based.txt create mode 100644 docs/ref/class-based-views/mixins-editing.txt create mode 100644 docs/ref/class-based-views/mixins-multiple-object.txt create mode 100644 docs/ref/class-based-views/mixins-simple.txt create mode 100644 docs/ref/class-based-views/mixins-single-object.txt create mode 100644 docs/ref/class-based-views/mixins.txt (limited to 'docs/ref') diff --git a/docs/ref/class-based-views.txt b/docs/ref/class-based-views.txt deleted file mode 100644 index acd9db2d66..0000000000 --- a/docs/ref/class-based-views.txt +++ /dev/null @@ -1,1367 +0,0 @@ -========================= -Class-based generic views -========================= - -.. versionadded:: 1.3 - -.. note:: - Prior to Django 1.3, generic views were implemented as functions. The - function-based implementation has been removed in favor of the - class-based approach described here. - -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 -:doc:`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 :doc:`/topics/db/queries` for more information about ``QuerySet`` -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. - -For example, the :class:`~django.views.generic.base.detail.DetailView` -is composed from: - -* :class:`~django.db.views.generic.base.View`, which provides the - basic class-based behavior -* :class:`~django.db.views.generic.detail.SingleObjectMixin`, which - provides the utilities for retrieving and displaying a single object -* :class:`~django.db.views.generic.detail.SingleObjectTemplateResponseMixin`, - which provides the tools for rendering a single object into a - template-based response. - -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. - -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. - -.. 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 -------------- - -.. currentmodule:: django.views.generic.base - -TemplateResponseMixin -~~~~~~~~~~~~~~~~~~~~~ -.. class:: TemplateResponseMixin() - - .. attribute:: template_name - - The path to the template to use when rendering the view. - - .. attribute:: response_class - - The response class to be returned by ``render_to_response`` method. - Default is - :class:`TemplateResponse `. - The template and context of ``TemplateResponse`` instances can be - altered later (e.g. in - :ref:`template response middleware `). - - If you need custom template loading or custom context object - instantiation, create a ``TemplateResponse`` subclass and assign it to - ``response_class``. - - .. method:: render_to_response(context, **response_kwargs) - - Returns a ``self.response_class`` instance. - - If any keyword arguments are provided, they will be - passed to the constructor of the response class. - - Calls :meth:`~TemplateResponseMixin.get_template_names()` to obtain the - list of template names that will be searched looking for an existent - template. - - .. method:: get_template_names() - - Returns a list of template names to search for when rendering the - template. - - If :attr:`TemplateResponseMixin.template_name` is specified, the - default implementation will return a list containing - :attr:`TemplateResponseMixin.template_name` (if it is specified). - - -Single object mixins --------------------- - -.. currentmodule:: django.views.generic.detail - -SingleObjectMixin -~~~~~~~~~~~~~~~~~ -.. class:: SingleObjectMixin() - - .. attribute:: model - - The model that this view will display data for. Specifying ``model - = Foo`` is effectively the same as specifying ``queryset = - Foo.objects.all()``. - - .. attribute:: queryset - - A ``QuerySet`` that represents the objects. If provided, the value of - :attr:`SingleObjectMixin.queryset` supersedes the value provided for - :attr:`SingleObjectMixin.model`. - - .. attribute:: slug_field - - The name of the field on the model that contains the slug. By default, - ``slug_field`` is ``'slug'``. - - .. attribute:: slug_url_kwarg - - .. versionadded:: 1.4 - - The name of the URLConf keyword argument that contains the slug. By - default, ``slug_url_kwarg`` is ``'slug'``. - - .. attribute:: pk_url_kwarg - - .. versionadded:: 1.4 - - The name of the URLConf keyword argument that contains the primary key. - By default, ``pk_url_kwarg`` is ``'pk'``. - - .. attribute:: context_object_name - - Designates the name of the variable to use in the context. - - .. method:: 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, - :meth:`~SingleObjectMixin.get_queryset` will be used. - ``get_object()`` looks for a - :attr:`SingleObjectMixin.pk_url_kwarg` argument in the arguments - to the view; if this argument is found, this method performs a - primary-key based lookup using that value. If this argument is not - found, it looks for a :attr:`SingleObjectMixin.slug_url_kwarg` - argument, and performs a slug lookup using the - :attr:`SingleObjectMixin.slug_field`. - - .. method:: get_queryset() - - Returns the queryset that will be used to retrieve the object that - this view will display. By default, - :meth:`~SingleObjectMixin.get_queryset` returns the value of the - :attr:`~SingleObjectMixin.queryset` attribute if it is set, otherwise - it constructs a :class:`QuerySet` by calling the `all()` method on the - :attr:`~SingleObjectMixin.model` attribute's default manager. - - .. method:: get_context_object_name(obj) - - Return the context variable name that will be used to contain the - data that this view is manipulating. If - :attr:`~SingleObjectMixin.context_object_name` is 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'``. - - .. method:: get_context_data(**kwargs) - - Returns context data for displaying the list of objects. - - **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.object`` will 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** - - * :class:`~django.views.generic.base.TemplateResponseMixin` - - .. attribute:: template_name_field - - The field on the current object instance that can be used to determine - the name of a candidate template. If either ``template_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. - - .. attribute:: template_name_suffix - - The suffix to append to the auto-generated candidate template name. - Default suffix is ``_detail``. - - .. method:: 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 ----------------------- - -.. currentmodule:: django.views.generic.list - -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 :doc:`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. - - .. attribute:: 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``. - - .. attribute:: model - - The model that this view will display data for. Specifying ``model - = Foo`` is effectively the same as specifying ``queryset = - Foo.objects.all()``. - - .. attribute:: queryset - - A ``QuerySet`` that represents the objects. If provided, the value of - :attr:`MultipleObjectMixin.queryset` supersedes the value provided for - :attr:`MultipleObjectMixin.model`. - - .. attribute:: paginate_by - - An integer specifying how many objects should be displayed per page. If - this is given, the view will paginate objects with - :attr:`MultipleObjectMixin.paginate_by` objects per page. The view will - expect either a ``page`` query string parameter (via ``GET``) or a - ``page`` variable specified in the URLconf. - - .. attribute:: paginator_class - - The paginator class to be used for pagination. By default, - :class:`django.core.paginator.Paginator` is used. If the custom paginator - class doesn't have the same constructor interface as - :class:`django.core.paginator.Paginator`, you will also need to - provide an implementation for :meth:`MultipleObjectMixin.get_paginator`. - - .. attribute:: context_object_name - - Designates the name of the variable to use in the context. - - .. method:: get_queryset() - - Returns the queryset that represents the data this view will display. - - .. method:: paginate_queryset(queryset, page_size) - - Returns a 4-tuple containing (``paginator``, ``page``, ``object_list``, - ``is_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. - - .. method:: get_paginate_by(queryset) - - Returns the number of items to paginate by, or ``None`` for no - pagination. By default this simply returns the value of - :attr:`MultipleObjectMixin.paginate_by`. - - .. method:: get_paginator(queryset, per_page, orphans=0, allow_empty_first_page=True) - - Returns an instance of the paginator to use for this view. By default, - instantiates an instance of :attr:`paginator_class`. - - .. method:: 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``. - - .. method:: 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_list`` is a queryset of Django objects and - :attr:`~MultipleObjectMixin.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``. - - .. method:: 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 - :class:`django.core.paginator.Paginator`. If the page is not - paginated, this context variable will be ``None``. - - * ``page_obj``: An instance of - :class:`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 :class:`~django.db.models.query.QuerySet`. - - **Extends** - - * :class:`~django.views.generic.base.TemplateResponseMixin` - - .. attribute:: template_name_suffix - - The suffix to append to the auto-generated candidate template name. - Default suffix is ``_list``. - - .. method:: 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 --------------- - -.. currentmodule:: django.views.generic.edit - -FormMixin -~~~~~~~~~ -.. class:: FormMixin() - - A mixin class that provides facilities for creating and displaying forms. - - .. attribute:: initial - - A dictionary containing initial data for the form. - - .. attribute:: form_class - - The form class to instantiate. - - .. attribute:: success_url - - The URL to redirect to when the form is successfully processed. - - .. method:: get_initial() - - Retrieve initial data for the form. By default, returns a copy of - :attr:`.initial`. - - .. admonition:: Changed in 1.4 - - In Django 1.3, this method was returning the :attr:`initial` class - variable itself. - - .. method:: get_form_class() - - Retrieve the form class to instantiate. By default - :attr:`.form_class`. - - .. method:: get_form(form_class) - - Instantiate an instance of ``form_class`` using - :meth:`.get_form_kwargs`. - - .. method:: get_form_kwargs() - - Build the keyword arguments required to instantiate the form. - - The ``initial`` argument is set to :meth:`.get_initial`. If the - request is a ``POST`` or ``PUT``, the request data (``request.POST`` - and ``request.FILES``) will also be provided. - - .. method:: get_success_url() - - Determine the URL to redirect to when the form is successfully - validated. Returns :attr:`.success_url` by default. - - .. method:: form_valid(form) - - Redirects to :meth:`.get_success_url`. - - .. method:: form_invalid(form) - - Renders a response, providing the invalid form as context. - - .. method:: 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 :class:`FormMixin` must - provide an implementation of :meth:`.form_valid` and - :meth:`.form_invalid`. - -ModelFormMixin -~~~~~~~~~~~~~~ -.. class:: ModelFormMixin() - - A form mixin that works on ModelForms, rather than a standalone form. - - Since this is a subclass of - :class:`~django.views.generic.detail.SingleObjectMixin`, instances of this - mixin have access to the :attr:`~SingleObjectMixin.model` and - :attr:`~SingleObjectMixin.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** - - * :class:`django.views.generic.edit.FormMixin` - * :class:`django.views.generic.detail.SingleObjectMixin` - - .. attribute:: 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. - - .. method:: get_form_class() - - Retrieve the form class to instantiate. If - :attr:`FormMixin.form_class` is provided, that class will be used. - Otherwise, a ModelForm will be instantiated using the model associated - with the :attr:`~SingleObjectMixin.queryset`, or with the - :attr:`~SingleObjectMixin.model`, depending on which attribute is - provided. - - .. method:: get_form_kwargs() - - Add the current instance (``self.object``) to the standard - :meth:`FormMixin.get_form_kwargs`. - - .. method:: get_success_url() - - Determine the URL to redirect to when the form is successfully - validated. Returns :attr:`FormMixin.success_url` if it is provided; - otherwise, attempts to use the ``get_absolute_url()`` of the object. - - .. method:: form_valid(form) - - Saves the form instance, sets the current object for the view, and - redirects to :meth:`.get_success_url`. - - .. method:: form_invalid() - - Renders a response, providing the invalid form as context. - -ProcessFormView -~~~~~~~~~~~~~~~ -.. class:: ProcessFormView() - - A mixin that provides basic HTTP GET and POST workflow. - - .. method:: get(request, *args, **kwargs) - - Constructs a form, then renders a response using a context that - contains that form. - - .. method:: 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. - - .. attribute:: success_url - - The url to redirect to when the nominated object has been - successfully deleted. - - .. method:: get_success_url(obj) - - Returns the url to redirect to when the nominated object has been - successfully deleted. Returns - :attr:`~django.views.generic.edit.DeletionMixin.success_url` by - default. - -Date-based mixins ------------------ - -.. currentmodule:: django.views.generic.dates - -YearMixin -~~~~~~~~~ -.. class:: YearMixin() - - A mixin that can be used to retrieve and provide parsing information for a - year component of a date. - - .. attribute:: year_format - - The :func:`~time.strftime` format to use when parsing the year. - By default, this is ``'%Y'``. - - .. attribute:: 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. - - .. method:: get_year_format() - - Returns the :func:`~time.strftime` format to use when parsing the year. Returns - :attr:`YearMixin.year_format` by default. - - .. method:: get_year() - - Returns the year for which this view will display data. Tries the - following sources, in order: - - * The value of the :attr:`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. - - .. attribute:: month_format - - The :func:`~time.strftime` format to use when parsing the month. By default, this is - ``'%b'``. - - .. attribute:: 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. - - .. method:: get_month_format() - - Returns the :func:`~time.strftime` format to use when parsing the month. Returns - :attr:`MonthMixin.month_format` by default. - - .. method:: get_month() - - Returns the month for which this view will display data. Tries the - following sources, in order: - - * The value of the :attr:`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. - - .. method:: 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. - - .. method:: 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. - - .. attribute:: day_format - - The :func:`~time.strftime` format to use when parsing the day. By default, this is - ``'%d'``. - - .. attribute:: 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. - - .. method:: get_day_format() - - Returns the :func:`~time.strftime` format to use when parsing the day. Returns - :attr:`DayMixin.day_format` by default. - - .. method:: get_day() - - Returns the day for which this view will display data. Tries the - following sources, in order: - - * The value of the :attr:`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. - - .. method:: get_next_day(date) - - Returns a date object containing the next day after the date provided. - Returns ``None`` if mixed with a view that sets ``allow_future = False``, - and the next day is in the future. If ``allow_empty = False``, returns - the next day that contains data. - - .. method:: 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. - - .. attribute:: week_format - - The :func:`~time.strftime` format to use when parsing the week. By default, this is - ``'%U'``. - - .. attribute:: 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. - - .. method:: get_week_format() - - Returns the :func:`~time.strftime` format to use when parsing the week. Returns - :attr:`WeekMixin.week_format` by default. - - .. method:: get_week() - - Returns the week for which this view will display data. Tries the - following sources, in order: - - * The value of the :attr:`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. - - .. attribute:: 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. - - When :doc:`time zone support ` is enabled and - ``date_field`` is a ``DateTimeField``, dates are assumed to be in the - current time zone. Otherwise, the queryset could include objects from - the previous or the next day in the end user's time zone. - - .. warning:: - - In this situation, if you have implemented per-user time zone - selection, the same URL may show a different set of objects, - depending on the end user's time zone. To avoid this, you should - use a ``DateField`` as the ``date_field`` attribute. - - .. attribute:: 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``. - - .. method:: get_date_field() - - Returns the name of the field that contains the date data that this - view will operate on. Returns :attr:`DateMixin.date_field` by default. - - .. method:: get_allow_future() - - Determine 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. Returns - :attr:`DateMixin.allow_future` 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 instantiate - :class:`~django.views.generic.dates.BaseDateListView`; 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** - - * :class:`~django.views.generic.dates.DateMixin` - * :class:`~django.views.generic.list.MultipleObjectMixin` - - .. attribute:: allow_empty - - A boolean specifying whether to display the page if no objects are - available. If this is ``True`` and no objects are available, the view - will display an empty page instead of raising a 404. By default, this - is ``False``. - - .. method:: get_dated_items(): - - Returns a 3-tuple containing (``date_list``, ``object_list``, - ``extra_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 - :class:`~django.views.generic.list.MultipleObjectMixin`. - - .. method:: 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``. - - .. method:: get_date_list(queryset, date_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 :meth:`~django.db.models.query.QuerySet.dates()` for the - ways that the ``date_type`` argument can be used. - - -Generic views -============= - -Simple generic views --------------------- - -.. currentmodule:: django.views.generic.base - -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 :class:`~django.views.generic.base.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 - :meth:`~View.as_view()` classmethod:: - - urlpatterns = patterns('', - (r'^view/$', MyView.as_view(size=42)), - ) - - Any argument passed into :meth:`~View.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``. - - .. admonition:: 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. - - .. method:: 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 :meth:`~View.get()`, a ``POST`` to :meth:`~View.post()`, - and so on. - - The default implementation also sets ``request``, ``args`` 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. - - .. method:: 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** - - * :class:`django.views.generic.base.TemplateResponseMixin` - - .. attribute:: template_name - - The full name of a template to use. - - .. method:: 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). - - .. attribute:: url - - The URL to redirect to, as a string. Or ``None`` to raise a 410 (Gone) - HTTP error. - - .. attribute:: 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``. - - .. attribute:: 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. If ``False``, - then the query string is discarded. By default, ``query_string`` is - ``False``. - - .. method:: get_redirect_url(**kwargs) - - Constructs the target URL for redirection. - - The default implementation uses :attr:`~RedirectView.url` as a starting - string, performs expansion of ``%`` parameters in that string, as well - as the appending of query string if requested by - :attr:`~RedirectView.query_string`. Subclasses may implement any - behavior they wish, as long as the method returns a redirect-ready URL - string. - -Detail views ------------- - -.. currentmodule:: django.views.generic.detail - -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. - - :class:`~django.views.generic.base.BaseDetailView` implements the same - behavior as :class:`~django.views.generic.base.DetailView`, but doesn't - include the - :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`. - - **Mixins** - - * :class:`django.views.generic.detail.SingleObjectMixin` - * :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin` - -List views ----------- - -.. currentmodule:: django.views.generic.list - -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. - - :class:`~django.views.generic.list.BaseListView` implements the same - behavior as :class:`~django.views.generic.list.ListView`, but doesn't - include the - :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`. - - **Mixins** - - * :class:`django.views.generic.list.MultipleObjectMixin` - * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin` - - -Editing views -------------- - -.. currentmodule:: django.views.generic.edit - -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. - - :class:`~django.views.generic.edit.BaseFormView` implements the same - behavior as :class:`~django.views.generic.edit.FormView`, but doesn't - include the :class:`~django.views.generic.base.TemplateResponseMixin`. - - **Mixins** - - * :class:`django.views.generic.edit.FormMixin` - * :class:`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. - - :class:`~django.views.generic.edit.BaseCreateView` implements the same - behavior as :class:`~django.views.generic.edit.CreateView`, but doesn't - include the :class:`~django.views.generic.base.TemplateResponseMixin`. - - **Mixins** - - * :class:`django.views.generic.edit.ModelFormMixin` - * :class:`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). - - :class:`~django.views.generic.edit.BaseUpdateView` implements the same - behavior as :class:`~django.views.generic.edit.UpdateView`, but doesn't - include the :class:`~django.views.generic.base.TemplateResponseMixin`. - - **Mixins** - - * :class:`django.views.generic.edit.ModelFormMixin` - * :class:`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. - - :class:`~django.views.generic.edit.BaseDeleteView` implements the same - behavior as :class:`~django.views.generic.edit.DeleteView`, but doesn't - include the :class:`~django.views.generic.base.TemplateResponseMixin`. - - **Mixins** - - * :class:`django.views.generic.edit.DeletionMixin` - * :class:`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 :mod:`django.views.generic.dates`) -are views for displaying drilldown pages for date-based data. - -.. currentmodule:: django.views.generic.dates - -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``. - - :class:`~django.views.generic.dates.BaseArchiveIndexView` implements the - same behavior as :class:`~django.views.generic.dates.ArchiveIndexView`, but - doesn't include the - :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`. - - **Mixins** - - * :class:`django.views.generic.dates.BaseDateListView` - * :class:`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``. - - :class:`~django.views.generic.dates.BaseYearArchiveView` implements the - same behavior as :class:`~django.views.generic.dates.YearArchiveView`, but - doesn't include the - :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`. - - **Mixins** - - * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin` - * :class:`django.views.generic.dates.YearMixin` - * :class:`django.views.generic.dates.BaseDateListView` - - .. attribute:: 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``. - - .. method:: 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 - :class:`django.views.generic.list.MultipleObjectMixin` (via - :class:`django.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 as - ``datetime.datetime`` objects, in ascending order. - - * ``year``: A ``datetime.date`` object representing the given year. - - * ``next_year``: A ``datetime.date`` object representing the first day - of the next year. If the next year is in the future, this will be - ``None``. - - * ``previous_year``: A ``datetime.date`` object representing the first - day of the previous year. Unlike ``next_year``, this will never be - ``None``. - - **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``. - - :class:`~django.views.generic.dates.BaseMonthArchiveView` implements - the same behavior as - :class:`~django.views.generic.dates.MonthArchiveView`, but doesn't - include the - :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`. - - **Mixins** - - * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin` - * :class:`django.views.generic.dates.YearMixin` - * :class:`django.views.generic.dates.MonthMixin` - * :class:`django.views.generic.dates.BaseDateListView` - - **Context** - - In addition to the context provided by - :class:`~django.views.generic.list.MultipleObjectMixin` (via - :class:`~django.views.generic.dates.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``. - - :class:`~django.views.generic.dates.BaseWeekArchiveView` implements the - same behavior as :class:`~django.views.generic.dates.WeekArchiveView`, but - doesn't include the - :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`. - - **Mixins** - - * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin` - * :class:`django.views.generic.dates.YearMixin` - * :class:`django.views.generic.dates.MonthMixin` - * :class:`django.views.generic.dates.BaseDateListView` - - **Context** - - In addition to the context provided by - :class:`~django.views.generic.list.MultipleObjectMixin` (via - :class:`~django.views.generic.dates.BaseDateListView`), the template's - context will be: - - * ``week``: A ``datetime.date`` object representing the first day of - the given week. - - * ``next_week``: A ``datetime.date`` object representing the first day - of the next week. If the next week is in the future, this will be - ``None``. - - * ``previous_week``: A ``datetime.date`` object representing the first - day of the previous week. Unlike ``next_week``, this will never be - ``None``. - - **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``. - - :class:`~django.views.generic.dates.BaseDayArchiveView` implements the same - behavior as :class:`~django.views.generic.dates.DayArchiveView`, but - doesn't include the - :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`. - - **Mixins** - - * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin` - * :class:`django.views.generic.dates.YearMixin` - * :class:`django.views.generic.dates.MonthMixin` - * :class:`django.views.generic.dates.DayMixin` - * :class:`django.views.generic.dates.BaseDateListView` - - **Context** - - In addition to the context provided by - :class:`~django.views.generic.list.MultipleObjectMixin` (via - :class:`~django.views.generic.dates.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 :class:`django.views.generic.dates.DayArchiveView`, except today's - date is used instead of the ``year``/``month``/``day`` arguments. - - :class:`~django.views.generic.dates.BaseTodayArchiveView` implements the - same behavior as :class:`~django.views.generic.dates.TodayArchiveView`, but - doesn't include the - :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`. - - **Mixins** - - * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin` - * :class:`django.views.generic.dates.BaseDayArchiveView` - -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``. - - :class:`~django.views.generic.dates.BaseDateDetailView` implements the same - behavior as :class:`~django.views.generic.dates.DateDetailView`, but - doesn't include the - :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`. - - **Mixins** - - * :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin` - * :class:`django.views.generic.detail.BaseDetailView` - * :class:`django.views.generic.dates.DateMixin` - * :class:`django.views.generic.dates.YearMixin` - * :class:`django.views.generic.dates.MonthMixin` - * :class:`django.views.generic.dates.DayMixin` diff --git a/docs/ref/class-based-views/base.txt b/docs/ref/class-based-views/base.txt new file mode 100644 index 0000000000..5e0360c88f --- /dev/null +++ b/docs/ref/class-based-views/base.txt @@ -0,0 +1,224 @@ +========== +Base views +========== + +The following three classes provide much of the functionality needed to create +Django views. You may think of them as *parent* views, which can be used by +themselves or inherited from. They may not provide all the capabilities +required for projects, in which case there are Mixins and Generic class-based +views. + +.. class:: django.views.generic.base.View + + The master class-based base view. All other class-based views inherit from + this base class. + + **Method Flowchart** + + 1. :meth:`dispatch()` + 2. :meth:`http_method_not_allowed()` + + **Example views.py**:: + + from django.http import HttpResponse + from django.views.generic import View + + class MyView(View): + + def get(self, request, *args, **kwargs): + return HttpResponse('Hello, World!') + + **Example urls.py**:: + + from django.conf.urls import patterns, url + + from myapp.views import MyView + + urlpatterns = patterns('', + url(r'^mine/$', MyView.as_view(), name='my-view'), + ) + + **Methods** + + .. method:: 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 :meth:`~View.get()`, a ``POST`` to :meth:`~View.post()`, + and so on. + + The default implementation also sets ``request``, ``args`` 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. + + .. method:: http_method_not_allowed(request, *args, **kwargs) + + If the view was called with a HTTP method it doesn't support, this + method is called instead. + + The default implementation returns ``HttpResponseNotAllowed`` with list + of allowed methods in plain text. + + .. note:: + + Documentation on class-based views is a work in progress. As yet, only the + methods defined directly on the class are documented here, not methods + defined on superclasses. + +.. class:: django.views.generic.base.TemplateView + + Renders a given template, passing it a ``{{ params }}`` template variable, + which is a dictionary of the parameters captured in the URL. + + **Ancestors (MRO)** + + * :class:`django.views.generic.base.TemplateView` + * :class:`django.views.generic.base.TemplateResponseMixin` + * :class:`django.views.generic.base.View` + + **Method Flowchart** + + 1. :meth:`dispatch()` + 2. :meth:`http_method_not_allowed()` + 3. :meth:`get_context_data()` + + **Example views.py**:: + + from django.views.generic.base import TemplateView + + from articles.models import Article + + class HomePageView(TemplateView): + + template_name = "home.html" + + def get_context_data(self, **kwargs): + context = super(HomePageView, self).get_context_data(**kwargs) + context['latest_articles'] = Article.objects.all()[:5] + return context + + **Example urls.py**:: + + from django.conf.urls import patterns, url + + from myapp.views import HomePageView + + urlpatterns = patterns('', + url(r'^$', HomePageView.as_view(), name='home'), + ) + + **Methods and Attributes** + + .. attribute:: template_name + + The full name of a template to use. + + .. method:: 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. + + .. note:: + + Documentation on class-based views is a work in progress. As yet, only the + methods defined directly on the class are documented here, not methods + defined on superclasses. + +.. class:: django.views.generic.base.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). + + **Ancestors (MRO)** + + * :class:`django.views.generic.base.View` + + **Method Flowchart** + + 1. :meth:`dispatch()` + 2. :meth:`http_method_not_allowed()` + 3. :meth:`get_redirect_url()` + + **Example views.py**:: + + from django.shortcuts import get_object_or_404 + from django.views.generic.base import RedirectView + + from articles.models import Article + + class ArticleCounterRedirectView(RedirectView): + + permanent = False + query_string = True + + def get_redirect_url(self, pk): + article = get_object_or_404(Article, pk=pk) + article.update_counter() + return reverse('product_detail', args=(pk,)) + + **Example urls.py**:: + + from django.conf.urls import patterns, url + from django.views.generic.base import RedirectView + + from article.views import ArticleCounterRedirectView + + urlpatterns = patterns('', + + url(r'r^(?P\d+)/$', ArticleCounterRedirectView.as_view(), name='article-counter'), + url(r'^go-to-django/$', RedirectView.as_view(url='http://djangoproject.com'), name='go-to-django'), + ) + + **Methods and Attributes** + + .. attribute:: url + + The URL to redirect to, as a string. Or ``None`` to raise a 410 (Gone) + HTTP error. + + .. attribute:: 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``. + + .. attribute:: 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. If ``False``, + then the query string is discarded. By default, ``query_string`` is + ``False``. + + .. method:: get_redirect_url(**kwargs) + + Constructs the target URL for redirection. + + The default implementation uses :attr:`~RedirectView.url` as a starting + string, performs expansion of ``%`` parameters in that string, as well + as the appending of query string if requested by + :attr:`~RedirectView.query_string`. Subclasses may implement any + behavior they wish, as long as the method returns a redirect-ready URL + string. + + .. note:: + + Documentation on class-based views is a work in progress. As yet, only the + methods defined directly on the class are documented here, not methods + defined on superclasses. diff --git a/docs/ref/class-based-views/generic-date-based.txt b/docs/ref/class-based-views/generic-date-based.txt new file mode 100644 index 0000000000..69a98df77b --- /dev/null +++ b/docs/ref/class-based-views/generic-date-based.txt @@ -0,0 +1,273 @@ +================== +Generic date views +================== + +Date-based generic views (in the module :mod:`django.views.generic.dates`) +are views for displaying drilldown pages for date-based data. + +.. class:: django.views.generic.dates.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``. + + **Ancestors (MRO)** + + * :class:`django.views.generic.dates.ArchiveIndexView` + * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin` + * :class:`django.views.generic.base.TemplateResponseMixin` + * :class:`django.views.generic.dates.BaseArchiveIndexView` + * :class:`django.views.generic.dates.BaseDateListView` + * :class:`django.views.generic.list.MultipleObjectMixin` + * :class:`django.views.generic.dates.DateMixin` + * :class:`django.views.generic.base.View` + + **Notes** + + * Uses a default ``context_object_name`` of ``latest``. + * Uses a default ``template_name_suffix`` of ``_archive``. + +.. class:: django.views.generic.dates.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``. + + **Ancestors (MRO)** + + * :class:`django.views.generic.dates.YearArchiveView` + * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin` + * :class:`django.views.generic.base.TemplateResponseMixin` + * :class:`django.views.generic.dates.BaseYearArchiveView` + * :class:`django.views.generic.dates.YearMixin` + * :class:`django.views.generic.dates.BaseDateListView` + * :class:`django.views.generic.list.MultipleObjectMixin` + * :class:`django.views.generic.dates.DateMixin` + * :class:`django.views.generic.base.View` + + .. attribute:: 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``. + + .. method:: 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 + :class:`django.views.generic.list.MultipleObjectMixin` (via + :class:`django.views.generic.dates.BaseDateListView`), the template's + context will be: + + * ``date_list``: A + :meth:`DateQuerySet` object object + containing all months that have objects available according to + ``queryset``, represented as + :class:`datetime.datetime` objects, in + ascending order. + + * ``year``: A :class:`datetime.date` object + representing the given year. + + * ``next_year``: A :class:`datetime.date` object + representing the first day of the next year. If the next year is in the + future, this will be ``None``. + + * ``previous_year``: A :class:`datetime.date` object + representing the first day of the previous year. Unlike ``next_year``, + this will never be ``None``. + + **Notes** + + * Uses a default ``template_name_suffix`` of ``_archive_year``. + +.. class:: django.views.generic.dates.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``. + + **Ancestors (MRO)** + + * :class:`django.views.generic.dates.MonthArchiveView` + * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin` + * :class:`django.views.generic.base.TemplateResponseMixin` + * :class:`django.views.generic.dates.BaseMonthArchiveView` + * :class:`django.views.generic.dates.YearMixin` + * :class:`django.views.generic.dates.MonthMixin` + * :class:`django.views.generic.dates.BaseDateListView` + * :class:`django.views.generic.list.MultipleObjectMixin` + * :class:`django.views.generic.dates.DateMixin` + * :class:`django.views.generic.base.View` + + **Context** + + In addition to the context provided by + :class:`~django.views.generic.list.MultipleObjectMixin` (via + :class:`~django.views.generic.dates.BaseDateListView`), the template's + context will be: + + * ``date_list``: A + :meth:`DateQuerySet` object + containing all days that have objects available in the given month, + according to ``queryset``, represented as + :class:`datetime.datetime` objects, in + ascending order. + + * ``month``: A :class:`datetime.date` object + representing the given month. + + * ``next_month``: A :class:`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 :class:`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``. + +.. class:: django.views.generic.dates.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``. + + **Ancestors (MRO)** + + * :class:`django.views.generic.dates.WeekArchiveView` + * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin` + * :class:`django.views.generic.base.TemplateResponseMixin` + * :class:`django.views.generic.dates.BaseWeekArchiveView` + * :class:`django.views.generic.dates.YearMixin` + * :class:`django.views.generic.dates.WeekMixin` + * :class:`django.views.generic.dates.BaseDateListView` + * :class:`django.views.generic.list.MultipleObjectMixin` + * :class:`django.views.generic.dates.DateMixin` + * :class:`django.views.generic.base.View` + + **Context** + + In addition to the context provided by + :class:`~django.views.generic.list.MultipleObjectMixin` (via + :class:`~django.views.generic.dates.BaseDateListView`), the template's + context will be: + + * ``week``: A :class:`datetime.date` object + representing the first day of the given week. + + * ``next_week``: A :class:`datetime.date` object + representing the first day of the next week. If the next week is in the + future, this will be ``None``. + + * ``previous_week``: A :class:`datetime.date` object + representing the first day of the previous week. Unlike ``next_week``, + this will never be ``None``. + + **Notes** + + * Uses a default ``template_name_suffix`` of ``_archive_week``. + +.. class:: django.views.generic.dates.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``. + + **Ancestors (MRO)** + + * :class:`django.views.generic.dates.DayArchiveView` + * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin` + * :class:`django.views.generic.base.TemplateResponseMixin` + * :class:`django.views.generic.dates.BaseDayArchiveView` + * :class:`django.views.generic.dates.YearMixin` + * :class:`django.views.generic.dates.MonthMixin` + * :class:`django.views.generic.dates.DayMixin` + * :class:`django.views.generic.dates.BaseDateListView` + * :class:`django.views.generic.list.MultipleObjectMixin` + * :class:`django.views.generic.dates.DateMixin` + * :class:`django.views.generic.base.View` + + **Context** + + In addition to the context provided by + :class:`~django.views.generic.list.MultipleObjectMixin` (via + :class:`~django.views.generic.dates.BaseDateListView`), the template's + context will be: + + * ``day``: A :class:`datetime.date` object + representing the given day. + + * ``next_day``: A :class:`datetime.date` object + representing the next day. If the next day is in the future, this will be + ``None``. + + * ``previous_day``: A :class:`datetime.date` object + representing the previous day. Unlike ``next_day``, this will never be + ``None``. + + * ``next_month``: A :class:`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 :class:`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``. + +.. class:: django.views.generic.dates.TodayArchiveView + + A day archive page showing all objects for *today*. This is exactly the + same as :class:`django.views.generic.dates.DayArchiveView`, except today's + date is used instead of the ``year``/``month``/``day`` arguments. + + **Ancestors (MRO)** + + * :class:`django.views.generic.dates.TodayArchiveView` + * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin` + * :class:`django.views.generic.base.TemplateResponseMixin` + * :class:`django.views.generic.dates.BaseTodayArchiveView` + * :class:`django.views.generic.dates.BaseDayArchiveView` + * :class:`django.views.generic.dates.YearMixin` + * :class:`django.views.generic.dates.MonthMixin` + * :class:`django.views.generic.dates.DayMixin` + * :class:`django.views.generic.dates.BaseDateListView` + * :class:`django.views.generic.list.MultipleObjectMixin` + * :class:`django.views.generic.dates.DateMixin` + * :class:`django.views.generic.base.View` + +.. class:: django.views.generic.dates.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``. + + **Ancestors (MRO)** + + * :class:`django.views.generic.dates.DateDetailView` + * :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin` + * :class:`django.views.generic.base.TemplateResponseMixin` + * :class:`django.views.generic.dates.BaseDateDetailView` + * :class:`django.views.generic.dates.YearMixin` + * :class:`django.views.generic.dates.MonthMixin` + * :class:`django.views.generic.dates.DayMixin` + * :class:`django.views.generic.dates.DateMixin` + * :class:`django.views.generic.detail.BaseDetailView` + * :class:`django.views.generic.detail.SingleObjectMixin` + * :class:`django.views.generic.base.View` + +.. note:: + + All of the generic views listed above have matching Base* views that only + differ in that the they do not include the + :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`. diff --git a/docs/ref/class-based-views/generic-display.txt b/docs/ref/class-based-views/generic-display.txt new file mode 100644 index 0000000000..8ec66a8cc1 --- /dev/null +++ b/docs/ref/class-based-views/generic-display.txt @@ -0,0 +1,86 @@ +===================== +Generic display views +===================== + +The two following generic class-based views are designed to display data. On +many projects they are typically the most commonly used views. + +.. class:: django.views.generic.detail.DetailView + + While this view is executing, ``self.object`` will contain the object that + the view is operating upon. + + **Ancestors (MRO)** + + * :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin` + * :class:`django.views.generic.base.TemplateResponseMixin` + * :class:`django.views.generic.detail.BaseDetailView` + * :class:`django.views.generic.detail.SingleObjectMixin` + * :class:`django.views.generic.base.View` + + **Method Flowchart** + + 1. :meth:`dispatch()` + 2. :meth:`http_method_not_allowed()` + 3. :meth:`get_template_names()` + 4. :meth:`get_slug_field()` + 5. :meth:`get_queryset()` + 6. :meth:`get_object()` + 7. :meth:`get_context_object_name()` + 8. :meth:`get_context_data()` + 9. :meth:`get()` + 10. :meth:`render_to_response()` + + **Example views.py**:: + + from django.views.generic.detail import DetailView + from django.utils import timezone + + from articles.models import Article + + class ArticleDetailView(DetailView): + + model = Article + + def get_context_data(self, **kwargs): + context = super(ArticleDetailView, self).get_context_data(**kwargs) + context['now'] = timezone.now() + return context + + **Example urls.py**:: + + from django.conf.urls import patterns, url + + from article.views import ArticleDetailView + + urlpatterns = patterns('', + url(r'^(?P[-_\w]+)/$', ArticleDetailView.as_view(), 'article-detail'), + ) + +.. class:: django.views.generic.list.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. + + **Mixins** + + * :class:`django.views.generic.list.ListView` + * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin` + * :class:`django.views.generic.base.TemplateResponseMixin` + * :class:`django.views.generic.list.BaseListView` + * :class:`django.views.generic.list.MultipleObjectMixin` + * :class:`django.views.generic.base.View` + + **Method Flowchart** + + 1. :meth:`dispatch():` + 2. :meth:`http_method_not_allowed():` + 3. :meth:`get_template_names():` + 4. :meth:`get_queryset():` + 5. :meth:`get_objects():` + 6. :meth:`get_context_data():` + 7. :meth:`get():` + 8. :meth:`render_to_response():` diff --git a/docs/ref/class-based-views/generic-editing.txt b/docs/ref/class-based-views/generic-editing.txt new file mode 100644 index 0000000000..d5df369fb3 --- /dev/null +++ b/docs/ref/class-based-views/generic-editing.txt @@ -0,0 +1,78 @@ +===================== +Generic editing views +===================== + +The views described here provide a foundation for editing content. + +.. class:: django.views.generic.edit.FormView + + A view that displays a form. On error, redisplays the form with validation + errors; on success, redirects to a new URL. + + **Ancestors (MRO)** + + * :class:`django.views.generic.edit.FormView` + * :class:`django.views.generic.base.TemplateResponseMixin` + * :class:`django.views.generic.edit.BaseFormView` + * :class:`django.views.generic.edit.FormMixin` + * :class:`django.views.generic.edit.ProcessFormView` + * :class:`django.views.generic.base.View` + +.. class:: django.views.generic.edit.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. + + **Ancestors (MRO)** + + * :class:`django.views.generic.edit.CreateView` + * :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin` + * :class:`django.views.generic.base.TemplateResponseMixin` + * :class:`django.views.generic.edit.BaseCreateView` + * :class:`django.views.generic.edit.ModelFormMixin` + * :class:`django.views.generic.edit.FormMixin` + * :class:`django.views.generic.detail.SingleObjectMixin` + * :class:`django.views.generic.edit.ProcessFormView` + * :class:`django.views.generic.base.View` + +.. class:: django.views.generic.edit.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). + + **Ancestors (MRO)** + + * :class:`django.views.generic.edit.UpdateView` + * :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin` + * :class:`django.views.generic.base.TemplateResponseMixin` + * :class:`django.views.generic.edit.BaseUpdateView` + * :class:`django.views.generic.edit.ModelFormMixin` + * :class:`django.views.generic.edit.FormMixin` + * :class:`django.views.generic.detail.SingleObjectMixin` + * :class:`django.views.generic.edit.ProcessFormView` + * :class:`django.views.generic.base.View` + +.. class:: django.views.generic.edit.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. + + **Ancestors (MRO)** + + * :class:`django.views.generic.edit.DeleteView` + * :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin` + * :class:`django.views.generic.base.TemplateResponseMixin` + * :class:`django.views.generic.edit.BaseDeleteView` + * :class:`django.views.generic.edit.DeletionMixin` + * :class:`django.views.generic.detail.BaseDetailView` + * :class:`django.views.generic.detail.SingleObjectMixin` + * :class:`django.views.generic.base.View` + + **Notes** + + * The delete confirmation page displayed to a GET request uses a + ``template_name_suffix`` of ``'_confirm_delete'``. diff --git a/docs/ref/class-based-views/index.txt b/docs/ref/class-based-views/index.txt new file mode 100644 index 0000000000..c10e66b396 --- /dev/null +++ b/docs/ref/class-based-views/index.txt @@ -0,0 +1,59 @@ +================= +Class-based views +================= + +Class-based views API reference. For introductory material, see +:doc:`/topics/class-based-views/index`. + +.. toctree:: + :maxdepth: 1 + + base + generic-display + generic-editing + generic-date-based + mixins + +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`` is +a thread-safe operation). + +A class-based view is deployed into a URL pattern using the +:meth:`~View.as_view()` classmethod:: + + urlpatterns = patterns('', + (r'^view/$', MyView.as_view(size=42)), + ) + +.. admonition:: 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. + +Any argument passed into :meth:`~View.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 use ``self.size``. + +Base vs Generic views +--------------------- + +Base class-based views can be thought of as *parent* views, which can be +used by themselves or inherited from. They may not provide all the +capabilities required for projects, in which case there are Mixins which +extend what base views can do. + +Django’s generic views are built off of those base views, and were developed +as a shortcut for common usage patterns such as displaying the details of an +object. They take certain common idioms and patterns found in view +development and abstract them so that you can quickly write common views of +data without having to repeat yourself. + +Most generic views require the ``queryset`` key, which is a ``QuerySet`` +instance; see :doc:`/topics/db/queries` for more information about ``QuerySet`` +objects. diff --git a/docs/ref/class-based-views/mixins-date-based.txt b/docs/ref/class-based-views/mixins-date-based.txt new file mode 100644 index 0000000000..a65471e68d --- /dev/null +++ b/docs/ref/class-based-views/mixins-date-based.txt @@ -0,0 +1,256 @@ +================= +Date-based mixins +================= + + +.. class:: django.views.generic.dates.YearMixin + + A mixin that can be used to retrieve and provide parsing information for a + year component of a date. + + **Methods and Attributes** + + .. attribute:: year_format + + The :func:`~time.strftime` format to use when parsing the year. + By default, this is ``'%Y'``. + + .. attribute:: 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. + + .. method:: get_year_format() + + Returns the :func:`~time.strftime` format to use when parsing the year. Returns + :attr:`YearMixin.year_format` by default. + + .. method:: get_year() + + Returns the year for which this view will display data. Tries the + following sources, in order: + + * The value of the :attr:`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. + +.. class:: django.views.generic.dates.MonthMixin + + A mixin that can be used to retrieve and provide parsing information for a + month component of a date. + + **Methods and Attributes** + + .. attribute:: month_format + + The :func:`~time.strftime` format to use when parsing the month. By default, this is + ``'%b'``. + + .. attribute:: 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. + + .. method:: get_month_format() + + Returns the :func:`~time.strftime` format to use when parsing the month. Returns + :attr:`MonthMixin.month_format` by default. + + .. method:: get_month() + + Returns the month for which this view will display data. Tries the + following sources, in order: + + * The value of the :attr:`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. + + .. method:: 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. + + .. method:: 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. + +.. class:: django.views.generic.dates.DayMixin + + A mixin that can be used to retrieve and provide parsing information for a + day component of a date. + + **Methods and Attributes** + + .. attribute:: day_format + + The :func:`~time.strftime` format to use when parsing the day. By default, this is + ``'%d'``. + + .. attribute:: 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. + + .. method:: get_day_format() + + Returns the :func:`~time.strftime` format to use when parsing the day. Returns + :attr:`DayMixin.day_format` by default. + + .. method:: get_day() + + Returns the day for which this view will display data. Tries the + following sources, in order: + + * The value of the :attr:`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. + + .. method:: get_next_day(date) + + Returns a date object containing the next day after the date provided. + Returns ``None`` if mixed with a view that sets ``allow_future = False``, + and the next day is in the future. If ``allow_empty = False``, returns + the next day that contains data. + + .. method:: get_prev_day(date) + + Returns a date object containing the previous day. If + ``allow_empty = False``, returns the previous day that contained data. + +.. class:: django.views.generic.dates.WeekMixin + + A mixin that can be used to retrieve and provide parsing information for a + week component of a date. + + **Methods and Attributes** + + .. attribute:: week_format + + The :func:`~time.strftime` format to use when parsing the week. By default, this is + ``'%U'``. + + .. attribute:: 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. + + .. method:: get_week_format() + + Returns the :func:`~time.strftime` format to use when parsing the week. Returns + :attr:`WeekMixin.week_format` by default. + + .. method:: get_week() + + Returns the week for which this view will display data. Tries the + following sources, in order: + + * The value of the :attr:`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. + + +.. class:: django.views.generic.dates.DateMixin + + A mixin class providing common behavior for all date-based views. + + **Methods and Attributes** + + .. attribute:: 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. + + When :doc:`time zone support ` is enabled and + ``date_field`` is a ``DateTimeField``, dates are assumed to be in the + current time zone. Otherwise, the queryset could include objects from + the previous or the next day in the end user's time zone. + + .. warning:: + + In this situation, if you have implemented per-user time zone + selection, the same URL may show a different set of objects, + depending on the end user's time zone. To avoid this, you should + use a ``DateField`` as the ``date_field`` attribute. + + .. attribute:: 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``. + + .. method:: get_date_field() + + Returns the name of the field that contains the date data that this + view will operate on. Returns :attr:`DateMixin.date_field` by default. + + .. method:: get_allow_future() + + Determine 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. Returns + :attr:`DateMixin.allow_future` by default. + +.. class:: django.views.generic.dates.BaseDateListView + + A base class that provides common behavior for all date-based views. There + won't normally be a reason to instantiate + :class:`~django.views.generic.dates.BaseDateListView`; 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** + + * :class:`~django.views.generic.dates.DateMixin` + * :class:`~django.views.generic.list.MultipleObjectMixin` + + **Methods and Attributes** + + .. attribute:: allow_empty + + A boolean specifying whether to display the page if no objects are + available. If this is ``True`` and no objects are available, the view + will display an empty page instead of raising a 404. By default, this + is ``False``. + + .. method:: get_dated_items(): + + Returns a 3-tuple containing (``date_list``, ``object_list``, + ``extra_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 + :class:`~django.views.generic.list.MultipleObjectMixin`. + + .. method:: 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``. + + .. method:: get_date_list(queryset, date_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 :meth:`~django.db.models.query.QuerySet.dates()` for the + ways that the ``date_type`` argument can be used. diff --git a/docs/ref/class-based-views/mixins-editing.txt b/docs/ref/class-based-views/mixins-editing.txt new file mode 100644 index 0000000000..7258893d63 --- /dev/null +++ b/docs/ref/class-based-views/mixins-editing.txt @@ -0,0 +1,183 @@ +============== +Editing mixins +============== + +.. class:: django.views.generic.edit.FormMixin + + A mixin class that provides facilities for creating and displaying forms. + + **Methods and Attributes** + + .. attribute:: initial + + A dictionary containing initial data for the form. + + .. attribute:: form_class + + The form class to instantiate. + + .. attribute:: success_url + + The URL to redirect to when the form is successfully processed. + + .. method:: get_initial() + + Retrieve initial data for the form. By default, returns a copy of + :attr:`~django.views.generic.edit.FormMixin.initial`. + + .. versionchanged:: 1.4 + In Django 1.3, this method was returning the + :attr:`~django.views.generic.edit.FormMixin.initial` class variable + itself. + + .. method:: get_form_class() + + Retrieve the form class to instantiate. By default + :attr:`.form_class`. + + .. method:: get_form(form_class) + + Instantiate an instance of ``form_class`` using + :meth:`~django.views.generic.edit.FormMixin.get_form_kwargs`. + + .. method:: get_form_kwargs() + + Build the keyword arguments required to instantiate the form. + + The ``initial`` argument is set to :meth:`.get_initial`. If the + request is a ``POST`` or ``PUT``, the request data (``request.POST`` + and ``request.FILES``) will also be provided. + + .. method:: get_success_url() + + Determine the URL to redirect to when the form is successfully + validated. Returns + :attr:`~django.views.generic.edit.FormMixin.success_url` by default. + + .. method:: form_valid(form) + + Redirects to + :meth:`~django.views.generic.edit.FormMixin.get_success_url`. + + .. method:: form_invalid(form) + + Renders a response, providing the invalid form as context. + + .. method:: 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 :class:`FormMixin` must provide an implementation of + :meth:`~django.views.generic.FormMixin.form_valid` and + :meth:`~django.views.generic.FormMixin.form_invalid`. + + +.. class:: django.views.generic.edit.ModelFormMixin + + A form mixin that works on ModelForms, rather than a standalone form. + + Since this is a subclass of + :class:`~django.views.generic.detail.SingleObjectMixin`, instances of this + mixin have access to the :attr:`~SingleObjectMixin.model` and + :attr:`~SingleObjectMixin.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** + + * :class:`django.views.generic.edit.FormMixin` + * :class:`django.views.generic.detail.SingleObjectMixin` + + **Methods and Attributes** + + .. attribute:: 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. + + .. method:: get_form_class() + + Retrieve the form class to instantiate. If + :attr:`FormMixin.form_class` is provided, that class will be used. + Otherwise, a ModelForm will be instantiated using the model associated + with the :attr:`~SingleObjectMixin.queryset`, or with the + :attr:`~SingleObjectMixin.model`, depending on which attribute is + provided. + + .. method:: get_form_kwargs() + + Add the current instance (``self.object``) to the standard + :meth:`FormMixin.get_form_kwargs`. + + .. method:: get_success_url() + + Determine the URL to redirect to when the form is successfully + validated. Returns :attr:`ModelFormMixin.success_url` if it is provided; + otherwise, attempts to use the ``get_absolute_url()`` of the object. + + .. method:: form_valid(form) + + Saves the form instance, sets the current object for the view, and + redirects to + :meth:`~django.views.generic.edit.FormMixin.get_success_url`. + + .. method:: form_invalid() + + Renders a response, providing the invalid form as context. + +.. class:: django.views.generic.edit.ProcessFormView + + A mixin that provides basic HTTP GET and POST workflow. + + .. note:: + + This is named 'ProcessFormView' and inherits directly from + :class:`django.views.generic.base.View`, but breaks if used + independently, so it is more of a mixin. + + **Extends** + + * :class:`django.views.generic.base.View` + + **Methods and Attributes** + + .. method:: get(request, *args, **kwargs) + + Constructs a form, then renders a response using a context that + contains that form. + + .. method:: 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. + +.. class:: django.views.generic.edit.DeletionMixin + + Enables handling of the ``DELETE`` http action. + + **Methods and Attributes** + + .. attribute:: success_url + + The url to redirect to when the nominated object has been + successfully deleted. + + .. method:: get_success_url(obj) + + Returns the url to redirect to when the nominated object has been + successfully deleted. Returns + :attr:`~django.views.generic.edit.DeletionMixin.success_url` by + default. diff --git a/docs/ref/class-based-views/mixins-multiple-object.txt b/docs/ref/class-based-views/mixins-multiple-object.txt new file mode 100644 index 0000000000..b414355c6b --- /dev/null +++ b/docs/ref/class-based-views/mixins-multiple-object.txt @@ -0,0 +1,175 @@ +====================== +Multiple object mixins +====================== + +.. class:: django.views.generic.list.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 :doc:`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. + + **Extends** + + * :class:`django.views.generic.base.ContextMixin` + + **Methods and Attributes** + + .. attribute:: 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``. + + .. attribute:: model + + The model that this view will display data for. Specifying ``model + = Foo`` is effectively the same as specifying ``queryset = + Foo.objects.all()``. + + .. attribute:: queryset + + A ``QuerySet`` that represents the objects. If provided, the value of + :attr:`MultipleObjectMixin.queryset` supersedes the value provided for + :attr:`MultipleObjectMixin.model`. + + .. attribute:: paginate_by + + An integer specifying how many objects should be displayed per page. If + this is given, the view will paginate objects with + :attr:`MultipleObjectMixin.paginate_by` objects per page. The view will + expect either a ``page`` query string parameter (via ``GET``) or a + ``page`` variable specified in the URLconf. + + .. attribute:: paginator_class + + The paginator class to be used for pagination. By default, + :class:`django.core.paginator.Paginator` is used. If the custom paginator + class doesn't have the same constructor interface as + :class:`django.core.paginator.Paginator`, you will also need to + provide an implementation for :meth:`MultipleObjectMixin.get_paginator`. + + .. attribute:: context_object_name + + Designates the name of the variable to use in the context. + + .. method:: get_queryset() + + Returns the queryset that represents the data this view will display. + + .. method:: paginate_queryset(queryset, page_size) + + Returns a 4-tuple containing (``paginator``, ``page``, ``object_list``, + ``is_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. + + .. method:: get_paginate_by(queryset) + + Returns the number of items to paginate by, or ``None`` for no + pagination. By default this simply returns the value of + :attr:`MultipleObjectMixin.paginate_by`. + + .. method:: get_paginator(queryset, per_page, orphans=0, allow_empty_first_page=True) + + Returns an instance of the paginator to use for this view. By default, + instantiates an instance of :attr:`paginator_class`. + + .. method:: 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``. + + .. method:: 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_list`` is a queryset of Django objects and + :attr:`~MultipleObjectMixin.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``. + + .. method:: 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 + :class:`django.core.paginator.Paginator`. If the page is not + paginated, this context variable will be ``None``. + + * ``page_obj``: An instance of + :class:`django.core.paginator.Page`. If the page is not paginated, + this context variable will be ``None``. + + +.. class:: django.views.generic.list.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 :class:`~django.db.models.query.QuerySet`. + + **Extends** + + * :class:`~django.views.generic.base.TemplateResponseMixin` + + **Methods and Attributes** + + .. attribute:: template_name_suffix + + The suffix to append to the auto-generated candidate template name. + Default suffix is ``_list``. + + .. method:: 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`` diff --git a/docs/ref/class-based-views/mixins-simple.txt b/docs/ref/class-based-views/mixins-simple.txt new file mode 100644 index 0000000000..33d0db3134 --- /dev/null +++ b/docs/ref/class-based-views/mixins-simple.txt @@ -0,0 +1,60 @@ +============= +Simple mixins +============= + +.. class:: django.views.generic.base.ContextMixin + + .. versionadded:: 1.5 + + **classpath** + + ``django.views.generic.base.ContextMixin`` + + **Methods** + + .. method:: get_context_data(**kwargs) + + Returns a dictionary representing the template context. The + keyword arguments provided will make up the returned context. + +.. class:: django.views.generic.base.TemplateResponseMixin + + Provides a mechanism to construct a + :class:`~django.template.response.TemplateResponse`, given + suitable context. The template to use is configurable and can be + further customized by subclasses. + + **Methods and Attributes** + + .. attribute:: response_class + + The response class to be returned by ``render_to_response`` method. + Default is + :class:`TemplateResponse `. + The template and context of ``TemplateResponse`` instances can be + altered later (e.g. in + :ref:`template response middleware `). + + If you need custom template loading or custom context object + instantiation, create a ``TemplateResponse`` subclass and assign it to + ``response_class``. + + .. method:: render_to_response(context, **response_kwargs) + + Returns a ``self.response_class`` instance. + + If any keyword arguments are provided, they will be + passed to the constructor of the response class. + + Calls :meth:`~TemplateResponseMixin.get_template_names()` to obtain the + list of template names that will be searched looking for an existent + template. + + .. method:: get_template_names() + + Returns a list of template names to search for when rendering the + template. + + If :attr:`TemplateResponseMixin.template_name` is specified, the + default implementation will return a list containing + :attr:`TemplateResponseMixin.template_name` (if it is specified). diff --git a/docs/ref/class-based-views/mixins-single-object.txt b/docs/ref/class-based-views/mixins-single-object.txt new file mode 100644 index 0000000000..a31608dbd4 --- /dev/null +++ b/docs/ref/class-based-views/mixins-single-object.txt @@ -0,0 +1,124 @@ +==================== +Single object mixins +==================== + +.. class:: django.views.generic.detail.SingleObjectMixin + + Provides a mechanism for looking up an object associated with the + current HTTP request. + + **Methods and Attributes** + + .. attribute:: model + + The model that this view will display data for. Specifying ``model + = Foo`` is effectively the same as specifying ``queryset = + Foo.objects.all()``. + + .. attribute:: queryset + + A ``QuerySet`` that represents the objects. If provided, the value of + :attr:`SingleObjectMixin.queryset` supersedes the value provided for + :attr:`SingleObjectMixin.model`. + + .. attribute:: slug_field + + The name of the field on the model that contains the slug. By default, + ``slug_field`` is ``'slug'``. + + .. attribute:: slug_url_kwarg + + .. versionadded:: 1.4 + + The name of the URLConf keyword argument that contains the slug. By + default, ``slug_url_kwarg`` is ``'slug'``. + + .. attribute:: pk_url_kwarg + + .. versionadded:: 1.4 + + The name of the URLConf keyword argument that contains the primary key. + By default, ``pk_url_kwarg`` is ``'pk'``. + + .. attribute:: context_object_name + + Designates the name of the variable to use in the context. + + .. method:: 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, + :meth:`~SingleObjectMixin.get_queryset` will be used. + ``get_object()`` looks for a + :attr:`SingleObjectMixin.pk_url_kwarg` argument in the arguments + to the view; if this argument is found, this method performs a + primary-key based lookup using that value. If this argument is not + found, it looks for a :attr:`SingleObjectMixin.slug_url_kwarg` + argument, and performs a slug lookup using the + :attr:`SingleObjectMixin.slug_field`. + + .. method:: get_queryset() + + Returns the queryset that will be used to retrieve the object that + this view will display. By default, + :meth:`~SingleObjectMixin.get_queryset` returns the value of the + :attr:`~SingleObjectMixin.queryset` attribute if it is set, otherwise + it constructs a :class:`QuerySet` by calling the `all()` method on the + :attr:`~SingleObjectMixin.model` attribute's default manager. + + .. method:: get_context_object_name(obj) + + Return the context variable name that will be used to contain the + data that this view is manipulating. If + :attr:`~SingleObjectMixin.context_object_name` is 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'``. + + .. method:: get_context_data(**kwargs) + + Returns context data for displaying the list of objects. + + **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``. + +.. class:: django.views.generic.detail.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.object`` will 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** + + * :class:`~django.views.generic.base.TemplateResponseMixin` + + **Methods and Attributes** + + .. attribute:: template_name_field + + The field on the current object instance that can be used to determine + the name of a candidate template. If either ``template_name_field`` + itself or the value of the ``template_name_field`` on the current + object instance is ``None``, the object will not be used for a + candidate template name. + + .. attribute:: template_name_suffix + + The suffix to append to the auto-generated candidate template name. + Default suffix is ``_detail``. + + .. method:: 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`` diff --git a/docs/ref/class-based-views/mixins.txt b/docs/ref/class-based-views/mixins.txt new file mode 100644 index 0000000000..661454f74d --- /dev/null +++ b/docs/ref/class-based-views/mixins.txt @@ -0,0 +1,14 @@ +======================== +Class-based views mixins +======================== + +Class-based views API reference. For introductory material, see :doc:`/topics/class-based-views/mixins`. + +.. toctree:: + :maxdepth: 1 + + mixins-simple + mixins-single-object + mixins-multiple-object + mixins-editing + mixins-date-based diff --git a/docs/ref/index.txt b/docs/ref/index.txt index 32b263199f..01a8ab22d1 100644 --- a/docs/ref/index.txt +++ b/docs/ref/index.txt @@ -6,6 +6,7 @@ API Reference :maxdepth: 1 authbackends + class-based-views/index clickjacking contrib/index databases @@ -13,7 +14,6 @@ API Reference exceptions files/index forms/index - class-based-views middleware models/index request-response -- cgit v1.3