summaryrefslogtreecommitdiff
path: root/docs/topics
diff options
context:
space:
mode:
Diffstat (limited to 'docs/topics')
-rw-r--r--docs/topics/auth.txt76
-rw-r--r--docs/topics/cache.txt88
-rw-r--r--docs/topics/conditional-view-processing.txt2
-rw-r--r--docs/topics/db/aggregation.txt8
-rw-r--r--docs/topics/db/index.txt2
-rw-r--r--docs/topics/db/managers.txt9
-rw-r--r--docs/topics/db/models.txt20
-rw-r--r--docs/topics/db/multi-db.txt4
-rw-r--r--docs/topics/db/optimization.txt41
-rw-r--r--docs/topics/db/queries.txt12
-rw-r--r--docs/topics/db/sql.txt12
-rw-r--r--docs/topics/db/transactions.txt4
-rw-r--r--docs/topics/email.txt4
-rw-r--r--docs/topics/files.txt10
-rw-r--r--docs/topics/forms/formsets.txt1
-rw-r--r--docs/topics/forms/index.txt14
-rw-r--r--docs/topics/forms/media.txt2
-rw-r--r--docs/topics/forms/modelforms.txt10
-rw-r--r--docs/topics/generic-views.txt10
-rw-r--r--docs/topics/http/file-uploads.txt6
-rw-r--r--docs/topics/http/generic-views.txt4
-rw-r--r--docs/topics/http/index.txt2
-rw-r--r--docs/topics/http/middleware.txt14
-rw-r--r--docs/topics/http/sessions.txt10
-rw-r--r--docs/topics/http/shortcuts.txt2
-rw-r--r--docs/topics/http/urls.txt105
-rw-r--r--docs/topics/http/views.txt4
-rw-r--r--docs/topics/i18n/deployment.txt6
-rw-r--r--docs/topics/i18n/index.txt8
-rw-r--r--docs/topics/i18n/internationalization.txt8
-rw-r--r--docs/topics/i18n/localization.txt4
-rw-r--r--docs/topics/index.txt2
-rw-r--r--docs/topics/install.txt81
-rw-r--r--docs/topics/pagination.txt2
-rw-r--r--docs/topics/serialization.txt10
-rw-r--r--docs/topics/settings.txt25
-rw-r--r--docs/topics/signals.txt26
-rw-r--r--docs/topics/templates.txt59
-rw-r--r--docs/topics/testing.txt95
39 files changed, 510 insertions, 292 deletions
diff --git a/docs/topics/auth.txt b/docs/topics/auth.txt
index 4e07f73190..8c9b0f1cff 100644
--- a/docs/topics/auth.txt
+++ b/docs/topics/auth.txt
@@ -1,5 +1,3 @@
-.. _topics-auth:
-
=============================
User authentication in Django
=============================
@@ -138,8 +136,8 @@ Methods
:class:`~django.contrib.auth.models.User` objects have two many-to-many
fields: models.User. ``groups`` and ``user_permissions``.
:class:`~django.contrib.auth.models.User` objects can access their related
- objects in the same way as any other :ref:`Django model
- <topics-db-models>`:
+ objects in the same way as any other :doc:`Django model
+ </topics/db/models>`:
.. code-block:: python
@@ -435,8 +433,6 @@ Anonymous users
instead of ``False``.
* :meth:`~django.contrib.auth.models.User.is_authenticated()` returns
``False`` instead of ``True``.
- * :meth:`~django.contrib.auth.models.User.has_perm()` always returns
- ``False``.
* :meth:`~django.contrib.auth.models.User.set_password()`,
:meth:`~django.contrib.auth.models.User.check_password()`,
:meth:`~django.contrib.auth.models.User.save()`,
@@ -539,7 +535,7 @@ First, install the
:class:`~django.contrib.sessions.middleware.SessionMiddleware` and
:class:`~django.contrib.auth.middleware.AuthenticationMiddleware`
middlewares by adding them to your :setting:`MIDDLEWARE_CLASSES` setting. See
-the :ref:`session documentation <topics-http-sessions>` for more information.
+the :doc:`session documentation </topics/http/sessions>` for more information.
Once you have those middlewares installed, you'll be able to access
:attr:`request.user <django.http.HttpRequest.user>` in views.
@@ -556,7 +552,7 @@ section). You can tell them apart with
else:
# Do something for anonymous users.
-.. _howtologauserin:
+.. _how-to-log-a-user-in:
How to log a user in
--------------------
@@ -717,6 +713,17 @@ The login_required decorator
def my_view(request):
...
+ .. versionadded:: 1.3
+
+ :func:`~django.contrib.auth.decorators.login_required` also takes an
+ optional ``login_url`` parameter. Example::
+
+ from django.contrib.auth.decorators import login_required
+
+ @login_required(login_url='/accounts/login/')
+ def my_view(request):
+ ...
+
:func:`~django.contrib.auth.decorators.login_required` does the following:
* If the user isn't logged in, redirect to
@@ -730,9 +737,9 @@ The login_required decorator
* If the user is logged in, execute the view normally. The view code is
free to assume the user is logged in.
-Note that you'll need to map the appropriate Django view to
-:setting:`settings.LOGIN_URL <LOGIN_URL>`. For example, using the defaults, add
-the following line to your URLconf::
+Note that if you don't specify the ``login_url`` parameter, you'll need to map
+the appropriate Django view to :setting:`settings.LOGIN_URL <LOGIN_URL>`. For
+example, using the defaults, add the following line to your URLconf::
(r'^accounts/login/$', 'django.contrib.auth.views.login'),
@@ -755,7 +762,7 @@ the following line to your URLconf::
template context variables:
* ``form``: A :class:`~django.forms.Form` object representing the login
- form. See the :ref:`forms documentation <topics-forms-index>` for
+ form. See the :doc:`forms documentation </topics/forms/index>` for
more on ``Form`` objects.
* ``next``: The URL to redirect to after successful login. This may
@@ -771,7 +778,7 @@ the following line to your URLconf::
* ``site_name``: An alias for ``site.name``. If you don't have the site
framework installed, this will be set to the value of
:attr:`request.META['SERVER_NAME'] <django.http.HttpRequest.META>`.
- For more on sites, see :ref:`ref-contrib-sites`.
+ For more on sites, see :doc:`/ref/contrib/sites`.
If you'd prefer not to call the template :file:`registration/login.html`,
you can pass the ``template_name`` parameter via the extra arguments to
@@ -798,7 +805,8 @@ the following line to your URLconf::
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
- <form method="post" action="{% url django.contrib.auth.views.login %}">{% csrf_token %}
+ <form method="post" action="{% url django.contrib.auth.views.login %}">
+ {% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
@@ -898,10 +906,11 @@ includes a few other useful built-in views located in
default to :file:`registration/password_change_done.html` if not
supplied.
-.. function:: views.password_reset(request[, is_admin_site, template_name, email_template_name, password_reset_form, token_generator, post_reset_redirect])
+.. function:: views.password_reset(request[, is_admin_site, template_name, email_template_name, password_reset_form, token_generator, post_reset_redirect, from_email])
- Allows a user to reset their password, and sends them the new password
- in an e-mail.
+ Allows a user to reset their password by generating a one-time use link
+ that can be used to reset the password, and sending that link to the
+ user's registered e-mail address.
**Optional arguments:**
@@ -923,6 +932,11 @@ includes a few other useful built-in views located in
* ``post_reset_redirect``: The URL to redirect to after a successful
password change.
+ .. versionchanged:: 1.3
+
+ * ``from_email``: A valid e-mail address. By default Django uses
+ the :setting:`DEFAULT_FROM_EMAIL`.
+
**Template context:**
* ``form``: The form for resetting the user's password.
@@ -1007,8 +1021,8 @@ provides several built-in forms located in :mod:`django.contrib.auth.forms`:
.. class:: PasswordResetForm
- A form for resetting a user's password and e-mailing the new password to
- them.
+ A form for generating and e-mailing a one-time use link to reset a
+ user's password.
.. class:: SetPasswordForm
@@ -1112,7 +1126,7 @@ The permission_required decorator
Limiting access to generic views
--------------------------------
-To limit access to a :ref:`generic view <ref-generic-views>`, write a thin
+To limit access to a :doc:`generic view </ref/generic-views>`, write a thin
wrapper around the view, and point your URLconf to your wrapper instead of the
generic view itself. For example::
@@ -1229,13 +1243,13 @@ Methods
~~~~~~~
:class:`~django.contrib.auth.models.Permission` objects have the standard
-data-access methods like any other :ref:`Django model <ref-models-instances>`.
+data-access methods like any other :doc:`Django model </ref/models/instances>`.
Authentication data in templates
================================
The currently logged-in user and his/her permissions are made available in the
-:ref:`template context <ref-templates-api>` when you use
+:doc:`template context </ref/templates/api>` when you use
:class:`~django.template.context.RequestContext`.
.. admonition:: Technicality
@@ -1324,7 +1338,7 @@ Messages
.. deprecated:: 1.2
This functionality will be removed in Django 1.4. You should use the
- :ref:`messages framework <ref-contrib-messages>` for all new projects and
+ :doc:`messages framework </ref/contrib/messages>` for all new projects and
begin to update your existing code immediately.
The message system is a lightweight way to queue messages for given users.
@@ -1359,7 +1373,7 @@ a playlist::
When you use :class:`~django.template.context.RequestContext`, the currently
logged-in user and his/her messages are made available in the
-:ref:`template context <ref-templates-api>` as the template variable
+:doc:`template context </ref/templates/api>` as the template variable
``{{ messages }}``. Here's an example of template code that displays messages:
.. code-block:: html+django
@@ -1374,14 +1388,14 @@ logged-in user and his/her messages are made available in the
.. versionchanged:: 1.2
The ``messages`` template variable uses a backwards compatible method in the
- :ref:`messages framework <ref-contrib-messages>` to retrieve messages from
+ :doc:`messages framework </ref/contrib/messages>` to retrieve messages from
both the user ``Message`` model and from the new framework. Unlike in
previous revisions, the messages will not be erased unless they are actually
displayed.
Finally, note that this messages framework only works with users in the user
database. To send messages to anonymous users, use the
-:ref:`messages framework <ref-contrib-messages>`.
+:doc:`messages framework </ref/contrib/messages>`.
.. _authentication-backends:
@@ -1402,7 +1416,7 @@ plug in other authentication sources. You can override Django's default
database-based scheme, or you can use the default system in tandem with other
systems.
-See the :ref:`authentication backend reference <ref-authentication-backends>`
+See the :doc:`authentication backend reference </ref/authbackends>`
for information on the authentication backends included with Django.
Specifying authentication backends
@@ -1411,9 +1425,9 @@ Specifying authentication backends
Behind the scenes, Django maintains a list of "authentication backends" that it
checks for authentication. When somebody calls
:func:`django.contrib.auth.authenticate()` -- as described in :ref:`How to log
-a user in` above -- Django tries authenticating across all of its
-authentication backends. If the first authentication method fails, Django tries
-the second one, and so on, until all backends have been attempted.
+a user in <how-to-log-a-user-in>` above -- Django tries authenticating across
+all of its authentication backends. If the first authentication method fails,
+Django tries the second one, and so on, until all backends have been attempted.
The list of authentication backends to use is specified in the
:setting:`AUTHENTICATION_BACKENDS` setting. This should be a tuple of Python
@@ -1593,7 +1607,7 @@ object permissions will always return ``False`` or an empty list (depending on
the check performed).
To enable object permissions in your own
-:ref:`authentication backend <ref-authentication-backends>` you'll just have
+:doc:`authentication backend </ref/authbackends>` you'll just have
to allow passing an ``obj`` parameter to the permission methods and set the
``supports_object_permissions`` class attribute to ``True``.
diff --git a/docs/topics/cache.txt b/docs/topics/cache.txt
index 9dedbcf3b9..5797199411 100644
--- a/docs/topics/cache.txt
+++ b/docs/topics/cache.txt
@@ -1,5 +1,3 @@
-.. _topics-cache:
-
========================
Django's cache framework
========================
@@ -136,6 +134,49 @@ settings file. You can't use a different database backend for your cache table.
Database caching works best if you've got a fast, well-indexed database server.
+Database caching and multiple databases
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+If you use database caching with multiple databases, you'll also need
+to set up routing instructions for your database cache table. For the
+purposes of routing, the database cache table appears as a model named
+``CacheEntry``, in an application named ``django_cache``. This model
+won't appear in the models cache, but the model details can be used
+for routing purposes.
+
+For example, the following router would direct all cache read
+operations to ``cache_slave``, and all write operations to
+``cache_master``. The cache table will only be synchronized onto
+``cache_master``::
+
+ class CacheRouter(object):
+ """A router to control all database cache operations"""
+
+ def db_for_read(self, model, **hints):
+ "All cache read operations go to the slave"
+ if model._meta.app_label in ('django_cache',):
+ return 'cache_slave'
+ return None
+
+ def db_for_write(self, model, **hints):
+ "All cache write operations go to master"
+ if model._meta.app_label in ('django_cache',):
+ return 'cache_master'
+ return None
+
+ def allow_syncdb(self, db, model):
+ "Only synchronize the cache model on master"
+ if model._meta.app_label in ('django_cache',):
+ return db == 'cache_master'
+ return None
+
+If you don't specify routing directions for the database cache model,
+the cache backend will use the ``default`` database.
+
+Of course, if you don't use the database cache backend, you don't need
+to worry about providing routing instructions for the database cache
+model.
+
Filesystem caching
------------------
@@ -301,7 +342,7 @@ Additionally, the cache middleware automatically sets a few headers in each
* Sets the ``Cache-Control`` header to give a max age for the page --
again, from the ``CACHE_MIDDLEWARE_SECONDS`` setting.
-See :ref:`topics-http-middleware` for more on middleware.
+See :doc:`/topics/http/middleware` for more on middleware.
.. versionadded:: 1.0
@@ -322,7 +363,7 @@ include the name of the active :term:`language<language code>`.
This allows you to easily cache multilingual sites without having to create
the cache key yourself.
-See :ref:`topics-i18n-deployment` for more on how Django discovers the active
+See :doc:`/topics/i18n/deployment` for more on how Django discovers the active
language.
__ `Controlling cache: Using other headers`_
@@ -600,6 +641,45 @@ nonexistent cache key.::
However, if the backend doesn't natively provide an increment/decrement
operation, it will be implemented using a two-step retrieve/update.
+Cache key warnings
+------------------
+
+.. versionadded:: 1.3
+
+Memcached, the most commonly-used production cache backend, does not allow
+cache keys longer than 250 characters or containing whitespace or control
+characters, and using such keys will cause an exception. To encourage
+cache-portable code and minimize unpleasant surprises, the other built-in cache
+backends issue a warning (``django.core.cache.backends.base.CacheKeyWarning``)
+if a key is used that would cause an error on memcached.
+
+If you are using a production backend that can accept a wider range of keys (a
+custom backend, or one of the non-memcached built-in backends), and want to use
+this wider range without warnings, you can silence ``CacheKeyWarning`` with
+this code in the ``management`` module of one of your
+:setting:`INSTALLED_APPS`::
+
+ import warnings
+
+ from django.core.cache import CacheKeyWarning
+
+ warnings.simplefilter("ignore", CacheKeyWarning)
+
+If you want to instead provide custom key validation logic for one of the
+built-in backends, you can subclass it, override just the ``validate_key``
+method, and follow the instructions for `using a custom cache backend`_. For
+instance, to do this for the ``locmem`` backend, put this code in a module::
+
+ from django.core.cache.backends.locmem import CacheClass as LocMemCacheClass
+
+ class CacheClass(LocMemCacheClass):
+ def validate_key(self, key):
+ """Custom validation, raising exceptions or warnings as needed."""
+ # ...
+
+...and use the dotted Python path to this module as the scheme portion of your
+:setting:`CACHE_BACKEND`.
+
Upstream caches
===============
diff --git a/docs/topics/conditional-view-processing.txt b/docs/topics/conditional-view-processing.txt
index 1ce3c3bb92..b5da140827 100644
--- a/docs/topics/conditional-view-processing.txt
+++ b/docs/topics/conditional-view-processing.txt
@@ -1,5 +1,3 @@
-.. _topics-conditional-processing:
-
===========================
Conditional View Processing
===========================
diff --git a/docs/topics/db/aggregation.txt b/docs/topics/db/aggregation.txt
index 087c1bf239..eb21021038 100644
--- a/docs/topics/db/aggregation.txt
+++ b/docs/topics/db/aggregation.txt
@@ -1,5 +1,3 @@
-.. _topics-db-aggregation:
-
===========
Aggregation
===========
@@ -8,7 +6,7 @@ Aggregation
.. currentmodule:: django.db.models
-The topic guide on :ref:`Django's database-abstraction API <topics-db-queries>`
+The topic guide on :doc:`Django's database-abstraction API </topics/db/queries>`
described the way that you can use Django queries that create,
retrieve, update and delete individual objects. However, sometimes you will
need to retrieve values that are derived by summarizing or *aggregating* a
@@ -353,7 +351,7 @@ without any harmful effects, since that is already playing a role in the
query.
This behavior is the same as that noted in the queryset documentation for
-:ref:`distinct() <queryset-distinct>` and the general rule is the same:
+:meth:`~django.db.models.QuerySet.distinct` and the general rule is the same:
normally you won't want extra columns playing a part in the result, so clear
out the ordering, or at least make sure it's restricted only to those fields
you also select in a ``values()`` call.
@@ -363,7 +361,7 @@ you also select in a ``values()`` call.
for you. The main reason is consistency with ``distinct()`` and other
places: Django **never** removes ordering constraints that you have
specified (and we can't change those other methods' behavior, as that
- would violate our :ref:`misc-api-stability` policy).
+ would violate our :doc:`/misc/api-stability` policy).
Aggregating annotations
-----------------------
diff --git a/docs/topics/db/index.txt b/docs/topics/db/index.txt
index 3eb62b70ca..c49f158e64 100644
--- a/docs/topics/db/index.txt
+++ b/docs/topics/db/index.txt
@@ -1,5 +1,3 @@
-.. _topics-db-index:
-
Models and databases
====================
diff --git a/docs/topics/db/managers.txt b/docs/topics/db/managers.txt
index 123408b2bb..5ebe0b1b94 100644
--- a/docs/topics/db/managers.txt
+++ b/docs/topics/db/managers.txt
@@ -1,5 +1,3 @@
-.. _topics-db-managers:
-
========
Managers
========
@@ -12,7 +10,7 @@ A ``Manager`` is the interface through which database query operations are
provided to Django models. At least one ``Manager`` exists for every model in
a Django application.
-The way ``Manager`` classes work is documented in :ref:`topics-db-queries`;
+The way ``Manager`` classes work is documented in :doc:`/topics/db/queries`;
this document specifically touches on model options that customize ``Manager``
behavior.
@@ -170,7 +168,8 @@ and ``Person.people.all()``, yielding predictable results.
If you use custom ``Manager`` objects, take note that the first ``Manager``
Django encounters (in the order in which they're defined in the model) has a
special status. Django interprets the first ``Manager`` defined in a class as
-the "default" ``Manager``, and several parts of Django will use that ``Manager``
+the "default" ``Manager``, and several parts of Django
+(including :djadmin:`dumpdata`) will use that ``Manager``
exclusively for that model. As a result, it's a good idea to be careful in
your choice of default manager in order to avoid a situation where overriding
``get_query_set()`` results in an inability to retrieve objects you'd like to
@@ -324,7 +323,7 @@ it will use :class:`django.db.models.Manager`.
attribute only controlled the type of manager used for related field
access, which is where the name came from. As it became clear the concept
was more broadly useful, the name hasn't been changed. This is primarily
- so that existing code will :ref:`continue to work <misc-api-stability>` in
+ so that existing code will :doc:`continue to work </misc/api-stability>` in
future Django versions.
Writing Correct Managers For Use In Automatic Manager Instances
diff --git a/docs/topics/db/models.txt b/docs/topics/db/models.txt
index 6d7a7a4374..0ff34ea0e1 100644
--- a/docs/topics/db/models.txt
+++ b/docs/topics/db/models.txt
@@ -1,5 +1,3 @@
-.. _topics-db-models:
-
======
Models
======
@@ -18,7 +16,7 @@ The basics:
* Each attribute of the model represents a database field.
* With all of this, Django gives you an automatically-generated
- database-access API; see :ref:`topics-db-queries`.
+ database-access API; see :doc:`/topics/db/queries`.
.. seealso::
@@ -64,7 +62,7 @@ Some technical notes:
* The ``CREATE TABLE`` SQL in this example is formatted using PostgreSQL
syntax, but it's worth noting Django uses SQL tailored to the database
- backend specified in your :ref:`settings file <topics-settings>`.
+ backend specified in your :doc:`settings file </topics/settings>`.
Using models
============
@@ -126,7 +124,7 @@ determine a few things:
Django ships with dozens of built-in field types; you can find the complete list
in the :ref:`model field reference <model-field-types>`. You can easily write
your own fields if Django's built-in ones don't do the trick; see
-:ref:`howto-custom-model-fields`.
+:doc:`/howto/custom-model-fields`.
Field options
-------------
@@ -353,7 +351,7 @@ For example, if a ``Pizza`` has multiple ``Topping`` objects -- that is, a
As with :class:`~django.db.models.ForeignKey`, you can also create
:ref:`recursive relationships <recursive-relationships>` (an object with a
-many-to-one relationship to itself) and :ref:`relationships to models not yet
+many-to-many relationship to itself) and :ref:`relationships to models not yet
defined <lazy-relationships>`; see :ref:`the model field reference
<ref-manytomany>` for details.
@@ -612,7 +610,7 @@ Custom field types
If one of the existing model fields cannot be used to fit your purposes, or if
you wish to take advantage of some less common database column types, you can
create your own field class. Full coverage of creating your own fields is
-provided in :ref:`howto-custom-model-fields`.
+provided in :doc:`/howto/custom-model-fields`.
.. _meta-options:
@@ -634,8 +632,8 @@ human-readable singular and plural names (:attr:`~Options.verbose_name` and
:attr:`~Options.verbose_name_plural`). None are required, and adding ``class
Meta`` to a model is completely optional.
-A complete list of all possible ``Meta`` options can be found in the :ref:`model
-option reference <ref-models-options>`.
+A complete list of all possible ``Meta`` options can be found in the :doc:`model
+option reference </ref/models/options>`.
.. _model-methods:
@@ -684,7 +682,7 @@ properties`_.
.. _Read more about properties: http://www.python.org/download/releases/2.2/descrintro/#property
-The :ref:`model instance reference <ref-models-instances>` has a complete list
+The :doc:`model instance reference </ref/models/instances>` has a complete list
of :ref:`methods automatically given to each model <model-instance-methods>`.
You can override most of these -- see `overriding predefined model methods`_,
below -- but there are a couple that you'll almost always want to define:
@@ -763,7 +761,7 @@ Executing custom SQL
Another common pattern is writing custom SQL statements in model methods and
module-level methods. For more details on using raw SQL, see the documentation
-on :ref:`using raw SQL<topics-db-sql>`.
+on :doc:`using raw SQL</topics/db/sql>`.
.. _model-inheritance:
diff --git a/docs/topics/db/multi-db.txt b/docs/topics/db/multi-db.txt
index e3f62ea71b..1a939b0e3a 100644
--- a/docs/topics/db/multi-db.txt
+++ b/docs/topics/db/multi-db.txt
@@ -1,5 +1,3 @@
-.. _topics-db-multi-db:
-
==================
Multiple databases
==================
@@ -240,7 +238,7 @@ master/slave relationship between the databases ``master``, ``slave1`` and
return False
return None
- class MasterSlaveRouter(object):
+ class MasterSlaveRouter(object):
"""A router that sets up a simple master/slave configuration"""
def db_for_read(self, model, **hints):
diff --git a/docs/topics/db/optimization.txt b/docs/topics/db/optimization.txt
index 6063bc6c2a..baf8cfa268 100644
--- a/docs/topics/db/optimization.txt
+++ b/docs/topics/db/optimization.txt
@@ -1,11 +1,9 @@
-.. _topics-db-optimization:
-
============================
Database access optimization
============================
Django's database layer provides various ways to help developers get the most
-out of their databases. This documents gathers together links to the relevant
+out of their databases. This document gathers together links to the relevant
documentation, and adds various tips, organized under an number of headings that
outline the steps to take when attempting to optimize your database usage.
@@ -45,13 +43,13 @@ Use standard DB optimization techniques
We will assume you have done the obvious things above. The rest of this document
focuses on how to use Django in such a way that you are not doing unnecessary
work. This document also does not address other optimization techniques that
-apply to all expensive operations, such as :ref:`general purpose caching
-<topics-cache>`.
+apply to all expensive operations, such as :doc:`general purpose caching
+</topics/cache>`.
Understand QuerySets
====================
-Understanding :ref:`QuerySets <ref-models-querysets>` is vital to getting good
+Understanding :doc:`QuerySets </ref/models/querysets>` is vital to getting good
performance with simple code. In particular:
Understand QuerySet evaluation
@@ -101,36 +99,35 @@ Use ``iterator()``
When you have a lot of objects, the caching behaviour of the ``QuerySet`` can
cause a large amount of memory to be used. In this case,
-:ref:`QuerySet.iterator() <queryset-iterator>` may help.
+:meth:`~django.db.models.QuerySet.iterator()` may help.
Do database work in the database rather than in Python
======================================================
For instance:
-* At the most basic level, use :ref:`filter and exclude <queryset-api>` to
- filtering in the database to avoid loading data into your Python process, only
- to throw much of it away.
+* At the most basic level, use :ref:`filter and exclude <queryset-api>` to do
+ filtering in the database.
* Use :ref:`F() object query expressions <query-expressions>` to do filtering
against other fields within the same model.
-* Use :ref:`annotate to do aggregation in the database <topics-db-aggregation>`.
+* Use :doc:`annotate to do aggregation in the database </topics/db/aggregation>`.
If these aren't enough to generate the SQL you need:
Use ``QuerySet.extra()``
------------------------
-A less portable but more powerful method is :ref:`QuerySet.extra()
-<queryset-extra>`, which allows some SQL to be explicitly added to the query.
-If that still isn't powerful enough:
+A less portable but more powerful method is
+:meth:`~django.db.models.QuerySet.extra()`, which allows some SQL to be
+explicitly added to the query. If that still isn't powerful enough:
Use raw SQL
-----------
-Write your own :ref:`custom SQL to retrieve data or populate models
-<topics-db-sql>`. Use ``django.db.connection.queries`` to find out what Django
+Write your own :doc:`custom SQL to retrieve data or populate models
+</topics/db/sql>`. Use ``django.db.connection.queries`` to find out what Django
is writing for you and start from there.
Retrieve everything at once if you know you will need it
@@ -149,7 +146,7 @@ Understand :ref:`QuerySet.select_related() <select-related>` thoroughly, and use
* in view code,
-* and in :ref:`managers and default managers <topics-db-managers>` where
+* and in :doc:`managers and default managers </topics/db/managers>` where
appropriate. Be aware when your manager is and is not used; sometimes this is
tricky so don't make assumptions.
@@ -160,7 +157,7 @@ Use ``QuerySet.values()`` and ``values_list()``
-----------------------------------------------
When you just want a dict/list of values, and don't need ORM model objects, make
-appropriate usage of :ref:`QuerySet.values() <queryset-values>`.
+appropriate usage of :meth:`~django.db.models.QuerySet.values()`.
These can be useful for replacing model objects in template code - as long as
the dicts you supply have the same attributes as those used in the template, you
are fine.
@@ -168,7 +165,8 @@ are fine.
Use ``QuerySet.defer()`` and ``only()``
---------------------------------------
-Use :ref:`defer() and only() <queryset-defer>` if there are database columns you
+Use :meth:`~django.db.models.QuerySet.defer()` and
+:meth:`~django.db.models.QuerySet.only()` if there are database columns you
know that you won't need (or won't need in most cases) to avoid loading
them. Note that if you *do* use them, the ORM will have to go and get them in a
separate query, making this a pessimization if you use it inappropriately.
@@ -243,10 +241,7 @@ individual, use a bulk SQL UPDATE statement, via :ref:`QuerySet.update()
Note, however, that these bulk update methods cannot call the ``save()`` or ``delete()``
methods of individual instances, which means that any custom behaviour you have
added for these methods will not be executed, including anything driven from the
-normal database object :ref:`signals <ref-signals>`.
-
-Don't retrieve things you already have
-======================================
+normal database object :doc:`signals </ref/signals>`.
Use foreign key values directly
-------------------------------
diff --git a/docs/topics/db/queries.txt b/docs/topics/db/queries.txt
index 981d727f4f..b0d053c2e9 100644
--- a/docs/topics/db/queries.txt
+++ b/docs/topics/db/queries.txt
@@ -1,15 +1,13 @@
-.. _topics-db-queries:
-
==============
Making queries
==============
.. currentmodule:: django.db.models
-Once you've created your :ref:`data models <topics-db-models>`, Django
+Once you've created your :doc:`data models </topics/db/models>`, Django
automatically gives you a database-abstraction API that lets you create,
retrieve, update and delete objects. This document explains how to use this
-API. Refer to the :ref:`data model reference <ref-models-index>` for full
+API. Refer to the :doc:`data model reference </ref/models/index>` for full
details of all the various model lookup options.
Throughout this guide (and in the reference), we'll refer to the following
@@ -825,6 +823,8 @@ a join with an ``F()`` object, a ``FieldError`` will be raised::
# THIS WILL RAISE A FieldError
>>> Entry.objects.update(headline=F('blog__name'))
+.. _topics-db-queries-related:
+
Related objects
===============
@@ -937,7 +937,7 @@ be accessed from an instance::
In addition to the ``QuerySet`` methods defined in "Retrieving objects" above,
the ``ForeignKey`` ``Manager`` has additional methods used to handle the set of
related objects. A synopsis of each is below, and complete details can be found
-in the :ref:`related objects reference <ref-models-relations>`.
+in the :doc:`related objects reference </ref/models/relations>`.
``add(obj1, obj2, ...)``
Adds the specified model objects to the related object set.
@@ -1067,7 +1067,7 @@ Falling back to raw SQL
If you find yourself needing to write an SQL query that is too complex for
Django's database-mapper to handle, you can fall back on writing SQL by hand.
Django has a couple of options for writing raw SQL queries; see
-:ref:`topics-db-sql`.
+:doc:`/topics/db/sql`.
Finally, it's important to note that the Django database layer is merely an
interface to your database. You can access your database via other tools,
diff --git a/docs/topics/db/sql.txt b/docs/topics/db/sql.txt
index f55a164373..9f2be7a2ef 100644
--- a/docs/topics/db/sql.txt
+++ b/docs/topics/db/sql.txt
@@ -1,12 +1,10 @@
-.. _topics-db-sql:
-
==========================
Performing raw SQL queries
==========================
.. currentmodule:: django.db.models
-When the :ref:`model query APIs <topics-db-queries>` don't go far enough, you
+When the :doc:`model query APIs </topics/db/queries>` don't go far enough, you
can fall back to writing raw SQL. Django gives you two ways of performing raw
SQL queries: you can use :meth:`Manager.raw()` to `perform raw queries and
return model instances`__, or you can avoid the model layer entirely and
@@ -116,9 +114,9 @@ Fields may also be left out::
>>> people = Person.objects.raw('SELECT id, first_name FROM myapp_person')
-The ``Person`` objects returned by this query will be :ref:`deferred
-<queryset-defer>` model instances. This means that the fields that are omitted
-from the query will be loaded on demand. For example::
+The ``Person`` objects returned by this query will be deferred model instances
+(see :meth:`~django.db.models.QuerySet.defer()`). This means that the fields
+that are omitted from the query will be loaded on demand. For example::
>>> for p in Person.objects.raw('SELECT id, first_name FROM myapp_person'):
... print p.first_name, # This will be retrieved by the original query
@@ -269,7 +267,7 @@ Connections and cursors
-----------------------
``connection`` and ``cursor`` mostly implement the standard `Python DB-API`_
-(except when it comes to :ref:`transaction handling <topics-db-transactions>`).
+(except when it comes to :doc:`transaction handling </topics/db/transactions>`).
If you're not familiar with the Python DB-API, note that the SQL statement in
``cursor.execute()`` uses placeholders, ``"%s"``, rather than adding parameters
directly within the SQL. If you use this technique, the underlying database
diff --git a/docs/topics/db/transactions.txt b/docs/topics/db/transactions.txt
index fb6e3f8646..2d99c17a32 100644
--- a/docs/topics/db/transactions.txt
+++ b/docs/topics/db/transactions.txt
@@ -1,5 +1,3 @@
-.. _topics-db-transactions:
-
==============================
Managing database transactions
==============================
@@ -306,7 +304,7 @@ Database-level autocommit
.. versionadded:: 1.1
With PostgreSQL 8.2 or later, there is an advanced option to run PostgreSQL
-with :ref:`database-level autocommit <ref-databases>`. If you use this option,
+with :doc:`database-level autocommit </ref/databases>`. If you use this option,
there is no constantly open transaction, so it is always possible to continue
after catching an exception. For example::
diff --git a/docs/topics/email.txt b/docs/topics/email.txt
index 74e153de61..31092b0aaa 100644
--- a/docs/topics/email.txt
+++ b/docs/topics/email.txt
@@ -1,5 +1,3 @@
-.. _topics-email:
-
==============
Sending e-mail
==============
@@ -501,7 +499,7 @@ convenience that can be used during development.
Defining a custom e-mail backend
--------------------------------
-If you need to change how e-mails are send you can write your own e-mail
+If you need to change how e-mails are sent you can write your own e-mail
backend. The ``EMAIL_BACKEND`` setting in your settings file is then the
Python import path for your backend class.
diff --git a/docs/topics/files.txt b/docs/topics/files.txt
index 45aca5488a..26114cb50b 100644
--- a/docs/topics/files.txt
+++ b/docs/topics/files.txt
@@ -1,5 +1,3 @@
-.. _topics-files:
-
==============
Managing files
==============
@@ -70,7 +68,7 @@ using a Python built-in ``file`` object::
>>> myfile = File(f)
Now you can use any of the ``File`` attributes and methods documented in
-:ref:`ref-files-file`.
+:doc:`/ref/files/file`.
File storage
============
@@ -84,7 +82,7 @@ setting; if you don't explicitly provide a storage system, this is the one that
will be used.
See below for details of the built-in default file storage system, and see
-:ref:`howto-custom-file-storage` for information on writing your own file
+:doc:`/howto/custom-file-storage` for information on writing your own file
storage system.
Storage objects
@@ -111,7 +109,7 @@ useful -- you can use the global default storage system::
>>> default_storage.exists(path)
False
-See :ref:`ref-files-storage` for the file storage API.
+See :doc:`/ref/files/storage` for the file storage API.
The built-in filesystem storage class
-------------------------------------
@@ -143,5 +141,5 @@ For example, the following code will store uploaded files under
...
photo = models.ImageField(storage=fs)
-:ref:`Custom storage systems <howto-custom-file-storage>` work the same way: you
+:doc:`Custom storage systems </howto/custom-file-storage>` work the same way: you
can pass them in as the ``storage`` argument to a ``FileField``.
diff --git a/docs/topics/forms/formsets.txt b/docs/topics/forms/formsets.txt
index 732fd93de1..e7b09dc409 100644
--- a/docs/topics/forms/formsets.txt
+++ b/docs/topics/forms/formsets.txt
@@ -1,4 +1,3 @@
-.. _topics-forms-formsets:
.. _formsets:
Formsets
diff --git a/docs/topics/forms/index.txt b/docs/topics/forms/index.txt
index 119e943889..cef322a02f 100644
--- a/docs/topics/forms/index.txt
+++ b/docs/topics/forms/index.txt
@@ -1,5 +1,3 @@
-.. _topics-forms-index:
-
==================
Working with forms
==================
@@ -7,8 +5,8 @@ Working with forms
.. admonition:: About this document
This document provides an introduction to Django's form handling features.
- For a more detailed look at the forms API, see :ref:`ref-forms-api`. For
- documentation of the available field types, see :ref:`ref-forms-fields`.
+ For a more detailed look at the forms API, see :doc:`/ref/forms/api`. For
+ documentation of the available field types, see :doc:`/ref/forms/fields`.
.. highlightlang:: html+django
@@ -77,10 +75,10 @@ personal Web site:
A form is composed of ``Field`` objects. In this case, our form has four
fields: ``subject``, ``message``, ``sender`` and ``cc_myself``. ``CharField``,
``EmailField`` and ``BooleanField`` are just three of the available field types;
-a full list can be found in :ref:`ref-forms-fields`.
+a full list can be found in :doc:`/ref/forms/fields`.
If your form is going to be used to directly add or edit a Django model, you can
-use a :ref:`ModelForm <topics-forms-modelforms>` to avoid duplicating your model
+use a :doc:`ModelForm </topics/forms/modelforms>` to avoid duplicating your model
description.
Using a form in a view
@@ -163,7 +161,7 @@ Extending the above example, here's how the form data could be processed:
send_mail(subject, message, sender, recipients)
return HttpResponseRedirect('/thanks/') # Redirect after POST
-For more on sending e-mail from Django, see :ref:`topics-email`.
+For more on sending e-mail from Django, see :doc:`/topics/email`.
Displaying a form using a template
----------------------------------
@@ -397,4 +395,4 @@ This covers the basics, but forms can do a whole lot more:
.. seealso::
- The :ref:`form API reference <ref-forms-index>`.
+ The :doc:`form API reference </ref/forms/index>`.
diff --git a/docs/topics/forms/media.txt b/docs/topics/forms/media.txt
index 663b0d3113..64cf50743d 100644
--- a/docs/topics/forms/media.txt
+++ b/docs/topics/forms/media.txt
@@ -1,5 +1,3 @@
-.. _topics-forms-media:
-
Form Media
==========
diff --git a/docs/topics/forms/modelforms.txt b/docs/topics/forms/modelforms.txt
index fd3edf5104..2cdd2bfa74 100644
--- a/docs/topics/forms/modelforms.txt
+++ b/docs/topics/forms/modelforms.txt
@@ -1,5 +1,3 @@
-.. _topics-forms-modelforms:
-
==========================
Creating forms from models
==========================
@@ -446,7 +444,7 @@ parameter when declaring the form field::
class Meta:
model = Article
- See the :ref:`form field documentation <ref-forms-fields>` for more information
+ See the :doc:`form field documentation </ref/forms/fields>` for more information
on fields and their arguments.
Changing the order of fields
@@ -540,7 +538,7 @@ Interaction with model validation
As part of its validation process, ``ModelForm`` will call the ``clean()``
method of each field on your model that has a corresponding field on your form.
If you have excluded any model fields, validation will not be run on those
-fields. See the :ref:`form validation <ref-forms-validation>` documentation
+fields. See the :doc:`form validation </ref/forms/validation>` documentation
for more on how field cleaning and validation work. Also, your model's
``clean()`` method will be called before any uniqueness checks are made. See
:ref:`Validating objects <validating-objects>` for more information on the
@@ -551,7 +549,7 @@ model's ``clean()`` hook.
Model formsets
==============
-Like :ref:`regular formsets <topics-forms-formsets>`, Django provides a couple
+Like :doc:`regular formsets </topics/forms/formsets>`, Django provides a couple
of enhanced formset classes that make it easy to work with Django models. Let's
reuse the ``Author`` model from above::
@@ -595,8 +593,8 @@ Alternatively, you can create a subclass that sets ``self.queryset`` in
class BaseAuthorFormSet(BaseModelFormSet):
def __init__(self, *args, **kwargs):
- self.queryset = Author.objects.filter(name__startswith='O')
super(BaseAuthorFormSet, self).__init__(*args, **kwargs)
+ self.queryset = Author.objects.filter(name__startswith='O')
Then, pass your ``BaseAuthorFormSet`` class to the factory function::
diff --git a/docs/topics/generic-views.txt b/docs/topics/generic-views.txt
index f70bb43f38..f90745d451 100644
--- a/docs/topics/generic-views.txt
+++ b/docs/topics/generic-views.txt
@@ -1,5 +1,3 @@
-.. _topics-generic-views:
-
=============
Generic views
=============
@@ -192,7 +190,7 @@ might look like the following::
That's really all there is to it. All the cool features of generic views come
from changing the "info" dictionary passed to the generic view. The
-:ref:`generic views reference<ref-generic-views>` documents all the generic
+:doc:`generic views reference</ref/generic-views>` documents all the generic
views and all their options in detail; the rest of this document will consider
some of the common ways you might customize and extend generic views.
@@ -315,9 +313,9 @@ Viewing subsets of objects
Now let's take a closer look at this ``queryset`` key we've been using all
along. Most generic views take one of these ``queryset`` arguments -- it's how
-the view knows which set of objects to display (see :ref:`topics-db-queries` for
+the view knows which set of objects to display (see :doc:`/topics/db/queries` for
more information about ``QuerySet`` objects, and see the
-:ref:`generic views reference<ref-generic-views>` for the complete details).
+:doc:`generic views reference</ref/generic-views>` 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:
@@ -365,7 +363,7 @@ We'll deal with this problem in the next section.
If you get a 404 when requesting ``/books/acme/``, check to ensure you
actually have a Publisher with the name 'ACME Publishing'. Generic
views have an ``allow_empty`` parameter for this case. See the
- :ref:`generic views reference<ref-generic-views>` for more details.
+ :doc:`generic views reference</ref/generic-views>` for more details.
Complex filtering with wrapper functions
----------------------------------------
diff --git a/docs/topics/http/file-uploads.txt b/docs/topics/http/file-uploads.txt
index ab8277599c..6b0a4d5722 100644
--- a/docs/topics/http/file-uploads.txt
+++ b/docs/topics/http/file-uploads.txt
@@ -1,5 +1,3 @@
-.. _topics-http-file-uploads:
-
============
File Uploads
============
@@ -10,8 +8,8 @@ File Uploads
When Django handles a file upload, the file data ends up placed in
:attr:`request.FILES <django.http.HttpRequest.FILES>` (for more on the
-``request`` object see the documentation for :ref:`request and response objects
-<ref-request-response>`). This document explains how files are stored on disk
+``request`` object see the documentation for :doc:`request and response objects
+</ref/request-response>`). This document explains how files are stored on disk
and in memory, and how to customize the default behavior.
Basic file uploads
diff --git a/docs/topics/http/generic-views.txt b/docs/topics/http/generic-views.txt
index 5aa2c48ea5..15f895ea78 100644
--- a/docs/topics/http/generic-views.txt
+++ b/docs/topics/http/generic-views.txt
@@ -1,7 +1,5 @@
-.. _topics-http-generic-views:
-
=============
Generic views
=============
-See :ref:`ref-generic-views`. \ No newline at end of file
+See :doc:`/ref/generic-views`.
diff --git a/docs/topics/http/index.txt b/docs/topics/http/index.txt
index ae73c2c29b..5ef776dd7b 100644
--- a/docs/topics/http/index.txt
+++ b/docs/topics/http/index.txt
@@ -1,5 +1,3 @@
-.. _topics-http-index:
-
Handling HTTP requests
======================
diff --git a/docs/topics/http/middleware.txt b/docs/topics/http/middleware.txt
index 215a4ec12c..eee398a3dc 100644
--- a/docs/topics/http/middleware.txt
+++ b/docs/topics/http/middleware.txt
@@ -1,5 +1,3 @@
-.. _topics-http-middleware:
-
==========
Middleware
==========
@@ -14,8 +12,8 @@ an ``"X-View"`` HTTP header to every response to a ``HEAD`` request.
This document explains how middleware works, how you activate middleware, and
how to write your own middleware. Django ships with some built-in middleware
-you can use right out of the box; they're documented in the :ref:`built-in
-middleware reference <ref-middleware>`.
+you can use right out of the box; they're documented in the :doc:`built-in
+middleware reference </ref/middleware>`.
Activating middleware
=====================
@@ -173,9 +171,9 @@ Guidelines
cares about is that the :setting:`MIDDLEWARE_CLASSES` setting includes
the path to it.
- * Feel free to look at :ref:`Django's available middleware
- <ref-middleware>` for examples.
+ * Feel free to look at :doc:`Django's available middleware
+ </ref/middleware>` for examples.
* If you write a middleware component that you think would be useful to
- other people, contribute to the community! :ref:`Let us know
- <internals-contributing>`, and we'll consider adding it to Django.
+ other people, contribute to the community! :doc:`Let us know
+ </internals/contributing>`, and we'll consider adding it to Django.
diff --git a/docs/topics/http/sessions.txt b/docs/topics/http/sessions.txt
index 68ead03b65..8a0f0d4b72 100644
--- a/docs/topics/http/sessions.txt
+++ b/docs/topics/http/sessions.txt
@@ -1,5 +1,3 @@
-.. _topics-http-sessions:
-
===================
How to use sessions
===================
@@ -15,7 +13,7 @@ Cookies contain a session ID -- not the data itself.
Enabling sessions
=================
-Sessions are implemented via a piece of :ref:`middleware <ref-middleware>`.
+Sessions are implemented via a piece of :doc:`middleware </ref/middleware>`.
To enable session functionality, do the following:
@@ -56,8 +54,8 @@ For better performance, you may want to use a cache-based session backend.
Django 1.0 did not include the ``cached_db`` session backend.
To store session data using Django's cache system, you'll first need to make
-sure you've configured your cache; see the :ref:`cache documentation
-<topics-cache>` for details.
+sure you've configured your cache; see the :doc:`cache documentation
+</topics/cache>` for details.
.. warning::
@@ -412,7 +410,7 @@ in the past -- but your application may have different requirements.
Settings
========
-A few :ref:`Django settings <ref-settings>` give you control over session behavior:
+A few :doc:`Django settings </ref/settings>` give you control over session behavior:
SESSION_ENGINE
--------------
diff --git a/docs/topics/http/shortcuts.txt b/docs/topics/http/shortcuts.txt
index 5510613355..6bd3058941 100644
--- a/docs/topics/http/shortcuts.txt
+++ b/docs/topics/http/shortcuts.txt
@@ -1,5 +1,3 @@
-.. _topics-http-shortcuts:
-
=========================
Django shortcut functions
=========================
diff --git a/docs/topics/http/urls.txt b/docs/topics/http/urls.txt
index 5a2980f9d2..1f499909ee 100644
--- a/docs/topics/http/urls.txt
+++ b/docs/topics/http/urls.txt
@@ -1,5 +1,3 @@
-.. _topics-http-urls:
-
==============
URL dispatcher
==============
@@ -335,7 +333,7 @@ The view prefix
You can specify a common prefix in your ``patterns()`` call, to cut down on
code duplication.
-Here's the example URLconf from the :ref:`Django overview <intro-overview>`::
+Here's the example URLconf from the :doc:`Django overview </intro/overview>`::
from django.conf.urls.defaults import *
@@ -537,8 +535,8 @@ In this example, for a request to ``/blog/2005/``, Django will call the
year='2005', foo='bar'
-This technique is used in :ref:`generic views <ref-generic-views>` and in the
-:ref:`syndication framework <ref-contrib-syndication>` to pass metadata and
+This technique is used in :doc:`generic views </ref/generic-views>` and in the
+:doc:`syndication framework </ref/contrib/syndication>` to pass metadata and
options to views.
.. admonition:: Dealing with conflicts
@@ -827,17 +825,80 @@ namespaces into URLs on specific application instances, according to the
resolve()
---------
-The :func:`django.core.urlresolvers.resolve` function can be used for resolving
-URL paths to the corresponding view functions. It has the following signature:
+The :func:`django.core.urlresolvers.resolve` function can be used for
+resolving URL paths to the corresponding view functions. It has the
+following signature:
.. function:: resolve(path, urlconf=None)
-``path`` is the URL path you want to resolve. As with ``reverse()`` above, you
-don't need to worry about the ``urlconf`` parameter. The function returns the
-triple (view function, arguments, keyword arguments).
+``path`` is the URL path you want to resolve. As with
+:func:`~django.core.urlresolvers.reverse`, you don't need to
+worry about the ``urlconf`` parameter. The function returns a
+:class:`django.core.urlresolvers.ResolverMatch` object that allows you
+to access various meta-data about the resolved URL.
+
+.. class:: ResolverMatch()
+
+ .. attribute:: ResolverMatch.func
+
+ The view function that would be used to serve the URL
+
+ .. attribute:: ResolverMatch.args
+
+ The arguments that would be passed to the view function, as
+ parsed from the URL.
+
+ .. attribute:: ResolverMatch.kwargs
+
+ The keyword arguments that would be passed to the view
+ function, as parsed from the URL.
+
+ .. attribute:: ResolverMatch.url_name
+
+ The name of the URL pattern that matches the URL.
+
+ .. attribute:: ResolverMatch.app_name
+
+ The application namespace for the URL pattern that matches the
+ URL.
+
+ .. attribute:: ResolverMatch.namespace
+
+ The instance namespace for the URL pattern that matches the
+ URL.
-For example, it can be used for testing if a view would raise a ``Http404``
-error before redirecting to it::
+ .. attribute:: ResolverMatch.namespaces
+
+ The list of individual namespace components in the full
+ instance namespace for the URL pattern that matches the URL.
+ i.e., if the namespace is ``foo:bar``, then namespaces will be
+ ``[`foo`, `bar`]``.
+
+A :class:`~django.core.urlresolvers.ResolverMatch` object can then be
+interrogated to provide information about the URL pattern that matches
+a URL::
+
+ # Resolve a URL
+ match = resolve('/some/path/')
+ # Print the URL pattern that matches the URL
+ print match.url_name
+
+A :class:`~django.core.urlresolvers.ResolverMatch` object can also be
+assigned to a triple::
+
+ func, args, kwargs = resolve('/some/path/')
+
+.. versionchanged:: 1.3
+ Triple-assignment exists for backwards-compatibility. Prior to
+ Django 1.3, :func:`~django.core.urlresolvers.resolve` returned a
+ triple containing (view function, arguments, keyword arguments);
+ the :class:`~django.core.urlresolvers.ResolverMatch` object (as
+ well as the namespace and pattern information it provides) is not
+ available in earlier Django releases.
+
+One possible use of :func:`~django.core.urlresolvers.resolve` would be
+to testing if a view would raise a ``Http404`` error before
+redirecting to it::
from urlparse import urlparse
from django.core.urlresolvers import resolve
@@ -858,9 +919,29 @@ error before redirecting to it::
return HttpResponseRedirect('/')
return response
+
permalink()
-----------
The :func:`django.db.models.permalink` decorator is useful for writing short
methods that return a full URL path. For example, a model's
``get_absolute_url()`` method. See :func:`django.db.models.permalink` for more.
+
+get_script_prefix()
+-------------------
+
+.. function:: get_script_prefix()
+
+.. versionadded:: 1.0
+
+Normally, you should always use :func:`~django.core.urlresolvers.reverse` or
+:func:`~django.db.models.permalink` to define URLs within your application.
+However, if your application constructs part of the URL hierarchy itself, you
+may occasionally need to generate URLs. In that case, you need to be able to
+find the base URL of the Django project within its web server
+(normally, :func:`~django.core.urlresolvers.reverse` takes care of this for
+you). In that case, you can call ``get_script_prefix()``, which will return the
+script prefix portion of the URL for your Django project. If your Django
+project is at the root of its webserver, this is always ``"/"``, but it can be
+changed, for instance by using ``django.root`` (see :ref:`How to use
+Django with Apache and mod_python <howto-deployment-modpython>`).
diff --git a/docs/topics/http/views.txt b/docs/topics/http/views.txt
index 7d8743fe06..399e6b6ad1 100644
--- a/docs/topics/http/views.txt
+++ b/docs/topics/http/views.txt
@@ -1,5 +1,3 @@
-.. _topics-http-views:
-
=============
Writing Views
=============
@@ -59,7 +57,7 @@ Mapping URLs to Views
So, to recap, this view function returns an HTML page that includes the current
date and time. To display this view at a particular URL, you'll need to create a
-*URLconf*; see :ref:`topics-http-urls` for instructions.
+*URLconf*; see :doc:`/topics/http/urls` for instructions.
Returning errors
================
diff --git a/docs/topics/i18n/deployment.txt b/docs/topics/i18n/deployment.txt
index 1a4f5fa4d5..f06227e0f6 100644
--- a/docs/topics/i18n/deployment.txt
+++ b/docs/topics/i18n/deployment.txt
@@ -1,5 +1,3 @@
-.. _topics-i18n-deployment:
-
==========================
Deployment of translations
==========================
@@ -72,8 +70,8 @@ For example, your ``MIDDLEWARE_CLASSES`` might look like this::
'django.middleware.common.CommonMiddleware',
)
-(For more on middleware, see the :ref:`middleware documentation
-<topics-http-middleware>`.)
+(For more on middleware, see the :doc:`middleware documentation
+</topics/http/middleware>`.)
``LocaleMiddleware`` tries to determine the user's language preference by
following this algorithm:
diff --git a/docs/topics/i18n/index.txt b/docs/topics/i18n/index.txt
index e39a75067a..9c25192504 100644
--- a/docs/topics/i18n/index.txt
+++ b/docs/topics/i18n/index.txt
@@ -1,5 +1,3 @@
-.. _topics-i18n:
-
=====================================
Internationalization and localization
=====================================
@@ -23,10 +21,10 @@ associated with each of these tasks (although it's perfectly normal if you
find yourself performing more than one of these roles):
* For application authors wishing to make sure their Django apps can be
- used in different locales: :ref:`topics-i18n-internationalization`.
- * For translators wanting to translate Django apps: :ref:`topics-i18n-localization`.
+ used in different locales: :doc:`/topics/i18n/internationalization`.
+ * For translators wanting to translate Django apps: :doc:`/topics/i18n/localization`.
* For system administrators/final users setting up internationalized apps or
- developers integrating third party apps: :ref:`topics-i18n-deployment`.
+ developers integrating third party apps: :doc:`/topics/i18n/deployment`.
.. toctree::
:hidden:
diff --git a/docs/topics/i18n/internationalization.txt b/docs/topics/i18n/internationalization.txt
index 7ae8d18791..879c7739fb 100644
--- a/docs/topics/i18n/internationalization.txt
+++ b/docs/topics/i18n/internationalization.txt
@@ -1,5 +1,3 @@
-.. _topics-i18n-internationalization:
-
====================
Internationalization
====================
@@ -242,7 +240,7 @@ If you don't like the verbose name ``ugettext_lazy``, you can just alias it as
class MyThing(models.Model):
name = models.CharField(help_text=_('This is the help text'))
-Always use lazy translations in :ref:`Django models <topics-db-models>`.
+Always use lazy translations in :doc:`Django models </topics/db/models>`.
Field names and table names should be marked for translation (otherwise, they
won't be translated in the admin interface). This means writing explicit
``verbose_name`` and ``verbose_name_plural`` options in the ``Meta`` class,
@@ -332,7 +330,7 @@ Specifying translation strings: In template code
.. highlightlang:: html+django
-Translations in :ref:`Django templates <topics-templates>` uses two template
+Translations in :doc:`Django templates </topics/templates>` uses two template
tags and a slightly different syntax than in Python code. To give your template
access to these tags, put ``{% load i18n %}`` toward the top of your template.
@@ -569,7 +567,7 @@ function supports both positional and named interpolation:
object or associative array. For example::
d = {
- count: 10
+ count: 10,
total: 50
};
diff --git a/docs/topics/i18n/localization.txt b/docs/topics/i18n/localization.txt
index ff8715571a..8ba1e1ecdc 100644
--- a/docs/topics/i18n/localization.txt
+++ b/docs/topics/i18n/localization.txt
@@ -1,5 +1,3 @@
-.. _topics-i18n-localization:
-
============
Localization
============
@@ -12,7 +10,7 @@ files`_ and `locale aware date, time and numbers input/output in forms`_
.. seealso::
- The :ref:`howto-i18n` document included with the Django HOW-TO documents collection.
+ The :doc:`/howto/i18n` document included with the Django HOW-TO documents collection.
.. _how-to-create-language-files:
diff --git a/docs/topics/index.txt b/docs/topics/index.txt
index 33f425a03e..4c6b7fc685 100644
--- a/docs/topics/index.txt
+++ b/docs/topics/index.txt
@@ -1,5 +1,3 @@
-.. _topics-index:
-
Using Django
============
diff --git a/docs/topics/install.txt b/docs/topics/install.txt
index d53f49de46..2965c32ab6 100644
--- a/docs/topics/install.txt
+++ b/docs/topics/install.txt
@@ -1,5 +1,3 @@
-.. _topics-install:
-
=====================
How to install Django
=====================
@@ -11,9 +9,9 @@ Install Python
Being a Python Web framework, Django requires Python.
-It works with any Python version from 2.4 to 2.6 (due to backwards
+It works with any Python version from 2.4 to 2.7 (due to backwards
incompatibilities in Python 3.0, Django does not currently work with
-Python 3.0; see :ref:`the Django FAQ <faq-install>` for more
+Python 3.0; see :doc:`the Django FAQ </faq/install>` for more
information on supported Python versions and the 3.0 transition).
Get Python at http://www.python.org. If you're running Linux or Mac OS X, you
@@ -22,34 +20,45 @@ probably already have it installed.
.. admonition:: Django on Jython
If you use Jython_ (a Python implementation for the Java platform), you'll
- need to follow a few additional steps. See :ref:`howto-jython` for details.
+ need to follow a few additional steps. See :doc:`/howto/jython` for details.
.. _jython: http://jython.org/
Install Apache and mod_wsgi
=============================
-If you just want to experiment with Django, skip ahead to the next section;
-Django includes a lightweight web server you can use for testing, so you won't
-need to set up Apache until you're ready to deploy Django in production.
-
-If you want to use Django on a production site, use Apache with `mod_wsgi`_.
-mod_wsgi is similar to mod_perl -- it embeds Python within Apache and loads
-Python code into memory when the server starts. Code stays in memory throughout
-the life of an Apache process, which leads to significant performance gains over
-other server arrangements. Make sure you have Apache installed, with the
-mod_wsgi module activated. Django will work with any version of Apache that
-supports mod_wsgi.
-
-See :ref:`How to use Django with mod_wsgi <howto-deployment-modwsgi>` for
-information on how to configure mod_wsgi once you have it installed.
-
-If you can't use mod_wsgi for some reason, fear not: Django supports many other
-deployment options. A great second choice is :ref:`mod_python
-<howto-deployment-modpython>`, the predecessor to mod_wsgi. Additionally, Django
-follows the WSGI_ spec, which allows it to run on a variety of server platforms.
-See the `server-arrangements wiki page`_ for specific installation instructions
-for each platform.
+If you just want to experiment with Django, skip ahead to the next
+section; Django includes a lightweight web server you can use for
+testing, so you won't need to set up Apache until you're ready to
+deploy Django in production.
+
+If you want to use Django on a production site, use Apache with
+`mod_wsgi`_. mod_wsgi can operate in one of two modes: an embedded
+mode and a daemon mode. In embedded mode, mod_wsgi is similar to
+mod_perl -- it embeds Python within Apache and loads Python code into
+memory when the server starts. Code stays in memory throughout the
+life of an Apache process, which leads to significant performance
+gains over other server arrangements. In daemon mode, mod_wsgi spawns
+an independent daemon process that handles requests. The daemon
+process can run as a different user than the webserver, possibly
+leading to improved security, and the daemon process can be restarted
+without restarting the entire Apache webserver, possibly making
+refreshing your codebase more seamless. Consult the mod_wsgi
+documentation to determine which mode is right for your setup. Make
+sure you have Apache installed, with the mod_wsgi module activated.
+Django will work with any version of Apache that supports mod_wsgi.
+
+See :doc:`How to use Django with mod_wsgi </howto/deployment/modwsgi>`
+for information on how to configure mod_wsgi once you have it
+installed.
+
+If you can't use mod_wsgi for some reason, fear not: Django supports
+many other deployment options. Another option is :doc:`FastCGI
+</howto/deployment/fastcgi>`, perfect for using Django with servers
+other than Apache. Additionally, Django follows the WSGI_ spec, which
+allows it to run on a variety of server platforms. See the
+`server-arrangements wiki page`_ for specific installation
+instructions for each platform.
.. _Apache: http://httpd.apache.org/
.. _mod_wsgi: http://code.google.com/p/modwsgi/
@@ -90,8 +99,8 @@ database bindings are installed.
If you're on Windows, check out the unofficial `compiled Windows version`_.
* If you're using MySQL, you'll need MySQLdb_, version 1.2.1p2 or higher. You
- will also want to read the database-specific notes for the :ref:`MySQL
- backend <ref-databases>`.
+ will also want to read the database-specific notes for the :doc:`MySQL
+ backend </ref/databases>`.
* If you're using SQLite and Python 2.4, you'll need pysqlite_. Use version
2.0.3 or higher. Python 2.5 ships with an SQLite wrapper in the standard
@@ -115,7 +124,7 @@ can simply grant Django ``SELECT``, ``INSERT``, ``UPDATE`` and
``ALTER TABLE`` privileges during ``syncdb`` but won't issue
``ALTER TABLE`` statements on a table once ``syncdb`` has created it.
-If you're using Django's :ref:`testing framework<topics-testing>` to test database queries,
+If you're using Django's :doc:`testing framework</topics/testing>` to test database queries,
Django will need permission to create a test database.
.. _PostgreSQL: http://www.postgresql.org/
@@ -177,7 +186,7 @@ It's easy, no matter which way you choose.
Installing a distribution-specific package
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Check the :ref:`distribution specific notes <misc-distributions>` to see if your
+Check the :doc:`distribution specific notes </misc/distributions>` to see if your
platform/distribution provides official Django packages/installers.
Distribution-provided packages will typically allow for automatic installation
of dependencies and easy upgrade paths.
@@ -257,15 +266,15 @@ latest bug fixes and improvements, follow these instructions:
links. (Environment variables can be defined on Windows systems `from the
Control Panel`_.)
- .. admonition:: What about Apache and mod_python?
+ .. admonition:: What about Apache and mod_wsgi?
- If you take the approach of setting ``PYTHONPATH``, you'll need to
- remember to do the same thing in your Apache configuration once you
- deploy your production site. Do this by setting ``PythonPath`` in your
- Apache configuration file.
+ If you take the approach of setting ``PYTHONPATH``, you'll need
+ to remember to do the same thing in your WSGI application once
+ you deploy your production site. Do this by appending to
+ ``sys.path`` in your WSGI application.
More information about deployment is available, of course, in our
- :ref:`How to use Django with mod_python <howto-deployment-modpython>`
+ :doc:`How to use Django with mod_wsgi </howto/deployment/modwsgi>`
documentation.
4. On Unix-like systems, create a symbolic link to the file
diff --git a/docs/topics/pagination.txt b/docs/topics/pagination.txt
index 70f087bd84..ee8a43379a 100644
--- a/docs/topics/pagination.txt
+++ b/docs/topics/pagination.txt
@@ -1,5 +1,3 @@
-.. _topics-pagination:
-
==========
Pagination
==========
diff --git a/docs/topics/serialization.txt b/docs/topics/serialization.txt
index 1cf8e86462..c8acc8539e 100644
--- a/docs/topics/serialization.txt
+++ b/docs/topics/serialization.txt
@@ -1,5 +1,3 @@
-.. _topics-serialization:
-
==========================
Serializing Django objects
==========================
@@ -141,10 +139,6 @@ to install third-party Python modules:
``json`` Serializes to and from JSON_ (using a version of simplejson_
bundled with Django).
- ``python`` Translates to and from "simple" Python objects (lists, dicts,
- strings, etc.). Not really all that useful on its own, but
- used as a base for other serializers.
-
``yaml`` Serializes to YAML (YAML Ain't a Markup Language). This
serializer is only available if PyYAML_ is installed.
========== ==============================================================
@@ -169,7 +163,7 @@ For example::
json_serializer.serialize(queryset, ensure_ascii=False, stream=response)
The Django source code includes the simplejson_ module. However, if you're
-using Python 2.6 (which includes a builtin version of the module), Django will
+using Python 2.6 or later (which includes a builtin version of the module), Django will
use the builtin ``json`` module automatically. If you have a system installed
version that includes the C-based speedup extension, or your system version is
more recent than the version shipped with Django (currently, 2.0.7), the
@@ -338,7 +332,7 @@ example, ``(first name, last name)``. Then, when you call
``serializers.serialize()``, you provide a ``use_natural_keys=True``
argument::
- >>> serializers.serialize([book1, book2], format='json', indent=2, use_natural_keys=True)
+ >>> serializers.serialize('json', [book1, book2], indent=2, use_natural_keys=True)
When ``use_natural_keys=True`` is specified, Django will use the
``natural_key()`` method to serialize any reference to objects of the
diff --git a/docs/topics/settings.txt b/docs/topics/settings.txt
index 9e6a689588..6d96190a90 100644
--- a/docs/topics/settings.txt
+++ b/docs/topics/settings.txt
@@ -1,5 +1,3 @@
-.. _topics-settings:
-
===============
Django settings
===============
@@ -46,7 +44,7 @@ Python `import search path`_.
The django-admin.py utility
---------------------------
-When using :ref:`django-admin.py <ref-django-admin>`, you can either set the
+When using :doc:`django-admin.py </ref/django-admin>`, you can either set the
environment variable once, or explicitly pass in the settings module each time
you run the utility.
@@ -66,20 +64,19 @@ Use the ``--settings`` command-line argument to specify the settings manually::
.. _django-admin.py: ../django-admin/
-On the server (mod_python)
+On the server (mod_wsgi)
--------------------------
-In your live server environment, you'll need to tell Apache/mod_python which
-settings file to use. Do that with ``SetEnv``::
+In your live server environment, you'll need to tell your WSGI
+application what settings file to use. Do that with ``os.environ``::
+
+ import os
- <Location "/mysite/">
- SetHandler python-program
- PythonHandler django.core.handlers.modpython
- SetEnv DJANGO_SETTINGS_MODULE mysite.settings
- </Location>
+ os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
-Read the :ref:`Django mod_python documentation <howto-deployment-modpython>` for
-more information.
+Read the :doc:`Django mod_wsgi documentation
+</howto/deployment/modwsgi>` for more information and other common
+elements to a Django WSGI application.
Default settings
================
@@ -151,7 +148,7 @@ read it. This is especially important in a shared-hosting environment.
Available settings
==================
-For a full list of available settings, see the :ref:`settings reference <ref-settings>`.
+For a full list of available settings, see the :doc:`settings reference </ref/settings>`.
Creating your own settings
==========================
diff --git a/docs/topics/signals.txt b/docs/topics/signals.txt
index eb1a5fd825..78790db071 100644
--- a/docs/topics/signals.txt
+++ b/docs/topics/signals.txt
@@ -1,5 +1,3 @@
-.. _topics-signals:
-
=======
Signals
=======
@@ -13,7 +11,7 @@ signals allow certain *senders* to notify a set of *receivers* that some action
has taken place. They're especially useful when many pieces of code may be
interested in the same events.
-Django provides a :ref:`set of built-in signals <ref-signals>` that let user
+Django provides a :doc:`set of built-in signals </ref/signals>` that let user
code get notified by Django itself of certain actions. These include some useful
notifications:
@@ -38,7 +36,7 @@ notifications:
Sent when Django starts or finishes an HTTP request.
-See the :ref:`built-in signal documentation <ref-signals>` for a complete list,
+See the :doc:`built-in signal documentation </ref/signals>` for a complete list,
and a complete explanation of each signal.
You can also `define and send your own custom signals`_; see below.
@@ -82,7 +80,8 @@ must be able to handle those new arguments.
Connecting receiver functions
-----------------------------
-Next, we'll need to connect our receiver to the signal:
+There are two ways you can connect a receiever to a signal. You can take the
+manual connect route:
.. code-block:: python
@@ -90,6 +89,17 @@ Next, we'll need to connect our receiver to the signal:
request_finished.connect(my_callback)
+Alternatively, you can use a decorator used when you define your receiver:
+
+.. code-block:: python
+
+ from django.core.signals import request_finished
+ from django.dispatch import receiver
+
+ @receiver(request_finished)
+ def my_callback(sender, **kwargs):
+ print "Request finished!"
+
Now, our ``my_callback`` function will be called each time a request finishes.
.. admonition:: Where should this code live?
@@ -117,18 +127,18 @@ signals sent by some model:
.. code-block:: python
from django.db.models.signals import pre_save
+ from django.dispatch import receiver
from myapp.models import MyModel
+ @receiver(pre_save, sender=MyModel)
def my_handler(sender, **kwargs):
...
- pre_save.connect(my_handler, sender=MyModel)
-
The ``my_handler`` function will only be called when an instance of ``MyModel``
is saved.
Different signals use different objects as their senders; you'll need to consult
-the :ref:`built-in signal documentation <ref-signals>` for details of each
+the :doc:`built-in signal documentation </ref/signals>` for details of each
particular signal.
Defining and sending signals
diff --git a/docs/topics/templates.txt b/docs/topics/templates.txt
index 9fa6c44dc9..492d23d716 100644
--- a/docs/topics/templates.txt
+++ b/docs/topics/templates.txt
@@ -1,5 +1,3 @@
-.. _topics-templates:
-
============================
The Django template language
============================
@@ -8,7 +6,7 @@ The Django template language
This document explains the language syntax of the Django template system. If
you're looking for a more technical perspective on how it works and how to
- extend it, see :ref:`ref-templates-api`.
+ extend it, see :doc:`/ref/templates/api`.
Django's template language is designed to strike a balance between power and
ease. It's designed to feel comfortable to those used to working with HTML. If
@@ -28,8 +26,8 @@ or CheetahTemplate_, you should feel right at home with Django's templates.
tag for looping, etc. -- but these are not simply executed as the
corresponding Python code, and the template system will not execute
arbitrary Python expressions. Only the tags, filters and syntax listed below
- are supported by default (although you can add :ref:`your own extensions
- <howto-custom-template-tags>` to the template language as needed).
+ are supported by default (although you can add :doc:`your own extensions
+ </howto/custom-template-tags>` to the template language as needed).
.. _`The Django template language: For Python programmers`: ../templates_python/
.. _Smarty: http://smarty.php.net/
@@ -140,7 +138,7 @@ template filters:
If ``value`` isn't provided or is empty, the above will display
"``nothing``".
-
+
:tfilter:`length`
Returns the length of the value. This works for both strings and lists;
for example::
@@ -148,7 +146,7 @@ template filters:
{{ value|length }}
If ``value`` is ``['a', 'b', 'c', 'd']``, the output will be ``4``.
-
+
:tfilter:`striptags`
Strips all [X]HTML tags. For example::
@@ -161,7 +159,7 @@ Again, these are just a few examples; see the :ref:`built-in filter reference
<ref-templates-builtins-filters>` for the complete list.
You can also create your own custom template filters; see
-:ref:`howto-custom-template-tags`.
+:doc:`/howto/custom-template-tags`.
Tags
====
@@ -217,7 +215,7 @@ Again, the above is only a selection of the whole list; see the :ref:`built-in
tag reference <ref-templates-builtins-tags>` for the complete list.
You can also create your own custom template tags; see
-:ref:`howto-custom-template-tags`.
+:doc:`/howto/custom-template-tags`.
Comments
========
@@ -571,6 +569,45 @@ This doesn't affect what happens to data coming from the variable itself.
The variable's contents are still automatically escaped, if necessary, because
they're beyond the control of the template author.
+.. _template-accessing-methods:
+
+Accessing method calls
+======================
+
+Most method calls attached to objects are also available from within templates.
+This means that templates have access to much more than just class attributes
+(like field names) and variables passed in from views. For example, the Django
+ORM provides the :ref:`"entry_set"<topics-db-queries-related>` syntax for
+finding a collection of objects related on a foreign key. Therefore, given
+a model called "comment" with a foreign key relationship to a model called
+"task" you can loop through all comments attached to a given task like this::
+
+ {% for comment in task.comment_set.all %}
+ {{ comment }}
+ {% endfor %}
+
+Similarly, :doc:`QuerySets<ref/models/querysets>` provide a ``count()`` method
+to count the number of objects they contain. Therefore, you can obtain a count
+of all comments related to the current task with::
+
+ {{ task.comment_set.all.count }}
+
+And of course you can easily access methods you've explicitly defined on your
+own models::
+
+ # In model
+ class Task(models.Model):
+ def foo(self):
+ return "bar"
+
+ # In template
+ {{ task.foo }}
+
+Because Django intentionally limits the amount of logic processing available
+in the template language, it is not possible to pass arguments to method calls
+accessed from within templates. Data should be calculated in views, then passed
+to templates for display.
+
.. _template-built-in-reference:
Using the built-in reference
@@ -634,8 +671,8 @@ The ``{% load %}`` tag can take multiple library names, separated by spaces.
Example::
{% load comments i18n %}
-
-See :ref:`howto-custom-template-tags` for information on writing your own custom
+
+See :doc:`/howto/custom-template-tags` for information on writing your own custom
template libraries.
Custom libraries and template inheritance
diff --git a/docs/topics/testing.txt b/docs/topics/testing.txt
index bd727ee136..5c1933c946 100644
--- a/docs/topics/testing.txt
+++ b/docs/topics/testing.txt
@@ -1,5 +1,3 @@
-.. _topics-testing:
-
===========================
Testing Django applications
===========================
@@ -311,6 +309,24 @@ can press ``Ctrl-C`` a second time and the test run will halt immediately,
but not gracefully. No details of the tests run before the interruption will
be reported, and any test databases created by the run will not be destroyed.
+Running tests outside the test runner
+-------------------------------------
+
+If you want to run tests outside of ``./manage.py test`` -- for example,
+from a shell prompt -- you will need to set up the test
+environment first. Django provides a convenience method to do this::
+
+ >>> from django.test.utils import setup_test_environment
+ >>> setup_test_environment()
+
+This convenience method sets up the test database, and puts other
+Django features into modes that allow for repeatable testing.
+
+The call to :meth:`~django.test.utils.setup_test_environment` is made
+automatically as part of the setup of `./manage.py test`. You only
+need to manually invoke this method if you're not using running your
+tests via Django's test runner.
+
The test database
-----------------
@@ -342,7 +358,7 @@ For fine-grained control over the character encoding of your test
database, use the :setting:`TEST_CHARSET` option. If you're using
MySQL, you can also use the :setting:`TEST_COLLATION` option to
control the particular collation used by the test database. See the
-:ref:`settings documentation <ref-settings>` for details of these
+:doc:`settings documentation </ref/settings>` for details of these
advanced settings.
.. _topics-testing-masterslave:
@@ -401,7 +417,7 @@ Other test conditions
---------------------
Regardless of the value of the :setting:`DEBUG` setting in your configuration
-file, all Django tests run with :setting:`DEBUG=False`. This is to ensure that
+file, all Django tests run with :setting:`DEBUG`\=False. This is to ensure that
the observed output of your code matches what will be seen in a production
setting.
@@ -556,6 +572,19 @@ Note a few important things about how the test client works:
This black magic (essentially a patching of Django's template system in
memory) only happens during test running.
+ * By default, the test client will disable any CSRF checks
+ performed by your site.
+
+ If, for some reason, you *want* the test client to perform CSRF
+ checks, you can create an instance of the test client that
+ enforces CSRF checks. To do this, pass in the
+ ``enforce_csrf_checks`` argument when you construct your
+ client::
+
+ >>> from django.test import Client
+ >>> csrf_client = Client(enforce_csrf_checks=True)
+
+
.. _urllib: http://docs.python.org/library/urllib.html
.. _urllib2: http://docs.python.org/library/urllib2.html
@@ -751,7 +780,7 @@ arguments at time of construction:
.. versionadded:: 1.0
- If your site uses Django's :ref:`authentication system<topics-auth>`
+ If your site uses Django's :doc:`authentication system</topics/auth>`
and you deal with logging in users, you can use the test client's
``login()`` method to simulate the effect of a user logging into the
site.
@@ -797,7 +826,7 @@ arguments at time of construction:
.. versionadded:: 1.0
- If your site uses Django's :ref:`authentication system<topics-auth>`,
+ If your site uses Django's :doc:`authentication system</topics/auth>`,
the ``logout()`` method can be used to simulate the effect of a user
logging out of your site.
@@ -904,7 +933,16 @@ can access these properties as part of a test condition.
.. attribute:: Client.session
A dictionary-like object containing session information. See the
- :ref:`session documentation<topics-http-sessions>` for full details.
+ :doc:`session documentation</topics/http/sessions>` for full details.
+
+ To modify the session and then save it, it must be stored in a variable
+ first (because a new ``SessionStore`` is created every time this property
+ is accessed)::
+
+ def test_something(self):
+ session = self.client.session
+ session['somekey'] = 'test'
+ session.save()
.. _Cookie module documentation: http://docs.python.org/library/cookie.html
@@ -1052,23 +1090,25 @@ A fixture is a collection of data that Django knows how to import into a
database. For example, if your site has user accounts, you might set up a
fixture of fake user accounts in order to populate your database during tests.
-The most straightforward way of creating a fixture is to use the ``manage.py
-dumpdata`` command. This assumes you already have some data in your database.
-See the :djadmin:`dumpdata documentation<dumpdata>` for more details.
+The most straightforward way of creating a fixture is to use the
+:djadmin:`manage.py dumpdata <dumpdata>` command. This assumes you
+already have some data in your database. See the :djadmin:`dumpdata
+documentation<dumpdata>` for more details.
.. note::
- If you've ever run ``manage.py syncdb``, you've already used a fixture
- without even knowing it! When you call ``syncdb`` in the database for
- the first time, Django installs a fixture called ``initial_data``.
- This gives you a way of populating a new database with any initial data,
- such as a default set of categories.
+ If you've ever run :djadmin:`manage.py syncdb<syncdb>`, you've
+ already used a fixture without even knowing it! When you call
+ :djadmin:`syncdb` in the database for the first time, Django
+ installs a fixture called ``initial_data``. This gives you a way
+ of populating a new database with any initial data, such as a
+ default set of categories.
- Fixtures with other names can always be installed manually using the
- ``manage.py loaddata`` command.
+ Fixtures with other names can always be installed manually using
+ the :djadmin:`manage.py loaddata<loaddata>` command.
Once you've created a fixture and placed it in a ``fixtures`` directory in one
of your :setting:`INSTALLED_APPS`, you can use it in your unit tests by
-specifying a ``fixtures`` class attribute on your ``django.test.TestCase``
+specifying a ``fixtures`` class attribute on your :class:`django.test.TestCase`
subclass::
from django.test import TestCase
@@ -1248,6 +1288,21 @@ cause of an failure in your test suite.
``target_status_code`` will be the url and status code for the final
point of the redirect chain.
+.. method:: TestCase.assertQuerysetEqual(qs, values, transform=repr)
+
+ .. versionadded:: 1.3
+
+ Asserts that a queryset ``qs`` returns a particular list of values ``values``.
+
+ The comparison of the contents of ``qs`` and ``values`` is performed using
+ the function ``transform``; by default, this means that the ``repr()`` of
+ each value is compared. Any other callable can be used if ``repr()`` doesn't
+ provide a unique or helpful comparison.
+
+ The comparison is also ordering dependent. If ``qs`` doesn't provide an
+ implicit ordering, you will need to apply a ``order_by()`` clause to your
+ queryset to ensure that the test will pass reliably.
+
.. _topics-testing-email:
E-mail services
@@ -1255,8 +1310,8 @@ E-mail services
.. versionadded:: 1.0
-If any of your Django views send e-mail using :ref:`Django's e-mail
-functionality <topics-email>`, you probably don't want to send e-mail each time
+If any of your Django views send e-mail using :doc:`Django's e-mail
+functionality </topics/email>`, you probably don't want to send e-mail each time
you run a test using that view. For this reason, Django's test runner
automatically redirects all Django-sent e-mail to a dummy outbox. This lets you
test every aspect of sending e-mail -- from the number of messages sent to the