[1.5.x] Fixed #19516 - Fixed remaining broken links.

Added -n to sphinx builds to catch issues going forward.

Backport of 9b5f64cc6e from master.
This commit is contained in:
Tim Graham 2013-01-01 08:12:42 -05:00
parent 61c861546b
commit be1e006c58
84 changed files with 721 additions and 604 deletions

View File

@ -10,7 +10,7 @@ BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
ALLSPHINXOPTS = -n -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .

View File

@ -52,10 +52,11 @@ Using a :class:`~django.db.models.FileField` or an
#. All that will be stored in your database is a path to the file
(relative to :setting:`MEDIA_ROOT`). You'll most likely want to use the
convenience :attr:`~django.core.files.File.url` attribute provided by
Django. For example, if your :class:`~django.db.models.ImageField` is
called ``mug_shot``, you can get the absolute path to your image in a
template with ``{{ object.mug_shot.url }}``.
convenience :attr:`~django.db.models.fields.files.FieldFile.url` attribute
provided by Django. For example, if your
:class:`~django.db.models.ImageField` is called ``mug_shot``, you can get
the absolute path to your image in a template with
``{{ object.mug_shot.url }}``.
How do I make a variable available to all my templates?
-------------------------------------------------------

View File

@ -199,20 +199,20 @@ The :meth:`~django.db.models.Field.__init__` method takes the following
parameters:
* :attr:`~django.db.models.Field.verbose_name`
* :attr:`~django.db.models.Field.name`
* ``name``
* :attr:`~django.db.models.Field.primary_key`
* :attr:`~django.db.models.Field.max_length`
* :attr:`~django.db.models.CharField.max_length`
* :attr:`~django.db.models.Field.unique`
* :attr:`~django.db.models.Field.blank`
* :attr:`~django.db.models.Field.null`
* :attr:`~django.db.models.Field.db_index`
* :attr:`~django.db.models.Field.rel`: Used for related fields (like
:class:`ForeignKey`). For advanced use only.
* ``rel``: Used for related fields (like :class:`ForeignKey`). For advanced
use only.
* :attr:`~django.db.models.Field.default`
* :attr:`~django.db.models.Field.editable`
* :attr:`~django.db.models.Field.serialize`: If ``False``, the field will
not be serialized when the model is passed to Django's :doc:`serializers
</topics/serialization>`. Defaults to ``True``.
* ``serialize``: If ``False``, the field will not be serialized when the model
is passed to Django's :doc:`serializers </topics/serialization>`. Defaults to
``True``.
* :attr:`~django.db.models.Field.unique_for_date`
* :attr:`~django.db.models.Field.unique_for_month`
* :attr:`~django.db.models.Field.unique_for_year`
@ -222,7 +222,7 @@ parameters:
* :attr:`~django.db.models.Field.db_tablespace`: Only for index creation, if the
backend supports :doc:`tablespaces </topics/db/tablespaces>`. You can usually
ignore this option.
* :attr:`~django.db.models.Field.auto_created`: True if the field was
* ``auto_created``: True if the field was
automatically created, as for the `OneToOneField` used by model
inheritance. For advanced use only.
@ -443,7 +443,7 @@ Python object type we want to store in the model's attribute. If anything is
going wrong during value conversion, you should raise a
:exc:`~django.core.exceptions.ValidationError` exception.
**Remember:** If your custom field needs the :meth:`to_python` method to be
**Remember:** If your custom field needs the :meth:`.to_python` method to be
called when it is created, you should be using `The SubfieldBase metaclass`_
mentioned earlier. Otherwise :meth:`.to_python` won't be called
automatically.

View File

@ -114,6 +114,8 @@ your function. Example:
Registering custom filters
~~~~~~~~~~~~~~~~~~~~~~~~~~
.. method:: django.template.Library.filter
Once you've written your filter definition, you need to register it with
your ``Library`` instance, to make it available to Django's template language:
@ -151,6 +153,8 @@ are described in :ref:`filters and auto-escaping <filters-auto-escaping>` and
Template filters that expect strings
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. method:: django.template.defaultfilters.stringfilter
If you're writing a template filter that only expects a string as the first
argument, you should use the decorator ``stringfilter``. This will
convert an object to its string value before being passed to your function:
@ -722,6 +726,8 @@ cannot resolve the string passed to it in the current context of the page.
Simple tags
~~~~~~~~~~~
.. method:: django.template.Library.simple_tag
Many template tags take a number of arguments -- strings or template variables
-- and return a string after doing some processing based solely on
the input arguments and some external information. For example, the

View File

@ -177,9 +177,9 @@ That means that the ability for third parties to import the module at the top
level is incompatible with the ability to configure the settings object
manually, or makes it very difficult in some circumstances.
Instead of the above code, a level of laziness or indirection must be used, such
as :class:`django.utils.functional.LazyObject`,
:func:`django.utils.functional.lazy` or ``lambda``.
Instead of the above code, a level of laziness or indirection must be used,
such as ``django.utils.functional.LazyObject``,
``django.utils.functional.lazy()`` or ``lambda``.
Miscellaneous
-------------

View File

@ -167,9 +167,8 @@ these changes.
* ``django.core.context_processors.PermWrapper`` and
``django.core.context_processors.PermLookupDict`` will be removed in
favor of the corresponding
:class:`django.contrib.auth.context_processors.PermWrapper` and
:class:`django.contrib.auth.context_processors.PermLookupDict`,
respectively.
``django.contrib.auth.context_processors.PermWrapper`` and
``django.contrib.auth.context_processors.PermLookupDict``, respectively.
* The :setting:`MEDIA_URL` or :setting:`STATIC_URL` settings will be
required to end with a trailing slash to ensure there is a consistent
@ -218,10 +217,10 @@ these changes.
synonym for ``django.views.decorators.csrf.csrf_exempt``, which should
be used to replace it.
* The :class:`~django.core.cache.backends.memcached.CacheClass` backend
* The ``django.core.cache.backends.memcached.CacheClass`` backend
was split into two in Django 1.3 in order to introduce support for
PyLibMC. The historical :class:`~django.core.cache.backends.memcached.CacheClass`
will be removed in favor of :class:`~django.core.cache.backends.memcached.MemcachedCache`.
PyLibMC. The historical ``CacheClass`` will be removed in favor of
``django.core.cache.backends.memcached.MemcachedCache``.
* The UK-prefixed objects of ``django.contrib.localflavor.uk`` will only
be accessible through their GB-prefixed names (GB is the correct
@ -243,8 +242,8 @@ these changes.
:setting:`LOGGING` setting should include this filter explicitly if
it is desired.
* The builtin truncation functions :func:`django.utils.text.truncate_words`
and :func:`django.utils.text.truncate_html_words` will be removed in
* The builtin truncation functions ``django.utils.text.truncate_words()``
and ``django.utils.text.truncate_html_words()`` will be removed in
favor of the ``django.utils.text.Truncator`` class.
* The :class:`~django.contrib.gis.geoip.GeoIP` class was moved to
@ -257,9 +256,8 @@ these changes.
:data:`~django.conf.urls.handler500`, are now available through
:mod:`django.conf.urls` .
* The functions :func:`~django.core.management.setup_environ` and
:func:`~django.core.management.execute_manager` will be removed from
:mod:`django.core.management`. This also means that the old (pre-1.4)
* The functions ``setup_environ()`` and ``execute_manager()`` will be removed
from :mod:`django.core.management`. This also means that the old (pre-1.4)
style of :file:`manage.py` file will no longer work.
* Setting the ``is_safe`` and ``needs_autoescape`` flags as attributes of

View File

@ -369,8 +369,8 @@ its human-readable name.
Some :class:`~django.db.models.Field` classes have required elements.
:class:`~django.db.models.CharField`, for example, requires that you give it a
:attr:`~django.db.models.Field.max_length`. That's used not only in the database
schema, but in validation, as we'll soon see.
:attr:`~django.db.models.CharField.max_length`. That's used not only in the
database schema, but in validation, as we'll soon see.
Finally, note a relationship is defined, using
:class:`~django.db.models.ForeignKey`. That tells Django each ``Choice`` is related

View File

@ -234,12 +234,12 @@ two views abstract the concepts of "display a list of objects" and
* Each generic view needs to know what model it will be acting
upon. This is provided using the ``model`` parameter.
* The :class:`~django.views.generic.list.DetailView` generic view
* The :class:`~django.views.generic.detail.DetailView` generic view
expects the primary key value captured from the URL to be called
``"pk"``, so we've changed ``poll_id`` to ``pk`` for the generic
views.
By default, the :class:`~django.views.generic.list.DetailView` generic
By default, the :class:`~django.views.generic.detail.DetailView` generic
view uses a template called ``<app name>/<model name>_detail.html``.
In our case, it'll use the template ``"polls/poll_detail.html"``. The
``template_name`` argument is used to tell Django to use a specific
@ -247,7 +247,7 @@ template name instead of the autogenerated default template name. We
also specify the ``template_name`` for the ``results`` list view --
this ensures that the results view and the detail view have a
different appearance when rendered, even though they're both a
:class:`~django.views.generic.list.DetailView` behind the scenes.
:class:`~django.views.generic.detail.DetailView` behind the scenes.
Similarly, the :class:`~django.views.generic.list.ListView` generic
view uses a default template called ``<app name>/<model
@ -257,7 +257,7 @@ name>_list.html``; we use ``template_name`` to tell
In previous parts of the tutorial, the templates have been provided
with a context that contains the ``poll`` and ``latest_poll_list``
context variables. For DetailView the ``poll`` variable is provided
context variables. For ``DetailView`` the ``poll`` variable is provided
automatically -- since we're using a Django model (``Poll``), Django
is able to determine an appropriate name for the context variable.
However, for ListView, the automatically generated context variable is

View File

@ -6,7 +6,7 @@ if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=_build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
set ALLSPHINXOPTS=-n -d %BUILDDIR%/doctrees %SPHINXOPTS% .
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%

View File

@ -49,9 +49,13 @@ View
**Attributes**
.. attribute:: http_method_names = ['get', 'post', 'put', 'delete', 'head', 'options', 'trace']
.. attribute:: http_method_names
The default list of HTTP method names that this view will accept.
The list of HTTP method names that this view will accept.
Default::
['get', 'post', 'put', 'delete', 'head', 'options', 'trace']
**Methods**
@ -68,12 +72,11 @@ View
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.
delegated to ``get()``, a ``POST`` to ``post()``, and so on.
By default, a ``HEAD`` request will be delegated to :meth:`~View.get()`.
By default, a ``HEAD`` request will be delegated to ``get()``.
If you need to handle ``HEAD`` requests in a different way than ``GET``,
you can override the :meth:`~View.head()` method. See
you can override the ``head()`` method. See
:ref:`supporting-other-http-methods` for an example.
The default implementation also sets ``request``, ``args`` and
@ -111,9 +114,9 @@ TemplateView
**Method Flowchart**
1. :meth:`dispatch()`
2. :meth:`http_method_not_allowed()`
3. :meth:`get_context_data()`
1. :meth:`~django.views.generic.base.View.dispatch()`
2. :meth:`~django.views.generic.base.View.http_method_not_allowed()`
3. :meth:`~django.views.generic.base.ContextMixin.get_context_data()`
**Example views.py**::
@ -169,8 +172,8 @@ RedirectView
**Method Flowchart**
1. :meth:`dispatch()`
2. :meth:`http_method_not_allowed()`
1. :meth:`~django.views.generic.base.View.dispatch()`
2. :meth:`~django.views.generic.base.View.http_method_not_allowed()`
3. :meth:`get_redirect_url()`
**Example views.py**::
@ -230,9 +233,8 @@ RedirectView
Constructs the target URL for redirection.
The default implementation uses :attr:`~RedirectView.url` as a starting
The default implementation uses :attr:`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.
as the appending of query string if requested by :attr:`query_string`.
Subclasses may implement any behavior they wish, as long as the method
returns a redirect-ready URL string.

View File

@ -23,7 +23,7 @@ View
* :meth:`~django.views.generic.base.View.as_view`
* :meth:`~django.views.generic.base.View.dispatch`
* :meth:`~django.views.generic.base.View.head`
* ``head()``
* :meth:`~django.views.generic.base.View.http_method_not_allowed`
TemplateView
@ -40,9 +40,9 @@ TemplateView
* :meth:`~django.views.generic.base.View.as_view`
* :meth:`~django.views.generic.base.View.dispatch`
* :meth:`~django.views.generic.base.TemplateView.get`
* :meth:`~django.views.generic.base.TemplateView.get_context_data`
* :meth:`~django.views.generic.base.View.head`
* ``get()``
* :meth:`~django.views.generic.base.ContextMixin.get_context_data`
* ``head()``
* :meth:`~django.views.generic.base.View.http_method_not_allowed`
* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`
@ -60,15 +60,15 @@ RedirectView
**Methods**
* :meth:`~django.views.generic.base.View.as_view`
* :meth:`~django.views.generic.base.RedirectView.delete`
* ``delete()``
* :meth:`~django.views.generic.base.View.dispatch`
* :meth:`~django.views.generic.base.RedirectView.get`
* ``get()``
* :meth:`~django.views.generic.base.RedirectView.get_redirect_url`
* :meth:`~django.views.generic.base.View.head`
* ``head()``
* :meth:`~django.views.generic.base.View.http_method_not_allowed`
* :meth:`~django.views.generic.base.RedirectView.options`
* :meth:`~django.views.generic.base.RedirectView.post`
* :meth:`~django.views.generic.base.RedirectView.put`
* ``options()``
* ``post()``
* ``put()``
Detail Views
------------
@ -95,10 +95,10 @@ DetailView
* :meth:`~django.views.generic.base.View.as_view`
* :meth:`~django.views.generic.base.View.dispatch`
* :meth:`~django.views.generic.detail.BaseDetailView.get`
* ``get()``
* :meth:`~django.views.generic.detail.SingleObjectMixin.get_context_data`
* :meth:`~django.views.generic.detail.SingleObjectMixin.get_object`
* :meth:`~django.views.generic.base.View.head`
* ``head()``
* :meth:`~django.views.generic.base.View.http_method_not_allowed`
* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`
@ -129,7 +129,7 @@ ListView
* :meth:`~django.views.generic.list.BaseListView.get`
* :meth:`~django.views.generic.list.MultipleObjectMixin.get_context_data`
* :meth:`~django.views.generic.list.MultipleObjectMixin.get_paginator`
* :meth:`~django.views.generic.base.View.head`
* ``head()``
* :meth:`~django.views.generic.base.View.http_method_not_allowed`
* :meth:`~django.views.generic.list.MultipleObjectMixin.paginate_queryset`
* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`
@ -160,10 +160,10 @@ FormView
* :meth:`~django.views.generic.edit.FormMixin.get_context_data`
* :meth:`~django.views.generic.edit.FormMixin.get_form`
* :meth:`~django.views.generic.edit.FormMixin.get_form_kwargs`
* :meth:`~django.views.generic.base.View.head`
* ``head()``
* :meth:`~django.views.generic.base.View.http_method_not_allowed`
* :meth:`~django.views.generic.edit.ProcessFormView.post`
* :meth:`~django.views.generic.edit.ProcessFormView.put`
* ``post()``
* ``put()``
* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`
CreateView
@ -198,10 +198,10 @@ CreateView
* :meth:`~django.views.generic.edit.FormMixin.get_form`
* :meth:`~django.views.generic.edit.FormMixin.get_form_kwargs`
* :meth:`~django.views.generic.detail.SingleObjectMixin.get_object`
* :meth:`~django.views.generic.base.View.head`
* ``head()``
* :meth:`~django.views.generic.base.View.http_method_not_allowed`
* :meth:`~django.views.generic.edit.ProcessFormView.post`
* :meth:`~django.views.generic.edit.ProcessFormView.put`
* ``put()``
* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`
UpdateView
@ -236,10 +236,10 @@ UpdateView
* :meth:`~django.views.generic.edit.FormMixin.get_form`
* :meth:`~django.views.generic.edit.FormMixin.get_form_kwargs`
* :meth:`~django.views.generic.detail.SingleObjectMixin.get_object`
* :meth:`~django.views.generic.base.View.head`
* ``head()``
* :meth:`~django.views.generic.base.View.http_method_not_allowed`
* :meth:`~django.views.generic.edit.ProcessFormView.post`
* :meth:`~django.views.generic.edit.ProcessFormView.put`
* ``put()``
* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`
DeleteView
@ -264,14 +264,14 @@ DeleteView
**Methods**
* :meth:`~django.views.generic.base.View.as_view`
* :meth:`~django.views.generic.edit.DeletionMixin.delete`
* ``delete()``
* :meth:`~django.views.generic.base.View.dispatch`
* :meth:`~django.views.generic.detail.BaseDetailView.get`
* ``get()``
* :meth:`~django.views.generic.detail.SingleObjectMixin.get_context_data`
* :meth:`~django.views.generic.detail.SingleObjectMixin.get_object`
* :meth:`~django.views.generic.base.View.head`
* ``head()``
* :meth:`~django.views.generic.base.View.http_method_not_allowed`
* :meth:`~django.views.generic.edit.DeletionMixin.post`
* ``post()``
* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`
Date-based views
@ -300,13 +300,13 @@ ArchiveIndexView
* :meth:`~django.views.generic.base.View.as_view`
* :meth:`~django.views.generic.base.View.dispatch`
* :meth:`~django.views.generic.dates.BaseDateListView.get`
* ``get()``
* :meth:`~django.views.generic.list.MultipleObjectMixin.get_context_data`
* :meth:`~django.views.generic.dates.BaseDateListView.get_date_list`
* :meth:`~django.views.generic.dates.BaseDateListView.get_dated_items`
* :meth:`~django.views.generic.dates.BaseDateListView.get_dated_queryset`
* :meth:`~django.views.generic.list.MultipleObjectMixin.get_paginator`
* :meth:`~django.views.generic.base.View.head`
* ``head()``
* :meth:`~django.views.generic.base.View.http_method_not_allowed`
* :meth:`~django.views.generic.list.MultipleObjectMixin.paginate_queryset`
* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`
@ -322,7 +322,7 @@ YearArchiveView
* :attr:`~django.views.generic.list.MultipleObjectMixin.context_object_name` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_context_object_name`]
* :attr:`~django.views.generic.dates.DateMixin.date_field` [:meth:`~django.views.generic.dates.DateMixin.get_date_field`]
* :attr:`~django.views.generic.base.View.http_method_names`
* :attr:`~django.views.generic.dates.BaseYearArchiveView.make_object_list` [:meth:`~django.views.generic.dates.BaseYearArchiveView.get_make_object_list`]
* :attr:`~django.views.generic.dates.YearArchiveView.make_object_list` [:meth:`~django.views.generic.dates.YearArchiveView.get_make_object_list`]
* :attr:`~django.views.generic.list.MultipleObjectMixin.model`
* :attr:`~django.views.generic.list.MultipleObjectMixin.paginate_by` [:meth:`~django.views.generic.list.MultipleObjectMixin.get_paginate_by`]
* :attr:`~django.views.generic.list.MultipleObjectMixin.paginator_class`
@ -337,13 +337,13 @@ YearArchiveView
* :meth:`~django.views.generic.base.View.as_view`
* :meth:`~django.views.generic.base.View.dispatch`
* :meth:`~django.views.generic.dates.BaseDateListView.get`
* ``get()``
* :meth:`~django.views.generic.list.MultipleObjectMixin.get_context_data`
* :meth:`~django.views.generic.dates.BaseDateListView.get_date_list`
* :meth:`~django.views.generic.dates.BaseDateListView.get_dated_items`
* :meth:`~django.views.generic.dates.BaseDateListView.get_dated_queryset`
* :meth:`~django.views.generic.list.MultipleObjectMixin.get_paginator`
* :meth:`~django.views.generic.base.View.head`
* ``head()``
* :meth:`~django.views.generic.base.View.http_method_not_allowed`
* :meth:`~django.views.generic.list.MultipleObjectMixin.paginate_queryset`
* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`
@ -375,7 +375,7 @@ MonthArchiveView
* :meth:`~django.views.generic.base.View.as_view`
* :meth:`~django.views.generic.base.View.dispatch`
* :meth:`~django.views.generic.dates.BaseDateListView.get`
* ``get()``
* :meth:`~django.views.generic.list.MultipleObjectMixin.get_context_data`
* :meth:`~django.views.generic.dates.BaseDateListView.get_date_list`
* :meth:`~django.views.generic.dates.BaseDateListView.get_dated_items`
@ -383,7 +383,7 @@ MonthArchiveView
* :meth:`~django.views.generic.dates.MonthMixin.get_next_month`
* :meth:`~django.views.generic.list.MultipleObjectMixin.get_paginator`
* :meth:`~django.views.generic.dates.MonthMixin.get_previous_month`
* :meth:`~django.views.generic.base.View.head`
* ``head()``
* :meth:`~django.views.generic.base.View.http_method_not_allowed`
* :meth:`~django.views.generic.list.MultipleObjectMixin.paginate_queryset`
* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`
@ -415,13 +415,13 @@ WeekArchiveView
* :meth:`~django.views.generic.base.View.as_view`
* :meth:`~django.views.generic.base.View.dispatch`
* :meth:`~django.views.generic.dates.BaseDateListView.get`
* ``get()``
* :meth:`~django.views.generic.list.MultipleObjectMixin.get_context_data`
* :meth:`~django.views.generic.dates.BaseDateListView.get_date_list`
* :meth:`~django.views.generic.dates.BaseDateListView.get_dated_items`
* :meth:`~django.views.generic.dates.BaseDateListView.get_dated_queryset`
* :meth:`~django.views.generic.list.MultipleObjectMixin.get_paginator`
* :meth:`~django.views.generic.base.View.head`
* ``head()``
* :meth:`~django.views.generic.base.View.http_method_not_allowed`
* :meth:`~django.views.generic.list.MultipleObjectMixin.paginate_queryset`
* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`
@ -455,7 +455,7 @@ DayArchiveView
* :meth:`~django.views.generic.base.View.as_view`
* :meth:`~django.views.generic.base.View.dispatch`
* :meth:`~django.views.generic.dates.BaseDateListView.get`
* ``get()``
* :meth:`~django.views.generic.list.MultipleObjectMixin.get_context_data`
* :meth:`~django.views.generic.dates.BaseDateListView.get_date_list`
* :meth:`~django.views.generic.dates.BaseDateListView.get_dated_items`
@ -465,7 +465,7 @@ DayArchiveView
* :meth:`~django.views.generic.list.MultipleObjectMixin.get_paginator`
* :meth:`~django.views.generic.dates.DayMixin.get_previous_day`
* :meth:`~django.views.generic.dates.MonthMixin.get_previous_month`
* :meth:`~django.views.generic.base.View.head`
* ``head()``
* :meth:`~django.views.generic.base.View.http_method_not_allowed`
* :meth:`~django.views.generic.list.MultipleObjectMixin.paginate_queryset`
* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`
@ -499,7 +499,7 @@ TodayArchiveView
* :meth:`~django.views.generic.base.View.as_view`
* :meth:`~django.views.generic.base.View.dispatch`
* :meth:`~django.views.generic.dates.BaseDateListView.get`
* ``get()``
* :meth:`~django.views.generic.list.MultipleObjectMixin.get_context_data`
* :meth:`~django.views.generic.dates.BaseDateListView.get_date_list`
* :meth:`~django.views.generic.dates.BaseDateListView.get_dated_items`
@ -509,7 +509,7 @@ TodayArchiveView
* :meth:`~django.views.generic.list.MultipleObjectMixin.get_paginator`
* :meth:`~django.views.generic.dates.DayMixin.get_previous_day`
* :meth:`~django.views.generic.dates.MonthMixin.get_previous_month`
* :meth:`~django.views.generic.base.View.head`
* ``head()``
* :meth:`~django.views.generic.base.View.http_method_not_allowed`
* :meth:`~django.views.generic.list.MultipleObjectMixin.paginate_queryset`
* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`
@ -544,13 +544,13 @@ DateDetailView
* :meth:`~django.views.generic.base.View.as_view`
* :meth:`~django.views.generic.base.View.dispatch`
* :meth:`~django.views.generic.detail.BaseDetailView.get`
* ``get()``
* :meth:`~django.views.generic.detail.SingleObjectMixin.get_context_data`
* :meth:`~django.views.generic.dates.DayMixin.get_next_day`
* :meth:`~django.views.generic.dates.MonthMixin.get_next_month`
* :meth:`~django.views.generic.detail.SingleObjectMixin.get_object`
* :meth:`~django.views.generic.dates.DayMixin.get_previous_day`
* :meth:`~django.views.generic.dates.MonthMixin.get_previous_month`
* :meth:`~django.views.generic.base.View.head`
* ``head()``
* :meth:`~django.views.generic.base.View.http_method_not_allowed`
* :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`

View File

@ -580,7 +580,7 @@ DateDetailView
* :class:`django.views.generic.dates.MonthMixin`
* :class:`django.views.generic.dates.DayMixin`
* :class:`django.views.generic.dates.DateMixin`
* :class:`django.views.generic.detail.BaseDetailView`
* ``django.views.generic.detail.BaseDetailView``
* :class:`django.views.generic.detail.SingleObjectMixin`
* :class:`django.views.generic.base.View`

View File

@ -19,22 +19,22 @@ DetailView
* :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin`
* :class:`django.views.generic.base.TemplateResponseMixin`
* :class:`django.views.generic.detail.BaseDetailView`
* ``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()`
1. :meth:`~django.views.generic.base.View.dispatch()`
2. :meth:`~django.views.generic.base.View.http_method_not_allowed()`
3. :meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names()`
4. :meth:`~django.views.generic.detail.SingleObjectMixin.get_slug_field()`
5. :meth:`~django.views.generic.detail.SingleObjectMixin.get_queryset()`
6. :meth:`~django.views.generic.detail.SingleObjectMixin.get_object()`
7. :meth:`~django.views.generic.detail.SingleObjectMixin.get_context_object_name()`
8. :meth:`~django.views.generic.detail.SingleObjectMixin.get_context_data()`
9. ``get()``
10. :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response()`
**Example views.py**::
@ -86,14 +86,14 @@ ListView
**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()`
1. :meth:`~django.views.generic.base.View.dispatch()`
2. :meth:`~django.views.generic.base.View.http_method_not_allowed()`
3. :meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names()`
4. :meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset()`
5. :meth:`~django.views.generic.list.MultipleObjectMixin.get_context_object_name()`
6. :meth:`~django.views.generic.list.MultipleObjectMixin.get_context_data()`
7. ``get()``
8. :meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response()`
**Example views.py**::
@ -140,7 +140,7 @@ ListView
.. method:: get(request, *args, **kwargs)
Adds :attr:`object_list` to the context. If
Adds ``object_list`` to the context. If
:attr:`~django.views.generic.list.MultipleObjectMixin.allow_empty`
is True then display an empty list. If
:attr:`~django.views.generic.list.MultipleObjectMixin.allow_empty` is

View File

@ -38,7 +38,7 @@ FormView
* :class:`django.views.generic.edit.FormView`
* :class:`django.views.generic.base.TemplateResponseMixin`
* :class:`django.views.generic.edit.BaseFormView`
* ``django.views.generic.edit.BaseFormView``
* :class:`django.views.generic.edit.FormMixin`
* :class:`django.views.generic.edit.ProcessFormView`
* :class:`django.views.generic.base.View`
@ -86,7 +86,7 @@ CreateView
* :class:`django.views.generic.edit.CreateView`
* :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin`
* :class:`django.views.generic.base.TemplateResponseMixin`
* :class:`django.views.generic.edit.BaseCreateView`
* ``django.views.generic.edit.BaseCreateView``
* :class:`django.views.generic.edit.ModelFormMixin`
* :class:`django.views.generic.edit.FormMixin`
* :class:`django.views.generic.detail.SingleObjectMixin`
@ -128,7 +128,7 @@ UpdateView
* :class:`django.views.generic.edit.UpdateView`
* :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin`
* :class:`django.views.generic.base.TemplateResponseMixin`
* :class:`django.views.generic.edit.BaseUpdateView`
* ``django.views.generic.edit.BaseUpdateView``
* :class:`django.views.generic.edit.ModelFormMixin`
* :class:`django.views.generic.edit.FormMixin`
* :class:`django.views.generic.detail.SingleObjectMixin`
@ -170,9 +170,9 @@ DeleteView
* :class:`django.views.generic.edit.DeleteView`
* :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin`
* :class:`django.views.generic.base.TemplateResponseMixin`
* :class:`django.views.generic.edit.BaseDeleteView`
* ``django.views.generic.edit.BaseDeleteView``
* :class:`django.views.generic.edit.DeletionMixin`
* :class:`django.views.generic.detail.BaseDetailView`
* ``django.views.generic.detail.BaseDetailView``
* :class:`django.views.generic.detail.SingleObjectMixin`
* :class:`django.views.generic.base.View`

View File

@ -100,7 +100,7 @@ MonthMixin
:attr:`~BaseDateListView.allow_empty` and
:attr:`~DateMixin.allow_future`.
.. method:: get_prev_month(date)
.. method:: get_previous_month(date)
Returns a date object containing the first day of the month before the
date provided. This function can also return ``None`` or raise an
@ -152,7 +152,7 @@ DayMixin
:attr:`~BaseDateListView.allow_empty` and
:attr:`~DateMixin.allow_future`.
.. method:: get_prev_day(date)
.. method:: get_previous_day(date)
Returns a date object containing the previous valid day. This function
can also return ``None`` or raise an :class:`~django.http.Http404`
@ -287,8 +287,9 @@ BaseDateListView
available. If this is ``True`` and no objects are available, the view
will display an empty page instead of raising a 404.
This is identical to :attr:`MultipleObjectMixin.allow_empty`, except
for the default value, which is ``False``.
This is identical to
:attr:`django.views.generic.list.MultipleObjectMixin.allow_empty`,
except for the default value, which is ``False``.
.. attribute:: date_list_period

View File

@ -88,9 +88,8 @@ FormMixin
.. 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`.
Views mixing ``FormMixin`` must provide an implementation of
:meth:`form_valid` and :meth:`form_invalid`.
ModelFormMixin
@ -98,15 +97,16 @@ ModelFormMixin
.. class:: django.views.generic.edit.ModelFormMixin
A form mixin that works on ModelForms, rather than a standalone form.
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``.
mixin have access to the
:attr:`~django.views.generic.detail.SingleObjectMixin.model` and
:attr:`~django.views.generic.detail.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**
@ -115,6 +115,12 @@ ModelFormMixin
**Methods and Attributes**
.. attribute:: model
A model class. Can be explicitly provided, otherwise will be determined
by examining ``self.object`` or
:attr:`~django.views.generic.detail.SingleObjectMixin.queryset`.
.. attribute:: success_url
The URL to redirect to when the form is successfully processed.
@ -127,22 +133,25 @@ ModelFormMixin
.. 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.
:attr:`~django.views.generic.edit.FormMixin.form_class` is provided,
that class will be used. Otherwise, a ``ModelForm`` will be
instantiated using the model associated with the
:attr:`~django.views.generic.detail.SingleObjectMixin.queryset`, or
with the :attr:`~django.views.generic.detail.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`.
:meth:`~django.views.generic.edit.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.
validated. Returns
:attr:`django.views.generic.edit.ModelFormMixin.success_url` if it is
provided; otherwise, attempts to use the ``get_absolute_url()`` of the
object.
.. method:: form_valid(form)

View File

@ -61,14 +61,13 @@ MultipleObjectMixin
.. attribute:: queryset
A ``QuerySet`` that represents the objects. If provided, the value of
:attr:`MultipleObjectMixin.queryset` supersedes the value provided for
:attr:`MultipleObjectMixin.model`.
``queryset`` supersedes the value provided for :attr:`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
``paginate_by`` objects per page. The view will
expect either a ``page`` query string parameter (via ``request.GET``)
or a ``page`` variable specified in the URLconf.
@ -87,7 +86,7 @@ MultipleObjectMixin
: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`.
provide an implementation for :meth:`get_paginator`.
.. attribute:: context_object_name
@ -112,7 +111,7 @@ MultipleObjectMixin
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`.
:attr:`paginate_by`.
.. method:: get_paginator(queryset, per_page, orphans=0, allow_empty_first_page=True)
@ -131,7 +130,7 @@ MultipleObjectMixin
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,
:attr:`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

View File

@ -48,7 +48,7 @@ TemplateResponseMixin
.. attribute:: template_name
The full name of a template to use as defined by a string. Not defining
a template_name will raise a
a ``template_name`` will raise a
:class:`django.core.exceptions.ImproperlyConfigured` exception.
.. attribute:: response_class
@ -73,15 +73,13 @@ TemplateResponseMixin
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.
Calls :meth:`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).
If :attr:`template_name` is specified, the default implementation will
return a list containing :attr:`template_name` (if it is specified).

View File

@ -21,8 +21,7 @@ SingleObjectMixin
.. attribute:: queryset
A ``QuerySet`` that represents the objects. If provided, the value of
:attr:`SingleObjectMixin.queryset` supersedes the value provided for
:attr:`SingleObjectMixin.model`.
``queryset`` supersedes the value provided for :attr:`model`.
.. attribute:: slug_field
@ -51,38 +50,38 @@ SingleObjectMixin
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`.
source of objects; otherwise, :meth:`get_queryset` will be used.
``get_object()`` looks for a :attr:`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:`slug_url_kwarg` argument, and performs a
slug lookup using the :attr:`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.
this view will display. By default, :meth:`get_queryset` returns the
value of the :attr:`queryset` attribute if it is set, otherwise
it constructs a :class:`~django.db.models.query.QuerySet` by calling
the `all()` method on the :attr:`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'``.
data that this view is manipulating. If :attr:`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.
.. method:: get_slug_field()
Returns the name of a slug field to be used to look up by slug. By
default this simply returns the value of :attr:`slug_field`.
**Context**
* ``object``: The object that this view is displaying. If

View File

@ -114,10 +114,10 @@ Browsers that support X-Frame-Options
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Internet Explorer 8+
* Firefox 3.6.9+
* Opera 10.5+
* Safari 4+
* Chrome 4.1+
* Firefox 3.6.9+
* Opera 10.5+
* Safari 4+
* Chrome 4.1+
See also
~~~~~~~~

View File

@ -24,7 +24,7 @@ the following:
* Add :mod:`django.contrib.admindocs` to your :setting:`INSTALLED_APPS`.
* Add ``(r'^admin/doc/', include('django.contrib.admindocs.urls'))`` to
your :data:`urlpatterns`. Make sure it's included *before* the
your ``urlpatterns``. Make sure it's included *before* the
``r'^admin/'`` entry, so that requests to ``/admin/doc/`` don't get
handled by the latter entry.
* Install the docutils Python module (http://docutils.sf.net/).

View File

@ -170,7 +170,7 @@ subclass::
``fields`` option (for more complex layout needs see the
:attr:`~ModelAdmin.fieldsets` option described in the next section). For
example, you could define a simpler version of the admin form for the
``django.contrib.flatpages.FlatPage`` model as follows::
:class:`django.contrib.flatpages.models.FlatPage` model as follows::
class FlatPageAdmin(admin.ModelAdmin):
fields = ('url', 'title', 'content')
@ -214,8 +214,8 @@ subclass::
a dictionary of information about the fieldset, including a list of fields
to be displayed in it.
A full example, taken from the :class:`django.contrib.flatpages.FlatPage`
model::
A full example, taken from the
:class:`django.contrib.flatpages.models.FlatPage` model::
class FlatPageAdmin(admin.ModelAdmin):
fieldsets = (
@ -359,7 +359,7 @@ subclass::
Note that the key in the dictionary is the actual field class, *not* a
string. The value is another dictionary; these arguments will be passed to
:meth:`~django.forms.Field.__init__`. See :doc:`/ref/forms/api` for
the form field's ``__init__()`` method. See :doc:`/ref/forms/api` for
details.
.. warning::
@ -588,7 +588,7 @@ subclass::
.. versionadded:: 1.4
* a class inheriting from :mod:`django.contrib.admin.SimpleListFilter`,
* a class inheriting from ``django.contrib.admin.SimpleListFilter``,
which you need to provide the ``title`` and ``parameter_name``
attributes to and override the ``lookups`` and ``queryset`` methods,
e.g.::
@ -677,7 +677,7 @@ subclass::
* a tuple, where the first element is a field name and the second
element is a class inheriting from
:mod:`django.contrib.admin.FieldListFilter`, for example::
``django.contrib.admin.FieldListFilter``, for example::
from django.contrib.admin import BooleanFieldListFilter
@ -959,10 +959,9 @@ templates used by the :class:`ModelAdmin` views:
.. attribute:: ModelAdmin.delete_selected_confirmation_template
Path to a custom template, used by the :meth:`delete_selected`
action method for displaying a confirmation page when deleting one
or more objects. See the :doc:`actions
documentation</ref/contrib/admin/actions>`.
Path to a custom template, used by the ``delete_selected`` action method
for displaying a confirmation page when deleting one or more objects. See
the :doc:`actions documentation</ref/contrib/admin/actions>`.
.. attribute:: ModelAdmin.object_history_template
@ -1134,9 +1133,8 @@ templates used by the :class:`ModelAdmin` views:
Since this is usually not what you want, Django provides a convenience
wrapper to check permissions and mark the view as non-cacheable. This
wrapper is :meth:`AdminSite.admin_view` (i.e.
``self.admin_site.admin_view`` inside a ``ModelAdmin`` instance); use it
like so::
wrapper is ``AdminSite.admin_view()`` (i.e. ``self.admin_site.admin_view``
inside a ``ModelAdmin`` instance); use it like so::
class MyModelAdmin(admin.ModelAdmin):
def get_urls(self):
@ -1156,7 +1154,7 @@ templates used by the :class:`ModelAdmin` views:
If the page is cacheable, but you still want the permission check to be
performed, you can pass a ``cacheable=True`` argument to
:meth:`AdminSite.admin_view`::
``AdminSite.admin_view()``::
(r'^my_view/$', self.admin_site.admin_view(self.my_view, cacheable=True))

View File

@ -66,15 +66,17 @@ In the ``models.py`` we'll define a ``CommentWithTitle`` model::
class CommentWithTitle(Comment):
title = models.CharField(max_length=300)
Most custom comment models will subclass the :class:`Comment` model. However,
Most custom comment models will subclass the
:class:`~django.contrib.comments.models.Comment` model. However,
if you want to substantially remove or change the fields available in the
:class:`Comment` model, but don't want to rewrite the templates, you could
try subclassing from :class:`BaseCommentAbstractModel`.
:class:`~django.contrib.comments.models.Comment` model, but don't want to
rewrite the templates, you could try subclassing from
``BaseCommentAbstractModel``.
Next, we'll define a custom comment form in ``forms.py``. This is a little more
tricky: we have to both create a form and override
:meth:`CommentForm.get_comment_model` and
:meth:`CommentForm.get_comment_create_data` to return deal with our custom title
``CommentForm.get_comment_model()`` and
``CommentForm.get_comment_create_data()`` to return deal with our custom title
field::
from django import forms
@ -139,7 +141,7 @@ however.
Return the :class:`~django.db.models.Model` class to use for comments. This
model should inherit from
:class:`django.contrib.comments.models.BaseCommentAbstractModel`, which
``django.contrib.comments.models.BaseCommentAbstractModel``, which
defines necessary core fields.
The default implementation returns
@ -170,33 +172,33 @@ however.
attribute when rendering your comment form.
The default implementation returns a reverse-resolved URL pointing
to the :func:`post_comment` view.
to the ``post_comment()`` view.
.. note::
If you provide a custom comment model and/or form, but you
want to use the default :func:`post_comment` view, you will
want to use the default ``post_comment()`` view, you will
need to be aware that it requires the model and form to have
certain additional attributes and methods: see the
:func:`post_comment` view documentation for details.
``django.contrib.comments.views.post_comment()`` view for details.
.. function:: get_flag_url()
Return the URL for the "flag this comment" view.
The default implementation returns a reverse-resolved URL pointing
to the :func:`django.contrib.comments.views.moderation.flag` view.
to the ``django.contrib.comments.views.moderation.flag()`` view.
.. function:: get_delete_url()
Return the URL for the "delete this comment" view.
The default implementation returns a reverse-resolved URL pointing
to the :func:`django.contrib.comments.views.moderation.delete` view.
to the ``django.contrib.comments.views.moderation.delete()`` view.
.. function:: get_approve_url()
Return the URL for the "approve this comment from moderation" view.
The default implementation returns a reverse-resolved URL pointing
to the :func:`django.contrib.comments.views.moderation.approve` view.
to the ``django.contrib.comments.views.moderation.approve()`` view.

View File

@ -136,7 +136,7 @@ Feeds
=====
Suppose you want to export a :doc:`feed </ref/contrib/syndication>` of the
latest comments, you can use the built-in :class:`LatestCommentFeed`. Just
latest comments, you can use the built-in ``LatestCommentFeed``. Just
enable it in your project's ``urls.py``:
.. code-block:: python
@ -166,7 +166,7 @@ features (all of which or only certain can be enabled):
* Close comments after a particular (user-defined) number of days.
* Email new comments to the site-staff.
To enable comment moderation, we subclass the :class:`CommentModerator` and
To enable comment moderation, we subclass the ``CommentModerator`` and
register it with the moderation features we want. Let's suppose we want to
close comments after 7 days of posting and also send out an email to the
site staff. In ``blog/models.py``, we register a comment moderator in the

View File

@ -185,15 +185,14 @@ via two methods:
be moderated using the options defined in the
``CommentModerator`` subclass. If any of the models are
already registered for moderation, the exception
:exc:`AlreadyModerated` will be raised.
``AlreadyModerated`` will be raised.
.. function:: moderator.unregister(model_or_iterable)
Takes one argument: a model class or list of model classes,
and removes the model or models from the set of models which
are being moderated. If any of the models are not currently
being moderated, the exception
:exc:`NotModerated` will be raised.
being moderated, the exception ``NotModerated`` will be raised.
Customizing the moderation system
@ -207,8 +206,8 @@ models with an instance of the subclass.
.. class:: Moderator
In addition to the :meth:`Moderator.register` and
:meth:`Moderator.unregister` methods detailed above, the following methods
In addition to the :func:`moderator.register` and
:func:`moderator.unregister` methods detailed above, the following methods
on :class:`Moderator` can be overridden to achieve customized behavior:
.. method:: connect

View File

@ -81,8 +81,8 @@ Arguments sent with this signal:
:meth:`~django.db.models.Model.save` again.
``flag``
The :class:`~django.contrib.comments.models.CommentFlag` that's been
attached to the comment.
The ``django.contrib.comments.models.CommentFlag`` that's been attached to
the comment.
``created``
``True`` if this is a new flag; ``False`` if it's a duplicate flag.

View File

@ -453,7 +453,7 @@ Generic relations in forms and admin
------------------------------------
The :mod:`django.contrib.contenttypes.generic` module provides
:class:`~django.contrib.contenttypes.generic.BaseGenericInlineFormSet`,
``BaseGenericInlineFormSet``,
:class:`~django.contrib.contenttypes.generic.GenericTabularInline`
and :class:`~django.contrib.contenttypes.generic.GenericStackedInline`
(the last two are subclasses of
@ -480,3 +480,9 @@ information.
The name of the integer field that represents the ID of the related
object. Defaults to ``object_id``.
.. class:: GenericTabularInline
.. class:: GenericStackedInline
Subclasses of :class:`GenericInlineModelAdmin` with stacked and tabular
layouts, respectively.

View File

@ -43,7 +43,7 @@ How to use Databrowse
.. versionchanged:: 1.4
Since Django 1.4, it is possible to register several models in the same
call to :func:`~databrowse.site.register`.
call to ``databrowse.site.register()``.
It doesn't matter where you put this, as long as it gets executed at some
point. A good place for it is in your :doc:`URLconf file
@ -71,7 +71,7 @@ code. Simply add the following import to your URLconf::
from django.contrib.auth.decorators import login_required
Then modify the :doc:`URLconf </topics/http/urls>` so that the
:func:`databrowse.site.root` view is decorated with
``databrowse.site.root()`` view is decorated with
:func:`django.contrib.auth.decorators.login_required`::
(r'^databrowse/(.*)', login_required(databrowse.site.root)),

View File

@ -194,7 +194,7 @@ Via the Python API
If you add or modify flatpages via your own code, you will likely want to
check for duplicate flatpage URLs within the same site. The flatpage form
used in the admin performs this validation check, and can be imported from
:class:`django.contrib.flatpages.forms.FlatPageForm` and used in your own
``django.contrib.flatpages.forms.FlatPageForm`` and used in your own
views.
Flatpage templates
@ -264,7 +264,7 @@ Displaying ``registration_required`` flatpages
By default, the :ttag:`get_flatpages` templatetag will only show
flatpages that are marked ``registration_required = False``. If you
want to display registration-protected flatpages, you need to specify
an authenticated user using a``for`` clause.
an authenticated user using a ``for`` clause.
For example:

View File

@ -25,9 +25,8 @@ application takes care of the following workflow:
a. If it's valid, displays a preview page.
b. If it's not valid, redisplays the form with error messages.
3. When the "confirmation" form is submitted from the preview page, calls
a hook that you define -- a
:meth:`~django.contrib.formtools.preview.FormPreview.done()` method that gets
passed the valid data.
a hook that you define -- a ``done()`` method that gets passed the valid
data.
The framework enforces the required preview by passing a shared-secret hash to
the preview page via hidden form fields. If somebody tweaks the form parameters
@ -51,8 +50,7 @@ How to use ``FormPreview``
directory to your :setting:`TEMPLATE_DIRS` setting.
2. Create a :class:`~django.contrib.formtools.preview.FormPreview` subclass that
overrides the :meth:`~django.contrib.formtools.preview.FormPreview.done()`
method::
overrides the ``done()`` method::
from django.contrib.formtools.preview import FormPreview
from myapp.models import SomeModel
@ -92,13 +90,15 @@ How to use ``FormPreview``
A :class:`~django.contrib.formtools.preview.FormPreview` class is a simple Python class
that represents the preview workflow.
:class:`~django.contrib.formtools.preview.FormPreview` classes must subclass
``django.contrib.formtools.preview.FormPreview`` and override the
:meth:`~django.contrib.formtools.preview.FormPreview.done()` method. They can live
anywhere in your codebase.
``django.contrib.formtools.preview.FormPreview`` and override the ``done()``
method. They can live anywhere in your codebase.
``FormPreview`` templates
=========================
.. attribute:: FormPreview.form_template
.. attribute:: FormPreview.preview_template
By default, the form is rendered via the template :file:`formtools/form.html`,
and the preview page is rendered via the template :file:`formtools/preview.html`.
These values can be overridden for a particular form preview by setting

View File

@ -54,7 +54,8 @@ you just have to do these things:
4. Add ``django.contrib.formtools`` to your
:setting:`INSTALLED_APPS` list in your settings file.
5. Point your URLconf at your :class:`WizardView` :meth:`~WizardView.as_view` method.
5. Point your URLconf at your :class:`WizardView` :meth:`~WizardView.as_view`
method.
Defining ``Form`` classes
-------------------------
@ -89,6 +90,9 @@ the message itself. Here's what the :file:`forms.py` might look like::
Creating a ``WizardView`` subclass
----------------------------------
.. class:: SessionWizardView
.. class:: CookieWizardView
The next step is to create a
:class:`django.contrib.formtools.wizard.views.WizardView` subclass. You can
also use the :class:`SessionWizardView` or :class:`CookieWizardView` classes
@ -225,9 +229,11 @@ Here's a full example template:
Hooking the wizard into a URLconf
---------------------------------
.. method:: WizardView.as_view
Finally, we need to specify which forms to use in the wizard, and then
deploy the new :class:`WizardView` object at a URL in the ``urls.py``. The
wizard's :meth:`as_view` method takes a list of your
wizard's ``as_view()`` method takes a list of your
:class:`~django.forms.Form` classes as an argument during instantiation::
from django.conf.urls import patterns
@ -346,9 +352,9 @@ Advanced ``WizardView`` methods
used as the form for step ``step``.
Returns an :class:`~django.db.models.Model` object which will be passed as
the :attr:`~django.forms.ModelForm.instance` argument when instantiating the
ModelForm for step ``step``. If no instance object was provided while
initializing the form wizard, ``None`` will be returned.
the ``instance`` argument when instantiating the ``ModelForm`` for step
``step``. If no instance object was provided while initializing the form
wizard, ``None`` will be returned.
The default implementation::
@ -514,10 +520,10 @@ Providing initial data for the forms
.. attribute:: WizardView.initial_dict
Initial data for a wizard's :class:`~django.forms.Form` objects can be
provided using the optional :attr:`~Wizard.initial_dict` keyword argument.
This argument should be a dictionary mapping the steps to dictionaries
containing the initial data for each step. The dictionary of initial data
will be passed along to the constructor of the step's
provided using the optional :attr:`~WizardView.initial_dict` keyword
argument. This argument should be a dictionary mapping the steps to
dictionaries containing the initial data for each step. The dictionary of
initial data will be passed along to the constructor of the step's
:class:`~django.forms.Form`::
>>> from myapp.forms import ContactForm1, ContactForm2
@ -542,11 +548,13 @@ Providing initial data for the forms
Handling files
==============
.. attribute:: WizardView.file_storage
To handle :class:`~django.forms.FileField` within any step form of the wizard,
you have to add a :attr:`file_storage` to your :class:`WizardView` subclass.
you have to add a ``file_storage`` to your :class:`WizardView` subclass.
This storage will temporarily store the uploaded files for the wizard. The
:attr:`file_storage` attribute should be a
``file_storage`` attribute should be a
:class:`~django.core.files.storage.Storage` subclass.
Django provides a built-in storage class (see :ref:`the built-in filesystem
@ -646,6 +654,8 @@ Usage of ``NamedUrlWizardView``
===============================
.. class:: NamedUrlWizardView
.. class:: NamedUrlSessionWizardView
.. class:: NamedUrlCookieWizardView
There is a :class:`WizardView` subclass which adds named-urls support to the
wizard. By doing this, you can have single urls for every step. You can also

View File

@ -1,6 +1,8 @@
django.contrib.formtools
========================
.. module:: django.contrib.formtools
A set of high-level abstractions for Django forms (:mod:`django.forms`).
.. toctree::

View File

@ -4,20 +4,23 @@
GeoDjango Database API
======================
.. module:: django.contrib.gis.db.models
:synopsis: GeoDjango's database API.
.. _spatial-backends:
Spatial Backends
================
.. module:: django.contrib.gis.db.backends
:synopsis: GeoDjango's spatial database backends.
GeoDjango currently provides the following spatial database backends:
* :mod:`django.contrib.gis.db.backends.postgis`
* :mod:`django.contrib.gis.db.backends.mysql`
* :mod:`django.contrib.gis.db.backends.oracle`
* :mod:`django.contrib.gis.db.backends.spatialite`
* ``django.contrib.gis.db.backends.postgis``
* ``django.contrib.gis.db.backends.mysql``
* ``django.contrib.gis.db.backends.oracle``
* ``django.contrib.gis.db.backends.spatialite``
.. module:: django.contrib.gis.db.models
:synopsis: GeoDjango's database API.
.. _mysql-spatial-limitations:

View File

@ -27,7 +27,7 @@ API Reference
.. class:: Feed
In addition to methods provided by
the :class:`django.contrib.syndication.feeds.Feed`
the :class:`django.contrib.syndication.views.Feed`
base class, GeoDjango's ``Feed`` class provides
the following overrides. Note that these overrides may be done in multiple ways::
@ -71,11 +71,11 @@ API Reference
can be a ``GEOSGeometry`` instance, or a tuple that represents a
point coordinate or bounding box. For example::
class ZipcodeFeed(Feed):
class ZipcodeFeed(Feed):
def item_geometry(self, obj):
# Returns the polygon.
return obj.poly
def item_geometry(self, obj):
# Returns the polygon.
return obj.poly
``SyndicationFeed`` Subclasses
------------------------------

View File

@ -683,7 +683,7 @@ Keyword Argument Description
a method name clashes with an existing
``GeoQuerySet`` method -- if you wanted to use the
``area()`` method on model with a ``PolygonField``
named ``area``, for example.
named ``area``, for example.
===================== =====================================================
Measurement
@ -1043,7 +1043,7 @@ Keyword Argument Description
===================== =====================================================
``relative`` If set to ``True``, the path data will be implemented
in terms of relative moves. Defaults to ``False``,
meaning that absolute moves are used instead.
meaning that absolute moves are used instead.
``precision`` This keyword may be used to specify the number of
significant digits for the coordinates in the SVG

View File

@ -142,10 +142,9 @@ Geometry Objects
.. class:: GEOSGeometry(geo_input[, srid=None])
:param geo_input: Geometry input value
:type geo_input: string or buffer
:param geo_input: Geometry input value (string or buffer)
:param srid: spatial reference identifier
:type srid: integer
:type srid: int
This is the base class for all GEOS geometry objects. It initializes on the
given ``geo_input`` argument, and then assumes the proper geometry subclass
@ -800,7 +799,7 @@ Example::
:param string: string that contains spatial data
:type string: string
:param srid: spatial reference identifier
:type srid: integer
:type srid: int
:rtype: a :class:`GEOSGeometry` corresponding to the spatial data in the string
Example::
@ -966,3 +965,10 @@ location (e.g., ``/home/bob/lib/libgeos_c.so``).
The setting must be the *full* path to the **C** shared library; in
other words you want to use ``libgeos_c.so``, not ``libgeos.so``.
Exceptions
==========
.. exception:: GEOSException
The base GEOS exception, indicates a GEOS-related error.

View File

@ -530,6 +530,6 @@ Finally, :ref:`install Django <installing-official-release>` on your system.
.. rubric:: Footnotes
.. [#] GeoDjango uses the :func:`~ctypes.util.find_library` routine from
:mod:`ctypes.util` to locate shared libraries.
``ctypes.util`` to locate shared libraries.
.. [#] The ``psycopg2`` Windows installers are packaged and maintained by
`Jason Erickson <http://www.stickpeople.com/projects/python/win-psycopg/>`_.

View File

@ -226,7 +226,7 @@ model to represent this data::
class WorldBorder(models.Model):
# Regular Django fields corresponding to the attributes in the
# world borders shapefile.
# world borders shapefile.
name = models.CharField(max_length=50)
area = models.IntegerField()
pop2005 = models.IntegerField('Population 2005')
@ -236,13 +236,13 @@ model to represent this data::
un = models.IntegerField('United Nations Code')
region = models.IntegerField('Region Code')
subregion = models.IntegerField('Sub-Region Code')
lon = models.FloatField()
lat = models.FloatField()
lon = models.FloatField()
lat = models.FloatField()
# GeoDjango-specific: a geometry field (MultiPolygonField), and
# GeoDjango-specific: a geometry field (MultiPolygonField), and
# overriding the default manager with a GeoManager instance.
mpoly = models.MultiPolygonField()
objects = models.GeoManager()
mpoly = models.MultiPolygonField()
objects = models.GeoManager()
# Returns the string representation of the model.
def __unicode__(self):
@ -250,7 +250,7 @@ model to represent this data::
Please note two important things:
1. The ``models`` module is imported from :mod:`django.contrib.gis.db`.
1. The ``models`` module is imported from ``django.contrib.gis.db``.
2. You must override the model's default manager with
:class:`~django.contrib.gis.db.models.GeoManager` to perform spatial queries.

View File

@ -49,6 +49,8 @@ loader can find the default templates.)
Initialization
==============
.. function:: views.sitemap(request, sitemaps, section=None, template_name='sitemap.xml', mimetype='application/xml')
To activate sitemap generation on your Django site, add this line to your
:doc:`URLconf </topics/http/urls>`::
@ -242,9 +244,9 @@ The sitemap framework provides a couple convenience classes for common cases:
The :class:`django.contrib.sitemaps.GenericSitemap` class allows you to
create a sitemap by passing it a dictionary which has to contain at least
a :data:`queryset` entry. This queryset will be used to generate the items
of the sitemap. It may also have a :data:`date_field` entry that
specifies a date field for objects retrieved from the :data:`queryset`.
a ``queryset`` entry. This queryset will be used to generate the items
of the sitemap. It may also have a ``date_field`` entry that
specifies a date field for objects retrieved from the ``queryset``.
This will be used for the :attr:`~Sitemap.lastmod` attribute in the
generated sitemap. You may also pass :attr:`~Sitemap.priority` and
:attr:`~Sitemap.changefreq` keyword arguments to the
@ -283,14 +285,16 @@ Here's an example of a :doc:`URLconf </topics/http/urls>` using both::
Creating a sitemap index
========================
.. function:: views.index(request, sitemaps, template_name='sitemap_index.xml', mimetype='application/xml', sitemap_url_name='django.contrib.sitemaps.views.sitemap')
The sitemap framework also has the ability to create a sitemap index that
references individual sitemap files, one per each section defined in your
:data:`sitemaps` dictionary. The only differences in usage are:
``sitemaps`` dictionary. The only differences in usage are:
* You use two views in your URLconf: :func:`django.contrib.sitemaps.views.index`
and :func:`django.contrib.sitemaps.views.sitemap`.
* The :func:`django.contrib.sitemaps.views.sitemap` view should take a
:data:`section` keyword argument.
``section`` keyword argument.
Here's what the relevant URLconf lines would look like for the example above::
@ -301,7 +305,7 @@ Here's what the relevant URLconf lines would look like for the example above::
This will automatically generate a :file:`sitemap.xml` file that references
both :file:`sitemap-flatpages.xml` and :file:`sitemap-blog.xml`. The
:class:`~django.contrib.sitemaps.Sitemap` classes and the :data:`sitemaps`
:class:`~django.contrib.sitemaps.Sitemap` classes and the ``sitemaps``
dict don't change at all.
You should create an index file if one of your sitemaps has more than 50,000
@ -356,19 +360,20 @@ parameter to the ``sitemap`` and ``index`` views via the URLconf::
Context variables
------------------
When customizing the templates for the :func:`~django.contrib.sitemaps.views.index`
and :func:`~django.contrib.sitemaps.views.sitemaps` views, you can rely on the
When customizing the templates for the
:func:`~django.contrib.sitemaps.views.index` and
:func:`~django.contrib.sitemaps.views.sitemap` views, you can rely on the
following context variables.
Index
-----
The variable :data:`sitemaps` is a list of absolute URLs to each of the sitemaps.
The variable ``sitemaps`` is a list of absolute URLs to each of the sitemaps.
Sitemap
-------
The variable :data:`urlset` is a list of URLs that should appear in the
The variable ``urlset`` is a list of URLs that should appear in the
sitemap. Each URL exposes attributes as defined in the
:class:`~django.contrib.sitemaps.Sitemap` class:
@ -419,14 +424,14 @@ that: :func:`django.contrib.sitemaps.ping_google()`.
.. function:: ping_google
:func:`ping_google` takes an optional argument, :data:`sitemap_url`,
:func:`ping_google` takes an optional argument, ``sitemap_url``,
which should be the absolute path to your site's sitemap (e.g.,
:file:`'/sitemap.xml'`). If this argument isn't provided,
:func:`ping_google` will attempt to figure out your
sitemap by performing a reverse looking in your URLconf.
:func:`ping_google` raises the exception
:exc:`django.contrib.sitemaps.SitemapNotFound` if it cannot determine your
``django.contrib.sitemaps.SitemapNotFound`` if it cannot determine your
sitemap URL.
.. admonition:: Register with Google first!

View File

@ -33,7 +33,7 @@ STATICFILES_DIRS
Default: ``[]``
This setting defines the additional locations the staticfiles app will traverse
if the :class:`FileSystemFinder` finder is enabled, e.g. if you use the
if the ``FileSystemFinder`` finder is enabled, e.g. if you use the
:djadmin:`collectstatic` or :djadmin:`findstatic` management command or use the
static file serving view.
@ -103,19 +103,19 @@ The list of finder backends that know how to find static files in
various locations.
The default will find files stored in the :setting:`STATICFILES_DIRS` setting
(using :class:`django.contrib.staticfiles.finders.FileSystemFinder`) and in a
(using ``django.contrib.staticfiles.finders.FileSystemFinder``) and in a
``static`` subdirectory of each app (using
:class:`django.contrib.staticfiles.finders.AppDirectoriesFinder`)
``django.contrib.staticfiles.finders.AppDirectoriesFinder``)
One finder is disabled by default:
:class:`django.contrib.staticfiles.finders.DefaultStorageFinder`. If added to
``django.contrib.staticfiles.finders.DefaultStorageFinder``. If added to
your :setting:`STATICFILES_FINDERS` setting, it will look for static files in
the default file storage as defined by the :setting:`DEFAULT_FILE_STORAGE`
setting.
.. note::
When using the :class:`AppDirectoriesFinder` finder, make sure your apps
When using the ``AppDirectoriesFinder`` finder, make sure your apps
can be found by staticfiles. Simply add the app to the
:setting:`INSTALLED_APPS` setting of your site.

View File

@ -334,7 +334,7 @@ And the accompanying URLconf::
Feed class reference
--------------------
.. class:: django.contrib.syndication.views.Feed
.. class:: views.Feed
This example illustrates all possible attributes and methods for a
:class:`~django.contrib.syndication.views.Feed` class::

View File

@ -273,9 +273,9 @@ recommended solution.
Should you decide to use ``utf8_bin`` collation for some of your tables with
MySQLdb 1.2.1p2 or 1.2.2, you should still use ``utf8_collation_ci_swedish``
(the default) collation for the :class:`django.contrib.sessions.models.Session`
(the default) collation for the ``django.contrib.sessions.models.Session``
table (usually called ``django_session``) and the
:class:`django.contrib.admin.models.LogEntry` table (usually called
``django.contrib.admin.models.LogEntry`` table (usually called
``django_admin_log``). Those are the two standard tables that use
:class:`~django.db.models.TextField` internally.

View File

@ -292,6 +292,8 @@ Searches for and loads the contents of the named fixture into the database.
The :djadminopt:`--database` option can be used to specify the database
onto which the data will be loaded.
.. django-admin-option:: --ignorenonexistent
.. versionadded:: 1.5
The :djadminopt:`--ignorenonexistent` option can be used to ignore fields that

View File

@ -131,6 +131,21 @@ The Django wrappers for database exceptions behave exactly the same as
the underlying database exceptions. See :pep:`249`, the Python Database API
Specification v2.0, for further information.
.. exception:: models.ProtectedError
Raised to prevent deletion of referenced objects when using
:attr:`django.db.models.PROTECT`. Subclass of :exc:`IntegrityError`.
.. currentmodule:: django.http
Http Exceptions
===============
.. exception:: UnreadablePostError
The :exc:`UnreadablePostError` is raised when a user cancels an upload.
It is available from :mod:`django.http`.
.. currentmodule:: django.db.transaction
Transaction Exceptions

View File

@ -14,7 +14,7 @@ The ``File`` Class
The :class:`File` is a thin wrapper around Python's built-in file object
with some Django-specific additions. Internally, Django uses this class
any time it needs to represent a file.
:class:`File` objects have the following attributes and methods:
.. attribute:: name
@ -148,7 +148,7 @@ below) will also have a couple of extra methods:
Note that the ``content`` argument must be an instance of either
:class:`File` or of a subclass of :class:`File`, such as
:class:`ContentFile`.
:class:`~django.core.files.base.ContentFile`.
.. method:: File.delete([save=True])

View File

@ -38,7 +38,7 @@ The FileSystemStorage Class
.. note::
The :class:`FileSystemStorage.delete` method will not raise
The ``FileSystemStorage.delete()`` method will not raise
raise an exception if the given file name does not exist.
The Storage Class

View File

@ -2,9 +2,7 @@
The Forms API
=============
.. module:: django.forms.forms
.. currentmodule:: django.forms
.. module:: django.forms
.. admonition:: About this document
@ -380,6 +378,9 @@ a form object, and each rendering method returns a Unicode object.
Styling required or erroneous form rows
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. attribute:: Form.error_css_class
.. attribute:: Form.required_css_class
It's pretty common to style form rows and fields that are required or have
errors. For example, you might want to present required form rows in bold and
highlight errors in red.
@ -587,24 +588,24 @@ lazy developers -- they're not the only way a form object can be displayed.
Used to display HTML or access attributes for a single field of a
:class:`Form` instance.
The :meth:`__unicode__` and :meth:`__str__` methods of this object displays
The ``__unicode__()`` and ``__str__()`` methods of this object displays
the HTML for this field.
To retrieve a single ``BoundField``, use dictionary lookup syntax on your form
using the field's name as the key::
>>> form = ContactForm()
>>> print(form['subject'])
<input id="id_subject" type="text" name="subject" maxlength="100" />
>>> form = ContactForm()
>>> print(form['subject'])
<input id="id_subject" type="text" name="subject" maxlength="100" />
To retrieve all ``BoundField`` objects, iterate the form::
>>> form = ContactForm()
>>> for boundfield in form: print(boundfield)
<input id="id_subject" type="text" name="subject" maxlength="100" />
<input type="text" name="message" id="id_message" />
<input type="text" name="sender" id="id_sender" />
<input type="checkbox" name="cc_myself" id="id_cc_myself" />
>>> form = ContactForm()
>>> for boundfield in form: print(boundfield)
<input id="id_subject" type="text" name="subject" maxlength="100" />
<input type="text" name="message" id="id_message" />
<input type="text" name="sender" id="id_sender" />
<input type="checkbox" name="cc_myself" id="id_cc_myself" />
The field-specific output honors the form object's ``auto_id`` setting::
@ -635,7 +636,7 @@ For a field's list of errors, access the field's ``errors`` attribute.
>>> print(f['subject'].errors)
>>> str(f['subject'].errors)
''
''
.. method:: BoundField.css_classes()
@ -644,17 +645,17 @@ indicate required form fields or fields that contain errors. If you're
manually rendering a form, you can access these CSS classes using the
``css_classes`` method::
>>> f = ContactForm(data)
>>> f['message'].css_classes()
'required'
>>> f = ContactForm(data)
>>> f['message'].css_classes()
'required'
If you want to provide some additional classes in addition to the
error and required classes that may be required, you can provide
those classes as an argument::
>>> f = ContactForm(data)
>>> f['message'].css_classes('foo bar')
'foo bar required'
>>> f = ContactForm(data)
>>> f['message'].css_classes('foo bar')
'foo bar required'
.. method:: BoundField.value()

View File

@ -508,9 +508,9 @@ Selector and checkbox widgets
.. attribute:: Select.choices
This attribute is optional when the field does not have a
:attr:`~Field.choices` attribute. If it does, it will override anything
you set here when the attribute is updated on the :class:`Field`.
This attribute is optional when the form field does not have a
``choices`` attribute. If it does, it will override anything you set
here when the attribute is updated on the :class:`Field`.
``NullBooleanSelect``
~~~~~~~~~~~~~~~~~~~~~
@ -662,9 +662,9 @@ Composite widgets
.. attribute:: MultipleHiddenInput.choices
This attribute is optional when the field does not have a
:attr:`~Field.choices` attribute. If it does, it will override anything
you set here when the attribute is updated on the :class:`Field`.
This attribute is optional when the form field does not have a
``choices`` attribute. If it does, it will override anything you set
here when the attribute is updated on the :class:`Field`.
``SplitDateTimeWidget``
~~~~~~~~~~~~~~~~~~~~~~~

View File

@ -111,7 +111,7 @@ It will NOT compress content if any of the following are true:
not to be performed on certain content types.
You can apply GZip compression to individual views using the
:func:`~django.views.decorators.http.gzip_page()` decorator.
:func:`~django.views.decorators.gzip.gzip_page()` decorator.
Conditional GET middleware
--------------------------
@ -124,7 +124,7 @@ Conditional GET middleware
Handles conditional GET operations. If the response has a ``ETag`` or
``Last-Modified`` header, and the request has ``If-None-Match`` or
``If-Modified-Since``, the response is replaced by an
:class:`~django.http.HttpNotModified`.
:class:`~django.http.HttpResponseNotModified`.
Also sets the ``Date`` and ``Content-Length`` response-headers.

View File

@ -113,7 +113,7 @@ define a suitably-named constant for each value::
default=FRESHMAN)
def is_upperclass(self):
return self.year_in_school in (self.JUNIOR, self.SENIOR)
return self.year_in_school in (self.JUNIOR, self.SENIOR)
Though you can define a choices list outside of a model class and then
refer to it, defining the choices and names for each choice inside the
@ -509,8 +509,8 @@ Has one **required** argument:
.. attribute:: FileField.upload_to
A local filesystem path that will be appended to your :setting:`MEDIA_ROOT`
setting to determine the value of the :attr:`~django.core.files.File.url`
attribute.
setting to determine the value of the
:attr:`~django.db.models.fields.files.FieldFile.url` attribute.
This path may contain :func:`~time.strftime` formatting, which will be
replaced by the date/time of the file upload (so that uploaded files don't
@ -564,9 +564,9 @@ takes a few steps:
3. All that will be stored in your database is a path to the file
(relative to :setting:`MEDIA_ROOT`). You'll most likely want to use the
convenience :attr:`~django.core.files.File.url` function provided by
Django. For example, if your :class:`ImageField` is called ``mug_shot``,
you can get the absolute path to your image in a template with
convenience :attr:`~django.db.models.fields.files.FieldFile.url` attribute
provided by Django. For example, if your :class:`ImageField` is called
``mug_shot``, you can get the absolute path to your image in a template with
``{{ object.mug_shot.url }}``.
For example, say your :setting:`MEDIA_ROOT` is set to ``'/home/media'``, and
@ -589,7 +589,7 @@ topic guide.
saved.
The uploaded file's relative URL can be obtained using the
:attr:`~django.db.models.FileField.url` attribute. Internally,
:attr:`~django.db.models.fields.files.FieldFile.url` attribute. Internally,
this calls the :meth:`~django.core.files.storage.Storage.url` method of the
underlying :class:`~django.core.files.storage.Storage` class.
@ -614,9 +614,20 @@ can change the maximum length using the :attr:`~CharField.max_length` argument.
FileField and FieldFile
~~~~~~~~~~~~~~~~~~~~~~~
When you access a :class:`FileField` on a model, you are given an instance
of :class:`FieldFile` as a proxy for accessing the underlying file. This
class has several methods that can be used to interact with file data:
.. currentmodule:: django.db.models.fields.files
.. class:: FieldFile
When you access a :class:`~django.db.models.FileField` on a model, you are
given an instance of :class:`FieldFile` as a proxy for accessing the underlying
file. This class has several attributes and methods that can be used to
interact with file data:
.. attribute:: FieldFile.url
A read-only property to access the file's relative URL by calling the
:meth:`~django.core.files.storage.Storage.url` method of the underlying
:class:`~django.core.files.storage.Storage` class.
.. method:: FieldFile.open(mode='rb')
@ -632,9 +643,9 @@ associated with this instance.
This method takes a filename and file contents and passes them to the storage
class for the field, then associates the stored file with the model field.
If you want to manually associate file data with :class:`FileField`
instances on your model, the ``save()`` method is used to persist that file
data.
If you want to manually associate file data with
:class:`~django.db.models.FileField` instances on your model, the ``save()``
method is used to persist that file data.
Takes two required arguments: ``name`` which is the name of the file, and
``content`` which is an object containing the file's contents. The
@ -672,6 +683,8 @@ to cleanup orphaned files, you'll need to handle it yourself (for instance,
with a custom management command that can be run manually or scheduled to run
periodically via e.g. cron).
.. currentmodule:: django.db.models
``FilePathField``
-----------------
@ -759,8 +772,7 @@ Inherits all attributes and methods from :class:`FileField`, but also
validates that the uploaded object is a valid image.
In addition to the special attributes that are available for :class:`FileField`,
an :class:`ImageField` also has :attr:`~django.core.files.File.height` and
:attr:`~django.core.files.File.width` attributes.
an :class:`ImageField` also has ``height`` and ``width`` attributes.
To facilitate querying on those attributes, :class:`ImageField` has two extra
optional arguments:
@ -1049,26 +1061,36 @@ define the details of how the relation works.
user = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL)
The possible values for :attr:`on_delete` are found in
:mod:`django.db.models`:
The possible values for :attr:`~ForeignKey.on_delete` are found in
:mod:`django.db.models`:
* :attr:`~django.db.models.CASCADE`: Cascade deletes; the default.
* .. attribute:: CASCADE
* :attr:`~django.db.models.PROTECT`: Prevent deletion of the referenced
object by raising :exc:`django.db.models.ProtectedError`, a subclass of
:exc:`django.db.IntegrityError`.
Cascade deletes; the default.
* :attr:`~django.db.models.SET_NULL`: Set the :class:`ForeignKey` null;
this is only possible if :attr:`null` is ``True``.
* .. attribute:: PROTECT
* :attr:`~django.db.models.SET_DEFAULT`: Set the :class:`ForeignKey` to its
default value; a default for the :class:`ForeignKey` must be set.
Prevent deletion of the referenced object by raising
:exc:`~django.db.models.ProtectedError`, a subclass of
:exc:`django.db.IntegrityError`.
* :func:`~django.db.models.SET()`: Set the :class:`ForeignKey` to the value
passed to :func:`~django.db.models.SET()`, or if a callable is passed in,
the result of calling it. In most cases, passing a callable will be
necessary to avoid executing queries at the time your models.py is
imported::
* .. attribute:: SET_NULL
Set the :class:`ForeignKey` null; this is only possible if
:attr:`~Field.null` is ``True``.
* .. attribute:: SET_DEFAULT
Set the :class:`ForeignKey` to its default value; a default for the
:class:`ForeignKey` must be set.
* .. function:: SET()
Set the :class:`ForeignKey` to the value passed to
:func:`~django.db.models.SET()`, or if a callable is passed in,
the result of calling it. In most cases, passing a callable will be
necessary to avoid executing queries at the time your models.py is
imported::
def get_sentinel_user():
return User.objects.get_or_create(username='deleted')[0]
@ -1076,11 +1098,12 @@ define the details of how the relation works.
class MyModel(models.Model):
user = models.ForeignKey(User, on_delete=models.SET(get_sentinel_user))
* :attr:`~django.db.models.DO_NOTHING`: Take no action. If your database
backend enforces referential integrity, this will cause an
:exc:`~django.db.IntegrityError` unless you manually add a SQL ``ON
DELETE`` constraint to the database field (perhaps using
:ref:`initial sql<initial-sql>`).
* .. attribute:: DO_NOTHING
Take no action. If your database backend enforces referential
integrity, this will cause an :exc:`~django.db.IntegrityError` unless
you manually add a SQL ``ON DELETE`` constraint to the database field
(perhaps using :ref:`initial sql<initial-sql>`).
.. _ref-manytomany:

View File

@ -100,7 +100,7 @@ Django quotes column and table names behind the scenes.
.. attribute:: Options.managed
Defaults to ``True``, meaning Django will create the appropriate database
tables in :djadmin:`syncdb` and remove them as part of a :djadmin:`reset`
tables in :djadmin:`syncdb` and remove them as part of a :djadmin:`flush`
management command. That is, Django *manages* the database tables'
lifecycles.

View File

@ -270,7 +270,7 @@ Methods
.. versionadded:: 1.4
Returns a cookie value for a signed cookie, or raises a
:class:`~django.core.signing.BadSignature` exception if the signature is
``django.core.signing.BadSignature`` exception if the signature is
no longer valid. If you provide the ``default`` argument the exception
will be suppressed and that default value will be returned instead.

View File

@ -2204,7 +2204,7 @@ startproject <startproject>` management command will create a simple
``wsgi.py`` file with an ``application`` callable in it, and point this setting
to that ``application``.
If not set, the return value of :func:`django.core.wsgi.get_wsgi_application`
If not set, the return value of ``django.core.wsgi.get_wsgi_application()``
will be used. In this case, the behavior of :djadmin:`runserver` will be
identical to previous Django versions.

View File

@ -436,9 +436,8 @@ Sent when Django begins processing an HTTP request.
Arguments sent with this signal:
``sender``
The handler class -- e.g.
:class:`django.core.handlers.wsgi.WsgiHandler` -- that handled
the request.
The handler class -- e.g. ``django.core.handlers.wsgi.WsgiHandler`` -- that
handled the request.
request_finished
----------------
@ -498,7 +497,7 @@ setting_changed
:module:
This signal is sent when the value of a setting is changed through the
:meth:`django.test.TestCase.setting` context manager or the
``django.test.TestCase.settings()`` context manager or the
:func:`django.test.utils.override_settings` decorator/context manager.
It's actually sent twice: when the new value is applied ("setup") and when the
@ -560,8 +559,8 @@ Arguments sent with this signal:
``sender``
The database wrapper class -- i.e.
:class:`django.db.backends.postgresql_psycopg2.DatabaseWrapper` or
:class:`django.db.backends.mysql.DatabaseWrapper`, etc.
``django.db.backends.postgresql_psycopg2.DatabaseWrapper`` or
``django.db.backends.mysql.DatabaseWrapper``, etc.
``connection``
The database connection that was opened. This can be used in a

View File

@ -121,15 +121,14 @@ Methods
used as the response instead of the original response object (and
will be passed to the next post rendering callback etc.)
.. method:: SimpleTemplateResponse.render():
.. method:: SimpleTemplateResponse.render()
Sets :attr:`response.content` to the result obtained by
Sets ``response.content`` to the result obtained by
:attr:`SimpleTemplateResponse.rendered_content`, runs all post-rendering
callbacks, and returns the resulting response object.
:meth:`~SimpleTemplateResponse.render()` will only have an effect
the first time it is called. On subsequent calls, it will return
the result obtained from the first call.
``render()`` will only have an effect the first time it is called. On
subsequent calls, it will return the result obtained from the first call.
TemplateResponse objects
@ -188,24 +187,23 @@ returned to the client, it must be rendered. The rendering process takes the
intermediate representation of template and context, and turns it into the
final byte stream that can be served to the client.
There are three circumstances under which a TemplateResponse will be
There are three circumstances under which a ``TemplateResponse`` will be
rendered:
* When the TemplateResponse instance is explicitly rendered, using
* When the ``TemplateResponse`` instance is explicitly rendered, using
the :meth:`SimpleTemplateResponse.render()` method.
* When the content of the response is explicitly set by assigning
:attr:`response.content`.
``response.content``.
* After passing through template response middleware, but before
passing through response middleware.
A TemplateResponse can only be rendered once. The first call to
:meth:`SimpleTemplateResponse.render` sets the content of the
response; subsequent rendering calls do not change the response
content.
A ``TemplateResponse`` can only be rendered once. The first call to
:meth:`SimpleTemplateResponse.render` sets the content of the response;
subsequent rendering calls do not change the response content.
However, when :attr:`response.content` is explicitly assigned, the
However, when ``response.content`` is explicitly assigned, the
change is always applied. If you want to force the content to be
re-rendered, you can re-evaluate the rendered content, and assign
the content of the response manually::

View File

@ -558,15 +558,17 @@ Note that these paths should use Unix-style forward slashes, even on Windows.
The Python API
~~~~~~~~~~~~~~
Django has two ways to load templates from files:
.. module:: django.template.loader
.. function:: django.template.loader.get_template(template_name)
``django.template.loader`` has two functions to load templates from files:
.. function:: get_template(template_name)
``get_template`` returns the compiled template (a ``Template`` object) for
the template with the given name. If the template doesn't exist, it raises
``django.template.TemplateDoesNotExist``.
.. function:: django.template.loader.select_template(template_name_list)
.. function:: select_template(template_name_list)
``select_template`` is just like ``get_template``, except it takes a list
of template names. Of the list, it returns the first template that exists.
@ -631,11 +633,19 @@ by editing your :setting:`TEMPLATE_LOADERS` setting. :setting:`TEMPLATE_LOADERS`
should be a tuple of strings, where each string represents a template loader
class. Here are the template loaders that come with Django:
.. currentmodule:: django.template.loaders
``django.template.loaders.filesystem.Loader``
.. class:: filesystem.Loader
Loads templates from the filesystem, according to :setting:`TEMPLATE_DIRS`.
This loader is enabled by default.
``django.template.loaders.app_directories.Loader``
.. class:: app_directories.Loader
Loads templates from Django apps on the filesystem. For each app in
:setting:`INSTALLED_APPS`, the loader looks for a ``templates``
subdirectory. If the directory exists, Django looks for templates in there.
@ -670,12 +680,18 @@ class. Here are the template loaders that come with Django:
This loader is enabled by default.
``django.template.loaders.eggs.Loader``
.. class:: eggs.Loader
Just like ``app_directories`` above, but it loads templates from Python
eggs rather than from the filesystem.
This loader is disabled by default.
``django.template.loaders.cached.Loader``
.. class:: cached.Loader
By default, the templating system will read and compile your templates every
time they need to be rendered. While the Django templating system is quite
fast, the overhead from reading and compiling templates can add up.

View File

@ -370,7 +370,7 @@ block are output::
In the above, if ``athlete_list`` is not empty, the number of athletes will be
displayed by the ``{{ athlete_list|length }}`` variable.
As you can see, the ``if`` tag may take one or several `` {% elif %}``
As you can see, the ``if`` tag may take one or several ``{% elif %}``
clauses, as well as an ``{% else %}`` clause that will be displayed if all
previous conditions fail. These clauses are optional.

View File

@ -94,7 +94,6 @@ include()
application and instance namespaces.
:arg module: URLconf module (or module name)
:type module: Module or string
:arg namespace: Instance namespace for the URL entries being included
:type namespace: string
:arg app_name: Application namespace for the URL entries being included
@ -153,4 +152,3 @@ value should suffice.
See the documentation about :ref:`the 500 (HTTP Internal Server Error) view
<http_internal_server_error_view>` for more information.

View File

@ -192,8 +192,7 @@ The functions defined in this module share the following properties:
Like ``decorator_from_middleware``, but returns a function
that accepts the arguments to be passed to the middleware_class.
For example, the :func:`~django.views.decorators.cache.cache_page`
decorator is created from the
:class:`~django.middleware.cache.CacheMiddleware` like this::
decorator is created from the ``CacheMiddleware`` like this::
cache_page = decorator_from_middleware_with_args(CacheMiddleware)
@ -284,15 +283,15 @@ The functions defined in this module share the following properties:
.. function:: smart_str(s, encoding='utf-8', strings_only=False, errors='strict')
Alias of :func:`smart_bytes` on Python 2 and :func:`smart_text` on Python
3. This function returns a :class:`str` or a lazy string.
3. This function returns a ``str`` or a lazy string.
For instance, this is suitable for writing to :attr:`sys.stdout` on
For instance, this is suitable for writing to :data:`sys.stdout` on
Python 2 and 3.
.. function:: force_str(s, encoding='utf-8', strings_only=False, errors='strict')
Alias of :func:`force_bytes` on Python 2 and :func:`force_text` on Python
3. This function always returns a :class:`str`.
3. This function always returns a ``str``.
.. function:: iri_to_uri(iri)
@ -626,12 +625,12 @@ escaping HTML.
.. function:: base36_to_int(s)
Converts a base 36 string to an integer. On Python 2 the output is
guaranteed to be an :class:`int` and not a :class:`long`.
guaranteed to be an ``int`` and not a ``long``.
.. function:: int_to_base36(i)
Converts a positive integer to a base 36 string. On Python 2 ``i`` must be
smaller than :attr:`sys.maxint`.
smaller than :data:`sys.maxint`.
``django.utils.safestring``
===========================
@ -649,12 +648,12 @@ appropriate entities.
.. versionadded:: 1.5
A :class:`bytes` subclass that has been specifically marked as "safe"
A ``bytes`` subclass that has been specifically marked as "safe"
(requires no further escaping) for HTML output purposes.
.. class:: SafeString
A :class:`str` subclass that has been specifically marked as "safe"
A ``str`` subclass that has been specifically marked as "safe"
(requires no further escaping) for HTML output purposes. This is
:class:`SafeBytes` on Python 2 and :class:`SafeText` on Python 3.
@ -662,7 +661,7 @@ appropriate entities.
.. versionadded:: 1.5
A :class:`str` (in Python 3) or :class:`unicode` (in Python 2) subclass
A ``str`` (in Python 3) or ``unicode`` (in Python 2) subclass
that has been specifically marked as "safe" for HTML output purposes.
.. class:: SafeUnicode

View File

@ -119,7 +119,7 @@ to, or in lieu of custom ``field.clean()`` methods.
.. data:: validate_ipv6_address
Uses :mod:`django.utils.ipv6` to check the validity of an IPv6 address.
Uses ``django.utils.ipv6`` to check the validity of an IPv6 address.
``validate_ipv46_address``
--------------------------

View File

@ -47,7 +47,7 @@ should be updated to use the new :ref:`class-based runners
Syndication feeds
-----------------
The :class:`django.contrib.syndication.feeds.Feed` class is being
The ``django.contrib.syndication.feeds.Feed`` class is being
replaced by the :class:`django.contrib.syndication.views.Feed` class.
The old ``feeds.Feed`` class is deprecated. The new class has an
almost identical API, but allows instances to be used as views.

View File

@ -345,10 +345,10 @@ in 1.2 is support for multiple spatial databases. As a result,
the following :ref:`spatial database backends <spatial-backends>`
are now included:
* :mod:`django.contrib.gis.db.backends.postgis`
* :mod:`django.contrib.gis.db.backends.mysql`
* :mod:`django.contrib.gis.db.backends.oracle`
* :mod:`django.contrib.gis.db.backends.spatialite`
* ``django.contrib.gis.db.backends.postgis``
* ``django.contrib.gis.db.backends.mysql``
* ``django.contrib.gis.db.backends.oracle``
* ``django.contrib.gis.db.backends.spatialite``
GeoDjango now supports the rich capabilities added
in the `PostGIS 1.5 release <http://postgis.refractions.net/documentation/manual-1.5/>`_.
@ -986,7 +986,7 @@ should be updated to use the new :ref:`class-based runners
``Feed`` in ``django.contrib.syndication.feeds``
------------------------------------------------
The :class:`django.contrib.syndication.feeds.Feed` class has been
The ``django.contrib.syndication.feeds.Feed`` class has been
replaced by the :class:`django.contrib.syndication.views.Feed` class.
The old ``feeds.Feed`` class is deprecated, and will be removed in
Django 1.4.

View File

@ -150,7 +150,7 @@ process has been on adding lots of smaller, long standing feature
requests. These include:
* Improved tools for accessing and manipulating the current Site via
:func:`django.contrib.sites.models.get_current_site`.
``django.contrib.sites.models.get_current_site()``.
* A :class:`~django.test.client.RequestFactory` for mocking
requests in tests.

View File

@ -140,7 +140,7 @@ attribute.
Changes to ``USStateField``
===========================
The :mod:`django.contrib.localflavor` application contains collections
The ``django.contrib.localflavor`` application contains collections
of code relevant to specific countries or cultures. One such is
``USStateField``, which provides a field for storing the two-letter postal
abbreviation of a U.S. state. This field has consistently caused problems,
@ -167,13 +167,13 @@ as a pair of changes:
independent nations -- the Federated States of Micronesia, the
Republic of the Marshall Islands and the Republic of Palau -- which
are serviced under treaty by the U.S. postal system. A new form
widget, :class:`django.contrib.localflavor.us.forms.USPSSelect`, is
widget, ``django.contrib.localflavor.us.forms.USPSSelect``, is
also available and provides the same set of choices.
Additionally, several finer-grained choice tuples are provided which
allow mixing and matching of subsets of the U.S. states and
territories, and other locations serviced by the U.S. postal
system. Consult the :mod:`django.contrib.localflavor` documentation
system. Consult the ``django.contrib.localflavor`` documentation
for more details.
The change to `USStateField` is technically backwards-incompatible for

View File

@ -367,9 +367,8 @@ In earlier Django versions, when a model instance containing a
file from the backend storage. This opened the door to several data-loss
scenarios, including rolled-back transactions and fields on different models
referencing the same file. In Django 1.3, when a model is deleted the
:class:`~django.db.models.FileField`'s
:func:`~django.db.models.FileField.delete` method won't be called. If you
need cleanup of orphaned files, you'll need to handle it yourself (for
:class:`~django.db.models.FileField`'s ``delete()`` method won't be called. If
you need cleanup of orphaned files, you'll need to handle it yourself (for
instance, with a custom management command that can be run manually or
scheduled to run periodically via e.g. cron).

View File

@ -504,7 +504,7 @@ Django 1.4 also includes several smaller improvements worth noting:
page.
* The ``django.contrib.auth.models.check_password`` function has been moved
to the :mod:`django.contrib.auth.utils` module. Importing it from the old
to the ``django.contrib.auth.utils`` module. Importing it from the old
location will still work, but you should update your imports.
* The :djadmin:`collectstatic` management command gained a ``--clear`` option

View File

@ -564,7 +564,7 @@ Django 1.4 also includes several smaller improvements worth noting:
page.
* The ``django.contrib.auth.models.check_password`` function has been moved
to the :mod:`django.contrib.auth.utils` module. Importing it from the old
to the ``django.contrib.auth.utils`` module. Importing it from the old
location will still work, but you should update your imports.
* The :djadmin:`collectstatic` management command gained a ``--clear`` option

View File

@ -888,10 +888,10 @@ object, Django raises an exception.
``MySQLdb``-specific exceptions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The MySQL backend historically has raised :class:`MySQLdb.OperationalError`
The MySQL backend historically has raised ``MySQLdb.OperationalError``
when a query triggered an exception. We've fixed this bug, and we now raise
:exc:`django.db.DatabaseError` instead. If you were testing for
:class:`MySQLdb.OperationalError`, you'll need to update your ``except``
``MySQLdb.OperationalError``, you'll need to update your ``except``
clauses.
Database connection's thread-locality

View File

@ -184,10 +184,10 @@ Manually managing a user's password
If you'd like to manually authenticate a user by comparing a plain-text
password to the hashed password in the database, use the convenience
function :func:`django.contrib.auth.hashers.check_password`. It takes two
arguments: the plain-text password to check, and the full value of a
user's ``password`` field in the database to check against, and returns
``True`` if they match, ``False`` otherwise.
function :func:`check_password`. It takes two arguments: the plain-text
password to check, and the full value of a user's ``password`` field in the
database to check against, and returns ``True`` if they match, ``False``
otherwise.
.. function:: make_password(password[, salt, hashers])
@ -202,11 +202,11 @@ Manually managing a user's password
``'unsalted_md5'`` (only for backward compatibility) and ``'crypt'``
if you have the ``crypt`` library installed. If the password argument is
``None``, an unusable password is returned (a one that will be never
accepted by :func:`django.contrib.auth.hashers.check_password`).
accepted by :func:`check_password`).
.. function:: is_password_usable(encoded_password)
.. versionadded:: 1.4
Checks if the given string is a hashed password that has a chance
of being verified against :func:`django.contrib.auth.hashers.check_password`.
of being verified against :func:`check_password`.

View File

@ -666,6 +666,8 @@ pickling.)
Accessing the cache
-------------------
.. function:: django.core.cache.get_cache(backend, **kwargs)
The cache module, ``django.core.cache``, has a ``cache`` object that's
automatically created from the ``'default'`` entry in the :setting:`CACHES`
setting::
@ -678,7 +680,7 @@ If you have multiple caches defined in :setting:`CACHES`, then you can use
>>> from django.core.cache import get_cache
>>> cache = get_cache('alternate')
If the named key does not exist, :exc:`InvalidCacheBackendError` will be raised.
If the named key does not exist, ``InvalidCacheBackendError`` will be raised.
Basic usage
@ -836,7 +838,7 @@ key version to set or get. For example::
'hello world!'
The version of a specific key can be incremented and decremented using
the :func:`incr_version()` and :func:`decr_version()` methods. This
the ``incr_version()`` and ``decr_version()`` methods. This
enables specific keys to be bumped to a new version, leaving other
keys unaffected. Continuing our previous example::
@ -871,7 +873,7 @@ parts), you can provide a custom key function.
The :setting:`KEY_FUNCTION <CACHES-KEY_FUNCTION>` cache setting
specifies a dotted-path to a function matching the prototype of
:func:`make_key()` above. If provided, this custom key function will
``make_key()`` above. If provided, this custom key function will
be used instead of the default key combining function.
Cache key warnings

View File

@ -257,9 +257,9 @@ Specifying ``model = Publisher`` is really just shorthand for saying
``queryset = Publisher.objects.all()``. However, by using ``queryset``
to define a filtered list of objects you can be more specific about the
objects that will be visible in the view (see :doc:`/topics/db/queries`
for more information about :class:`QuerySet` objects, and see the
:doc:`class-based views reference </ref/class-based-views/index>` for the
complete details).
for more information about :class:`~django.db.models.query.QuerySet` objects,
and see the :doc:`class-based views reference </ref/class-based-views/index>`
for the complete details).
To pick a simple example, we might want to order a list of books by
publication date, with the most recent first::
@ -312,9 +312,9 @@ what if we wanted to write a view that displayed all the books by some arbitrary
publisher?
Handily, the ``ListView`` has a
:meth:`~django.views.generic.detail.ListView.get_queryset` method we can
override. Previously, it has just been returning the value of the ``queryset``
attribute, but now we can add more logic.
:meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset` method we
can override. Previously, it has just been returning the value of the
``queryset`` attribute, but now we can add more logic.
The key part to making this work is that when class-based views are called,
various useful things are stored on ``self``; as well as the request

View File

@ -7,10 +7,10 @@ Form processing generally has 3 paths:
* POST with invalid data (typically redisplay form with errors)
* POST with valid data (process the data and typically redirect)
Implementing this yourself often results in a lot of repeated
boilerplate code (see :ref:`Using a form in a
view<using-a-form-in-a-view>`). To help avoid this, Django provides a
collection of generic class-based views for form processing.
Implementing this yourself often results in a lot of repeated boilerplate code
(see :ref:`Using a form in a view<using-a-form-in-a-view>`). To help avoid
this, Django provides a collection of generic class-based views for form
processing.
Basic Forms
-----------
@ -28,7 +28,7 @@ Given a simple contact form::
# send email using the self.cleaned_data dictionary
pass
The view can be constructed using a FormView::
The view can be constructed using a ``FormView``::
# views.py
from myapp.forms import ContactForm
@ -50,42 +50,46 @@ Notes:
* FormView inherits
:class:`~django.views.generic.base.TemplateResponseMixin` so
:attr:`~django.views.generic.base.TemplateResponseMixin.template_name`
can be used here
can be used here.
* The default implementation for
:meth:`~django.views.generic.edit.FormView.form_valid` simply
redirects to the :attr:`success_url`
:meth:`~django.views.generic.edit.FormMixin.form_valid` simply
redirects to the :attr:`~django.views.generic.edit.FormMixin.success_url`.
Model Forms
-----------
Generic views really shine when working with models. These generic
views will automatically create a :class:`ModelForm`, so long as they
can work out which model class to use:
views will automatically create a :class:`~django.forms.ModelForm`, so long as
they can work out which model class to use:
* If the :attr:`model` attribute is given, that model class will be used
* If :meth:`get_object()` returns an object, the class of that object
will be used
* If a :attr:`queryset` is given, the model for that queryset will be used
* If the :attr:`~django.views.generic.edit.ModelFormMixin.model` attribute is
given, that model class will be used.
* If :meth:`~django.views.generic.detail.SingleObjectMixin.get_object()`
returns an object, the class of that object will be used.
* If a :attr:`~django.views.generic.detail.SingleObjectMixin.queryset` is
given, the model for that queryset will be used.
Model form views provide a :meth:`form_valid()` implementation that
saves the model automatically. You can override this if you have any
Model form views provide a
:meth:`~django.views.generic.edit.ModelFormMixin.form_valid()` implementation
that saves the model automatically. You can override this if you have any
special requirements; see below for examples.
You don't even need to provide a attr:`success_url` for
You don't even need to provide a ``success_url`` for
:class:`~django.views.generic.edit.CreateView` or
:class:`~django.views.generic.edit.UpdateView` - they will use
:meth:`get_absolute_url()` on the model object if available.
:meth:`~django.db.models.Model.get_absolute_url()` on the model object if available.
If you want to use a custom :class:`ModelForm` (for instance to add
extra validation) simply set
If you want to use a custom :class:`~django.forms.ModelForm` (for instance to
add extra validation) simply set
:attr:`~django.views.generic.edit.FormMixin.form_class` on your view.
.. note::
When specifying a custom form class, you must still specify the model,
even though the :attr:`form_class` may be a :class:`ModelForm`.
even though the :attr:`~django.views.generic.edit.FormMixin.form_class` may
be a :class:`~django.forms.ModelForm`.
First we need to add :meth:`get_absolute_url()` to our :class:`Author`
class:
First we need to add :meth:`~django.db.models.Model.get_absolute_url()` to our
``Author`` class:
.. code-block:: python
@ -137,8 +141,10 @@ Finally, we hook these new views into the URLconf::
.. note::
These views inherit :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`
which uses :attr:`~django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_prefix`
These views inherit
:class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`
which uses
:attr:`~django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_suffix`
to construct the
:attr:`~django.views.generic.base.TemplateResponseMixin.template_name`
based on the model.
@ -149,15 +155,17 @@ Finally, we hook these new views into the URLconf::
* :class:`DeleteView` uses ``myapp/author_confirm_delete.html``
If you wish to have separate templates for :class:`CreateView` and
:class:1UpdateView`, you can set either :attr:`template_name` or
:attr:`template_name_suffix` on your view class.
:class:`UpdateView`, you can set either
:attr:`~django.views.generic.base.TemplateResponseMixin.template_name` or
:attr:`~django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_suffix`
on your view class.
Models and request.user
-----------------------
To track the user that created an object using a :class:`CreateView`,
you can use a custom :class:`ModelForm` to do this. First, add the
foreign key relation to the model::
you can use a custom :class:`~django.forms.ModelForm` to do this. First, add
the foreign key relation to the model::
# models.py
from django.contrib.auth import User
@ -169,7 +177,7 @@ foreign key relation to the model::
# ...
Create a custom :class:`ModelForm` in order to exclude the
Create a custom :class:`~django.forms.ModelForm` in order to exclude the
``created_by`` field and prevent the user from editing it:
.. code-block:: python
@ -183,8 +191,10 @@ Create a custom :class:`ModelForm` in order to exclude the
model = Author
exclude = ('created_by',)
In the view, use the custom :attr:`form_class` and override
:meth:`form_valid()` to add the user::
In the view, use the custom
:attr:`~django.views.generic.edit.FormMixin.form_class` and override
:meth:`~django.views.generic.edit.ModelFormMixin.form_valid()` to add the
user::
# views.py
from django.views.generic.edit import CreateView
@ -202,7 +212,8 @@ In the view, use the custom :attr:`form_class` and override
Note that you'll need to :ref:`decorate this
view<decorating-class-based-views>` using
:func:`~django.contrib.auth.decorators.login_required`, or
alternatively handle unauthorised users in the :meth:`form_valid()`.
alternatively handle unauthorized users in the
:meth:`~django.views.generic.edit.ModelFormMixin.form_valid()`.
AJAX example
------------

View File

@ -32,13 +32,14 @@ Two central mixins are provided that help in providing a consistent
interface to working with templates in class-based views.
:class:`~django.views.generic.base.TemplateResponseMixin`
Every built in view which returns a
:class:`~django.template.response.TemplateResponse` will call the
:meth:`~django.views.generic.base.TemplateResponseMixin.render_to_response`
method that :class:`TemplateResponseMixin` provides. Most of the time this
method that ``TemplateResponseMixin`` provides. Most of the time this
will be called for you (for instance, it is called by the ``get()`` method
implemented by both :class:`~django.views.generic.base.TemplateView` and
:class:`~django.views.generic.base.DetailView`); similarly, it's unlikely
:class:`~django.views.generic.detail.DetailView`); similarly, it's unlikely
that you'll need to override it, although if you want your response to
return something not rendered via a Django template then you'll want to do
it. For an example of this, see the :ref:`JSONResponseMixin example
@ -59,10 +60,10 @@ interface to working with templates in class-based views.
:class:`~django.views.generic.base.ContextMixin`
Every built in view which needs context data, such as for rendering a
template (including :class:`TemplateResponseMixin` above), should call
template (including ``TemplateResponseMixin`` above), should call
:meth:`~django.views.generic.base.ContextMixin.get_context_data` passing
any data they want to ensure is in there as keyword arguments.
``get_context_data`` returns a dictionary; in :class:`ContextMixin` it
``get_context_data`` returns a dictionary; in ``ContextMixin`` it
simply returns its keyword arguments, but it is common to override this to
add more members to the dictionary.
@ -106,7 +107,7 @@ URLConf, and looks the object up either from the
:attr:`~django.views.generic.detail.SingleObjectMixin.model` attribute
on the view, or the
:attr:`~django.views.generic.detail.SingleObjectMixin.queryset`
attribute if that's provided). :class:`SingleObjectMixin` also overrides
attribute if that's provided). ``SingleObjectMixin`` also overrides
:meth:`~django.views.generic.base.ContextMixin.get_context_data`,
which is used across all Django's built in class-based views to supply
context data for template renders.
@ -115,10 +116,12 @@ To then make a :class:`~django.template.response.TemplateResponse`,
:class:`DetailView` uses
:class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`,
which extends :class:`~django.views.generic.base.TemplateResponseMixin`,
overriding :meth:`get_template_names()` as discussed above. It actually
provides a fairly sophisticated set of options, but the main one that most
people are going to use is ``<app_label>/<object_name>_detail.html``. The
``_detail`` part can be changed by setting
overriding
:meth:`~django.views.generic.base.TemplateResponseMixin.get_template_names()`
as discussed above. It actually provides a fairly sophisticated set of options,
but the main one that most people are going to use is
``<app_label>/<object_name>_detail.html``. The ``_detail`` part can be changed
by setting
:attr:`~django.views.generic.detail.SingleObjectTemplateResponseMixin.template_name_suffix`
on a subclass to something else. (For instance, the :doc:`generic edit
views<generic-editing>` use ``_form`` for create and update views, and
@ -128,9 +131,10 @@ ListView: working with many Django objects
------------------------------------------
Lists of objects follow roughly the same pattern: we need a (possibly
paginated) list of objects, typically a :class:`QuerySet`, and then we need
to make a :class:`TemplateResponse` with a suitable template using
that list of objects.
paginated) list of objects, typically a
:class:`~django.db.models.query.QuerySet`, and then we need to make a
:class:`~django.template.response.TemplateResponse` with a suitable template
using that list of objects.
To get the objects, :class:`~django.views.generic.list.ListView` uses
:class:`~django.views.generic.list.MultipleObjectMixin`, which
@ -138,9 +142,9 @@ provides both
:meth:`~django.views.generic.list.MultipleObjectMixin.get_queryset`
and
:meth:`~django.views.generic.list.MultipleObjectMixin.paginate_queryset`. Unlike
with :class:`SingleObjectMixin`, there's no need to key off parts of
the URL to figure out the queryset to work with, so the default just
uses the
with :class:`~django.views.generic.detail.SingleObjectMixin`, there's no need
to key off parts of the URL to figure out the queryset to work with, so the
default just uses the
:attr:`~django.views.generic.list.MultipleObjectMixin.queryset` or
:attr:`~django.views.generic.list.MultipleObjectMixin.model` attribute
on the view class. A common reason to override
@ -148,19 +152,19 @@ on the view class. A common reason to override
here would be to dynamically vary the objects, such as depending on
the current user or to exclude posts in the future for a blog.
:class:`MultipleObjectMixin` also overrides
:class:`~django.views.generic.list.MultipleObjectMixin` also overrides
:meth:`~django.views.generic.base.ContextMixin.get_context_data` to
include appropriate context variables for pagination (providing
dummies if pagination is disabled). It relies on ``object_list`` being
passed in as a keyword argument, which :class:`ListView` arranges for
it.
To make a :class:`TemplateResponse`, :class:`ListView` then uses
To make a :class:`~django.template.response.TemplateResponse`,
:class:`ListView` then uses
:class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`;
as with :class:`SingleObjectTemplateResponseMixin` above, this
overrides :meth:`get_template_names()` to provide :meth:`a range of
options
<~django.views.generic.list.MultipleObjectTempalteResponseMixin>`,
as with :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`
above, this overrides ``get_template_names()`` to provide :meth:`a range of
options <django.views.generic.list.MultipleObjectTemplateResponseMixin>`,
with the most commonly-used being
``<app_label>/<object_name>_list.html``, with the ``_list`` part again
being taken from the
@ -197,13 +201,13 @@ the box.
If in doubt, it's often better to back off and base your work on
:class:`View` or :class:`TemplateView`, perhaps with
:class:`SimpleObjectMixin` and
:class:`MultipleObjectMixin`. Although you will probably end up
writing more code, it is more likely to be clearly understandable
to someone else coming to it later, and with fewer interactions to
worry about you will save yourself some thinking. (Of course, you
can always dip into Django's implementation of the generic class
based views for inspiration on how to tackle problems.)
:class:`~django.views.generic.detail.SingleObjectMixin` and
:class:`~django.views.generic.list.MultipleObjectMixin`. Although you
will probably end up writing more code, it is more likely to be clearly
understandable to someone else coming to it later, and with fewer
interactions to worry about you will save yourself some thinking. (Of
course, you can always dip into Django's implementation of the generic
class based views for inspiration on how to tackle problems.)
.. _method resolution order: http://www.python.org/download/releases/2.3/mro/
@ -247,9 +251,9 @@ We'll demonstrate this with the publisher modelling we used in the
In practice you'd probably want to record the interest in a key-value
store rather than in a relational database, so we've left that bit
out. The only bit of the view that needs to worry about using
:class:`SingleObjectMixin` is where we want to look up the author
we're interested in, which it just does with a simple call to
``self.get_object()``. Everything else is taken care of for us by the
:class:`~django.views.generic.detail.SingleObjectMixin` is where we want to
look up the author we're interested in, which it just does with a simple call
to ``self.get_object()``. Everything else is taken care of for us by the
mixin.
We can hook this into our URLs easily enough::
@ -265,7 +269,8 @@ We can hook this into our URLs easily enough::
Note the ``pk`` named group, which
:meth:`~django.views.generic.detail.SingleObjectMixin.get_object` uses
to look up the ``Author`` instance. You could also use a slug, or
any of the other features of :class:`SingleObjectMixin`.
any of the other features of
:class:`~django.views.generic.detail.SingleObjectMixin`.
Using SingleObjectMixin with ListView
-------------------------------------
@ -277,23 +282,24 @@ example, you might want to paginate through all the books by a
particular publisher.
One way to do this is to combine :class:`ListView` with
:class:`SingleObjectMixin`, so that the queryset for the paginated
list of books can hang off the publisher found as the single
:class:`~django.views.generic.detail.SingleObjectMixin`, so that the queryset
for the paginated list of books can hang off the publisher found as the single
object. In order to do this, we need to have two different querysets:
**Publisher queryset for use in get_object**
We'll set that up directly when we call :meth:`get_object()`.
We'll set that up directly when we call ``get_object()``.
**Book queryset for use by ListView**
We'll figure that out ourselves in :meth:`get_queryset()` so we
can take into account the Publisher we're looking at.
We'll figure that out ourselves in ``get_queryset()`` so we
can take into account the ``Publisher`` we're looking at.
.. note::
We have to think carefully about :meth:`get_context_data()`.
Since both :class:`SingleObjectMixin` and :class:`ListView` will
We have to think carefully about ``get_context_data()``.
Since both :class:`~django.views.generic.detail.SingleObjectMixin` and
:class:`ListView` will
put things in the context data under the value of
:attr:`context_object_name` if it's set, we'll instead explictly
``context_object_name`` if it's set, we'll instead explictly
ensure the Publisher is in the context data. :class:`ListView`
will add in the suitable ``page_obj`` and ``paginator`` for us
providing we remember to call ``super()``.
@ -316,13 +322,14 @@ Now we can write a new ``PublisherDetail``::
self.object = self.get_object(Publisher.objects.all())
return self.object.book_set.all()
Notice how we set ``self.object`` within :meth:`get_queryset` so we
can use it again later in :meth:`get_context_data`. If you don't set
:attr:`template_name`, the template will default to the normal
Notice how we set ``self.object`` within ``get_queryset()`` so we
can use it again later in ``get_context_data()``. If you don't set
``template_name``, the template will default to the normal
:class:`ListView` choice, which in this case would be
``"books/book_list.html"`` because it's a list of books;
:class:`ListView` knows nothing about :class:`SingleObjectMixin`, so
it doesn't have any clue this view is anything to do with a Publisher.
:class:`ListView` knows nothing about
:class:`~django.views.generic.detail.SingleObjectMixin`, so it doesn't have
any clue this view is anything to do with a Publisher.
.. highlightlang:: html+django
@ -365,7 +372,7 @@ Generally you can use
:class:`~django.views.generic.base.TemplateResponseMixin` and
:class:`~django.views.generic.detail.SingleObjectMixin` when you need
their functionality. As shown above, with a bit of care you can even
combine :class:`SingleObjectMixin` with
combine ``SingleObjectMixin`` with
:class:`~django.views.generic.list.ListView`. However things get
increasingly complex as you try to do so, and a good rule of thumb is:
@ -376,48 +383,48 @@ increasingly complex as you try to do so, and a good rule of thumb is:
list<generic-display>`, :doc:`editing<generic-editing>` and
date. For example it's fine to combine
:class:`TemplateView` (built in view) with
:class:`MultipleObjectMixin` (generic list), but you're likely to
have problems combining :class:`SingleObjectMixin` (generic
detail) with :class:`MultipleObjectMixin` (generic list).
:class:`~django.views.generic.list.MultipleObjectMixin` (generic list), but
you're likely to have problems combining ``SingleObjectMixin`` (generic
detail) with ``MultipleObjectMixin`` (generic list).
To show what happens when you try to get more sophisticated, we show
an example that sacrifices readability and maintainability when there
is a simpler solution. First, let's look at a naive attempt to combine
:class:`~django.views.generic.detail.DetailView` with
:class:`~django.views.generic.edit.FormMixin` to enable use to
``POST`` a Django :class:`Form` to the same URL as we're displaying an
object using :class:`DetailView`.
``POST`` a Django :class:`~django.forms.Form` to the same URL as we're
displaying an object using :class:`DetailView`.
Using FormMixin with DetailView
-------------------------------
Think back to our earlier example of using :class:`View` and
:class:`SingleObjectMixin` together. We were recording a user's
interest in a particular author; say now that we want to let them
leave a message saying why they like them. Again, let's assume we're
:class:`~django.views.generic.detail.SingleObjectMixin` together. We were
recording a user's interest in a particular author; say now that we want to
let them leave a message saying why they like them. Again, let's assume we're
not going to store this in a relational database but instead in
something more esoteric that we won't worry about here.
At this point it's natural to reach for a :class:`Form` to encapsulate
the information sent from the user's browser to Django. Say also that
we're heavily invested in `REST`_, so we want to use the same URL for
At this point it's natural to reach for a :class:`~django.forms.Form` to
encapsulate the information sent from the user's browser to Django. Say also
that we're heavily invested in `REST`_, so we want to use the same URL for
displaying the author as for capturing the message from the
user. Let's rewrite our ``AuthorDetailView`` to do that.
.. _REST: http://en.wikipedia.org/wiki/Representational_state_transfer
We'll keep the ``GET`` handling from :class:`DetailView`, although
we'll have to add a :class:`Form` into the context data so we can
we'll have to add a :class:`~django.forms.Form` into the context data so we can
render it in the template. We'll also want to pull in form processing
from :class:`~django.views.generic.edit.FormMixin`, and write a bit of
code so that on ``POST`` the form gets called appropriately.
.. note::
We use :class:`FormMixin` and implement :meth:`post()` ourselves
rather than try to mix :class:`DetailView` with :class:`FormView`
(which provides a suitable :meth:`post()` already) because both of
the views implement :meth:`get()`, and things would get much more
We use :class:`~django.views.generic.edit.FormMixin` and implement
``post()`` ourselves rather than try to mix :class:`DetailView` with
:class:`FormView` (which provides a suitable ``post()`` already) because
both of the views implement ``get()``, and things would get much more
confusing.
.. highlightlang:: python
@ -472,24 +479,24 @@ Our new ``AuthorDetail`` looks like this::
# record the interest using the message in form.cleaned_data
return super(AuthorDetail, self).form_valid(form)
:meth:`get_success_url()` is just providing somewhere to redirect to,
``get_success_url()`` is just providing somewhere to redirect to,
which gets used in the default implementation of
:meth:`form_valid()`. We have to provide our own :meth:`post()` as
noted earlier, and override :meth:`get_context_data()` to make the
:class:`Form` available in the context data.
``form_valid()``. We have to provide our own ``post()`` as
noted earlier, and override ``get_context_data()`` to make the
:class:`~django.forms.Form` available in the context data.
A better solution
-----------------
It should be obvious that the number of subtle interactions between
:class:`FormMixin` and :class:`DetailView` is already testing our
ability to manage things. It's unlikely you'd want to write this kind
of class yourself.
:class:`~django.views.generic.edit.FormMixin` and :class:`DetailView` is
already testing our ability to manage things. It's unlikely you'd want to
write this kind of class yourself.
In this case, it would be fairly easy to just write the :meth:`post()`
In this case, it would be fairly easy to just write the ``post()``
method yourself, keeping :class:`DetailView` as the only generic
functionality, although writing :class:`Form` handling code involves a
lot of duplication.
functionality, although writing :class:`~django.forms.Form` handling code
involves a lot of duplication.
Alternatively, it would still be easier than the above approach to
have a separate view for processing the form, which could use
@ -502,15 +509,15 @@ An alternative better solution
What we're really trying to do here is to use two different class
based views from the same URL. So why not do just that? We have a very
clear division here: ``GET`` requests should get the
:class:`DetailView` (with the :class:`Form` added to the context
:class:`DetailView` (with the :class:`~django.forms.Form` added to the context
data), and ``POST`` requests should get the :class:`FormView`. Let's
set up those views first.
The ``AuthorDisplay`` view is almost the same as :ref:`when we
first introduced AuthorDetail<generic-views-extra-work>`; we have to
write our own :meth:`get_context_data()` to make the
write our own ``get_context_data()`` to make the
``AuthorInterestForm`` available to the template. We'll skip the
:meth:`get_object()` override from before for clarity.
``get_object()`` override from before for clarity.
.. code-block:: python
@ -533,9 +540,9 @@ write our own :meth:`get_context_data()` to make the
return super(AuthorDisplay, self).get_context_data(**context)
Then the ``AuthorInterest`` is a simple :class:`FormView`, but we
have to bring in :class:`SingleObjectMixin` so we can find the author
we're talking about, and we have to remember to set
:attr:`template_name` to ensure that form errors will render the same
have to bring in :class:`~django.views.generic.detail.SingleObjectMixin` so we
can find the author we're talking about, and we have to remember to set
``template_name`` to ensure that form errors will render the same
template as ``AuthorDisplay`` is using on ``GET``.
.. code-block:: python
@ -568,14 +575,14 @@ template as ``AuthorDisplay`` is using on ``GET``.
return super(AuthorInterest, self).form_valid(form)
Finally we bring this together in a new ``AuthorDetail`` view. We
already know that calling :meth:`as_view()` on a class-based view
gives us something that behaves exactly like a function based view, so
we can do that at the point we choose between the two subviews.
already know that calling :meth:`~django.views.generic.base.View.as_view()` on
a class-based view gives us something that behaves exactly like a function
based view, so we can do that at the point we choose between the two subviews.
You can of course pass through keyword arguments to :meth:`as_view()`
in the same way you would in your URLconf, such as if you wanted the
``AuthorInterest`` behaviour to also appear at another URL but
using a different template.
You can of course pass through keyword arguments to
:meth:`~django.views.generic.base.View.as_view()` in the same way you
would in your URLconf, such as if you wanted the ``AuthorInterest`` behavior
to also appear at another URL but using a different template.
.. code-block:: python
@ -646,8 +653,8 @@ Now we mix this into the base TemplateView::
Equally we could use our mixin with one of the generic views. We can make our
own version of :class:`~django.views.generic.detail.DetailView` by mixing
:class:`JSONResponseMixin` with the
:class:`~django.views.generic.detail.BaseDetailView` -- (the
``JSONResponseMixin`` with the
``django.views.generic.detail.BaseDetailView`` -- (the
:class:`~django.views.generic.detail.DetailView` before template
rendering behavior has been mixed in)::
@ -662,11 +669,12 @@ If you want to be really adventurous, you could even mix a
:class:`~django.views.generic.detail.DetailView` subclass that is able
to return *both* HTML and JSON content, depending on some property of
the HTTP request, such as a query argument or a HTTP header. Just mix
in both the :class:`JSONResponseMixin` and a
in both the ``JSONResponseMixin`` and a
:class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`,
and override the implementation of :func:`render_to_response()` to defer
to the appropriate subclass depending on the type of response that the user
requested::
and override the implementation of
:func:`~django.views.generic.base.TemplateResponseMixin.render_to_response()`
to defer to the appropriate subclass depending on the type of response that the
user requested::
class HybridDetailView(JSONResponseMixin, SingleObjectTemplateResponseMixin, BaseDetailView):
def render_to_response(self, context):
@ -678,5 +686,5 @@ requested::
Because of the way that Python resolves method overloading, the local
``render_to_response()`` implementation will override the versions provided by
:class:`JSONResponseMixin` and
``JSONResponseMixin`` and
:class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`.

View File

@ -24,9 +24,8 @@ return model instances:
.. method:: Manager.raw(raw_query, params=None, translations=None)
This method method takes a raw SQL query, executes it, and returns a
:class:`~django.db.models.query.RawQuerySet` instance. This
:class:`~django.db.models.query.RawQuerySet` instance can be iterated
over just like an normal QuerySet to provide object instances.
``django.db.models.query.RawQuerySet`` instance. This ``RawQuerySet`` instance
can be iterated over just like an normal QuerySet to provide object instances.
This is best illustrated with an example. Suppose you've got the following model::

View File

@ -48,10 +48,9 @@ you use the session middleware after the transaction middleware, session
creation will be part of the transaction.
The various cache middlewares are an exception:
:class:`~django.middleware.cache.CacheMiddleware`,
:class:`~django.middleware.cache.UpdateCacheMiddleware`, and
:class:`~django.middleware.cache.FetchFromCacheMiddleware` are never affected.
Even when using database caching, Django's cache backend uses its own
``CacheMiddleware``, :class:`~django.middleware.cache.UpdateCacheMiddleware`,
and :class:`~django.middleware.cache.FetchFromCacheMiddleware` are never
affected. Even when using database caching, Django's cache backend uses its own
database cursor (which is mapped to its own database connection internally).
.. note::

View File

@ -3,6 +3,8 @@
Formsets
========
.. class:: django.forms.formset.BaseFormSet
A formset is a layer of abstraction to working with multiple forms on the same
page. It can be best compared to a data grid. Let's say you have the following
form::

View File

@ -227,8 +227,8 @@ field in the model::
``UploadedFile`` objects
========================
In addition to those inherited from :class:`File`, all ``UploadedFile`` objects
define the following methods/attributes:
In addition to those inherited from :class:`~django.core.files.File`, all
``UploadedFile`` objects define the following methods/attributes:
.. attribute:: UploadedFile.content_type

View File

@ -132,6 +132,8 @@ Customizing error views
The 404 (page not found) view
-----------------------------
.. function:: django.views.defaults.page_not_found(request, template_name='404.html')
When you raise an ``Http404`` exception, Django loads a special view devoted
to handling 404 errors. By default, it's the view
``django.views.defaults.page_not_found``, which either produces a very simple

View File

@ -312,7 +312,7 @@ time zone is unset, the default time zone applies.
get_current_timezone
~~~~~~~~~~~~~~~~~~~~
When the :func:`django.core.context_processors.tz` context processor is
When the ``django.core.context_processors.tz`` context processor is
enabled -- by default, it is -- each :class:`~django.template.RequestContext`
contains a ``TIME_ZONE`` variable that provides the name of the current time
zone.
@ -661,7 +661,7 @@ Usage
datetime.datetime(2012, 2, 21, 10, 28, 45, tzinfo=<DstTzInfo 'Europe/Helsinki' EET+2:00:00 STD>)
Note that ``localize`` is a pytz extension to the :class:`~datetime.tzinfo`
API. Also, you may want to catch :exc:`~pytz.InvalidTimeError`. The
API. Also, you may want to catch ``pytz.InvalidTimeError``. The
documentation of pytz contains `more examples`_. You should review it
before attempting to manipulate aware datetimes.

View File

@ -141,7 +141,7 @@ error log record will be written.
Naming loggers
--------------
The call to :meth:`logging.getLogger()` obtains (creating, if
The call to :func:`logging.getLogger()` obtains (creating, if
necessary) an instance of a logger. The logger instance is identified
by a name. This name is used to identify the logger for configuration
purposes.
@ -242,7 +242,7 @@ An example
The full documentation for `dictConfig format`_ is the best source of
information about logging configuration dictionaries. However, to give
you a taste of what is possible, here is an example of a fairly
complex logging setup, configured using :meth:`logging.dictConfig`::
complex logging setup, configured using :func:`logging.config.dictConfig`::
LOGGING = {
'version': 1,
@ -317,12 +317,12 @@ This logging configuration does the following things:
message, plus the time, process, thread and module that
generate the log message.
* Defines one filter -- :class:`project.logging.SpecialFilter`,
* Defines one filter -- ``project.logging.SpecialFilter``,
using the alias ``special``. If this filter required additional
arguments at time of construction, they can be provided as
additional keys in the filter configuration dictionary. In this
case, the argument ``foo`` will be given a value of ``bar`` when
instantiating the :class:`SpecialFilter`.
instantiating the ``SpecialFilter``.
* Defines three handlers:
@ -365,7 +365,7 @@ logger, you can specify your own configuration scheme.
The :setting:`LOGGING_CONFIG` setting defines the callable that will
be used to configure Django's loggers. By default, it points at
Python's :meth:`logging.dictConfig()` method. However, if you want to
Python's :func:`logging.config.dictConfig()` function. However, if you want to
use a different configuration process, you can use any other callable
that takes a single argument. The contents of :setting:`LOGGING` will
be provided as the value of that argument when logging is configured.
@ -494,7 +494,7 @@ logging module.
through the filter. Handling of that record will not proceed if the callback
returns False.
For instance, to filter out :class:`~django.http.UnreadablePostError`
For instance, to filter out :exc:`~django.http.UnreadablePostError`
(raised when a user cancels an upload) from the admin emails, you would
create a filter function::

View File

@ -78,8 +78,8 @@ wherever possible and avoid the ``b`` prefixes.
String handling
---------------
Python 2's :class:`unicode` type was renamed :class:`str` in Python 3,
:class:`str` was renamed :class:`bytes`, and :class:`basestring` disappeared.
Python 2's :func:`unicode` type was renamed :func:`str` in Python 3,
:func:`str` was renamed ``bytes()``, and :func:`basestring` disappeared.
six_ provides :ref:`tools <string-handling-with-six>` to deal with these
changes.
@ -131,35 +131,36 @@ and ``SafeText`` respectively.
For forwards compatibility, the new names work as of Django 1.4.2.
:meth:`__str__` and :meth:`__unicode__` methods
-----------------------------------------------
:meth:`~object.__str__` and :meth:`~object.__unicode__` methods
---------------------------------------------------------------
In Python 2, the object model specifies :meth:`__str__` and
:meth:`__unicode__` methods. If these methods exist, they must return
:class:`str` (bytes) and :class:`unicode` (text) respectively.
In Python 2, the object model specifies :meth:`~object.__str__` and
:meth:`~object.__unicode__` methods. If these methods exist, they must return
``str`` (bytes) and ``unicode`` (text) respectively.
The ``print`` statement and the :func:`str` built-in call :meth:`__str__` to
determine the human-readable representation of an object. The :func:`unicode`
built-in calls :meth:`__unicode__` if it exists, and otherwise falls back to
:meth:`__str__` and decodes the result with the system encoding. Conversely,
the :class:`~django.db.models.Model` base class automatically derives
:meth:`__str__` from :meth:`__unicode__` by encoding to UTF-8.
The ``print`` statement and the :func:`str` built-in call
:meth:`~object.__str__` to determine the human-readable representation of an
object. The :func:`unicode` built-in calls :meth:`~object.__unicode__` if it
exists, and otherwise falls back to :meth:`~object.__str__` and decodes the
result with the system encoding. Conversely, the
:class:`~django.db.models.Model` base class automatically derives
:meth:`~object.__str__` from :meth:`~object.__unicode__` by encoding to UTF-8.
In Python 3, there's simply :meth:`__str__`, which must return :class:`str`
In Python 3, there's simply :meth:`~object.__str__`, which must return ``str``
(text).
(It is also possible to define :meth:`__bytes__`, but Django application have
(It is also possible to define ``__bytes__()``, but Django application have
little use for that method, because they hardly ever deal with
:class:`bytes`.)
``bytes``.)
Django provides a simple way to define :meth:`__str__` and :meth:`__unicode__`
methods that work on Python 2 and 3: you must define a :meth:`__str__` method
returning text and to apply the
Django provides a simple way to define :meth:`~object.__str__` and
:meth:`~object.__unicode__` methods that work on Python 2 and 3: you must
define a :meth:`~object.__str__` method returning text and to apply the
:func:`~django.utils.encoding.python_2_unicode_compatible` decorator.
On Python 3, the decorator is a no-op. On Python 2, it defines appropriate
:meth:`__unicode__` and :meth:`__str__` methods (replacing the original
:meth:`__str__` method in the process). Here's an example::
:meth:`~object.__unicode__` and :meth:`~object.__str__` methods (replacing the
original :meth:`~object.__str__` method in the process). Here's an example::
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
@ -173,8 +174,8 @@ This technique is the best match for Django's porting philosophy.
For forwards compatibility, this decorator is available as of Django 1.4.2.
Finally, note that :meth:`__repr__` must return a :class:`str` on all versions
of Python.
Finally, note that :meth:`~object.__repr__` must return a ``str`` on all
versions of Python.
:class:`dict` and :class:`dict`-like classes
--------------------------------------------
@ -187,19 +188,19 @@ behave likewise in Python 3.
six_ provides compatibility functions to work around this change:
:func:`~six.iterkeys`, :func:`~six.iteritems`, and :func:`~six.itervalues`.
Django's bundled version adds :func:`~django.utils.six.iterlists` for
:class:`~django.utils.datastructures.MultiValueDict` and its subclasses.
``django.utils.datastructures.MultiValueDict`` and its subclasses.
:class:`~django.http.HttpRequest` and :class:`~django.http.HttpResponse` objects
--------------------------------------------------------------------------------
According to :pep:`3333`:
- headers are always :class:`str` objects,
- input and output streams are always :class:`bytes` objects.
- headers are always ``str`` objects,
- input and output streams are always ``bytes`` objects.
Specifically, :attr:`HttpResponse.content <django.http.HttpResponse.content>`
contains :class:`bytes`, which may become an issue if you compare it with a
:class:`str` in your tests. The preferred solution is to rely on
contains ``bytes``, which may become an issue if you compare it with a
``str`` in your tests. The preferred solution is to rely on
:meth:`~django.test.TestCase.assertContains` and
:meth:`~django.test.TestCase.assertNotContains`. These methods accept a
response and a unicode string as arguments.
@ -236,11 +237,10 @@ under Python 3, use the :func:`str` builtin::
str('my string')
In Python 3, there aren't any automatic conversions between :class:`str` and
:class:`bytes`, and the :mod:`codecs` module became more strict.
:meth:`str.decode` always returns :class:`bytes`, and :meth:`bytes.decode`
always returns :class:`str`. As a consequence, the following pattern is
sometimes necessary::
In Python 3, there aren't any automatic conversions between ``str`` and
``bytes``, and the :mod:`codecs` module became more strict. :meth:`str.decode`
always returns ``bytes``, and ``bytes.decode`` always returns ``str``. As a
consequence, the following pattern is sometimes necessary::
value = value.encode('ascii', 'ignore').decode('ascii')
@ -395,11 +395,8 @@ The version of six bundled with Django includes one extra function:
.. function:: iterlists(MultiValueDict)
Returns an iterator over the lists of values of a
:class:`~django.utils.datastructures.MultiValueDict`. This replaces
:meth:`~django.utils.datastructures.MultiValueDict.iterlists()` on Python
2 and :meth:`~django.utils.datastructures.MultiValueDict.lists()` on
Python 3.
Returns an iterator over the lists of values of a ``MultiValueDict``. This
replaces ``iterlists()`` on Python 2 and ``lists()`` on Python 3.
.. function:: assertRaisesRegex(testcase, *args, **kwargs)

View File

@ -26,6 +26,8 @@ to (see `Serialization formats`_) and a
argument can be any iterator that yields Django model instances, but it'll
almost always be a QuerySet).
.. function:: django.core.serializers.get_serializer(format)
You can also use a serializer object directly::
XMLSerializer = serializers.get_serializer("xml")
@ -43,7 +45,7 @@ This is useful if you want to serialize data directly to a file-like object
Calling :func:`~django.core.serializers.get_serializer` with an unknown
:ref:`format <serialization-formats>` will raise a
:class:`~django.core.serializers.SerializerDoesNotExist` exception.
``django.core.serializers.SerializerDoesNotExist`` exception.
Subset of fields
~~~~~~~~~~~~~~~~

View File

@ -32,6 +32,8 @@ Because a settings file is a Python module, the following apply:
Designating the settings
========================
.. envvar:: DJANGO_SETTINGS_MODULE
When you use Django, you have to tell it which settings you're using. Do this
by using an environment variable, ``DJANGO_SETTINGS_MODULE``.
@ -260,4 +262,3 @@ It boils down to this: Use exactly one of either ``configure()`` or
``DJANGO_SETTINGS_MODULE``. Not both, and not neither.
.. _@login_required: ../authentication/#the-login-required-decorator

View File

@ -28,7 +28,7 @@ module defines tests in class-based approach.
backported for Python 2.5 compatibility.
To access this library, Django provides the
:mod:`django.utils.unittest` module alias. If you are using Python
``django.utils.unittest`` module alias. If you are using Python
2.7, or you have installed unittest2 locally, Django will map the
alias to the installed version of the unittest library. Otherwise,
Django will use its own bundled version of unittest2.
@ -851,7 +851,7 @@ Normal Python unit test classes extend a base class of
Hierarchy of Django unit testing classes
Regardless of the version of Python you're using, if you've installed
``unittest2``, :mod:`django.utils.unittest` will point to that library.
``unittest2``, ``django.utils.unittest`` will point to that library.
SimpleTestCase
~~~~~~~~~~~~~~
@ -882,7 +882,7 @@ features like:
then you should use :class:`~django.test.TransactionTestCase` or
:class:`~django.test.TestCase` instead.
``SimpleTestCase`` inherits from :class:`django.utils.unittest.TestCase`.
``SimpleTestCase`` inherits from ``django.utils.unittest.TestCase``.
TransactionTestCase
~~~~~~~~~~~~~~~~~~~
@ -1745,7 +1745,7 @@ test if the database doesn't support a specific named feature.
The decorators use a string identifier to describe database features.
This string corresponds to attributes of the database connection
features class. See :class:`~django.db.backends.BaseDatabaseFeatures`
features class. See ``django.db.backends.BaseDatabaseFeatures``
class for a full list of database features that can be used as a basis
for skipping tests.