From f911df19a455246198b0c8c81ab96bf2abec04f8 Mon Sep 17 00:00:00 2001 From: Honza Král Date: Mon, 28 Dec 2009 16:35:23 +0000 Subject: [soc2009/model-validation] Merget to trunk at r12009 git-svn-id: http://code.djangoproject.com/svn/django/branches/soc2009/model-validation@12014 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/faq/install.txt | 2 +- docs/howto/auth-remote-user.txt | 2 +- docs/howto/custom-model-fields.txt | 148 ++++++-- docs/howto/custom-template-tags.txt | 79 ++++ docs/howto/deployment/modpython.txt | 4 +- docs/howto/initial-data.txt | 36 +- docs/howto/legacy-databases.txt | 19 +- docs/howto/outputting-pdf.txt | 10 +- docs/index.txt | 6 +- docs/internals/contributing.txt | 102 ++++- docs/internals/deprecation.txt | 48 ++- docs/internals/documentation.txt | 11 +- docs/intro/tutorial01.txt | 50 +-- docs/man/django-admin.1 | 4 +- docs/ref/authbackends.txt | 8 +- docs/ref/contrib/admin/index.txt | 34 ++ docs/ref/contrib/flatpages.txt | 1 - docs/ref/contrib/formtools/form-wizard.txt | 152 ++++---- docs/ref/contrib/index.txt | 20 +- docs/ref/contrib/localflavor.txt | 62 ++- docs/ref/contrib/messages.txt | 405 ++++++++++++++++++++ docs/ref/contrib/sitemaps.txt | 4 +- docs/ref/contrib/syndication.txt | 2 +- docs/ref/databases.txt | 128 ++++--- docs/ref/django-admin.txt | 271 +++++++++++-- docs/ref/files/index.txt | 9 +- docs/ref/forms/api.txt | 149 +++++--- docs/ref/forms/index.txt | 5 +- docs/ref/generic-views.txt | 1 - docs/ref/index.txt | 2 +- docs/ref/middleware.txt | 20 +- docs/ref/models/fields.txt | 14 +- docs/ref/models/index.txt | 1 + docs/ref/models/options.txt | 6 +- docs/ref/models/querysets.txt | 37 +- docs/ref/request-response.txt | 11 +- docs/ref/settings.txt | 588 ++++++++++++++++++++++++----- docs/ref/signals.txt | 6 +- docs/ref/templates/api.txt | 147 +++++++- docs/ref/templates/builtins.txt | 177 ++++++++- docs/ref/templates/index.txt | 7 +- docs/ref/unicode.txt | 12 +- docs/releases/0.96.txt | 34 +- docs/releases/1.1-alpha-1.txt | 13 +- docs/releases/1.1.txt | 11 +- docs/releases/1.2.txt | 344 +++++++++++++++++ docs/topics/auth.txt | 83 +++- docs/topics/db/index.txt | 1 + docs/topics/db/multi-db.txt | 269 +++++++++++++ docs/topics/db/queries.txt | 13 +- docs/topics/db/sql.txt | 189 +++++++++- docs/topics/db/transactions.txt | 30 +- docs/topics/files.txt | 2 +- docs/topics/forms/modelforms.txt | 8 + docs/topics/http/file-uploads.txt | 20 +- docs/topics/http/sessions.txt | 28 +- docs/topics/http/urls.txt | 16 +- docs/topics/i18n.txt | 142 ++++--- docs/topics/install.txt | 4 +- docs/topics/serialization.txt | 192 +++++++++- docs/topics/templates.txt | 21 +- docs/topics/testing.txt | 128 ++++--- 62 files changed, 3654 insertions(+), 694 deletions(-) create mode 100644 docs/ref/contrib/messages.txt create mode 100644 docs/topics/db/multi-db.txt (limited to 'docs') diff --git a/docs/faq/install.txt b/docs/faq/install.txt index 28a89ccc1f..810247a1bc 100644 --- a/docs/faq/install.txt +++ b/docs/faq/install.txt @@ -35,7 +35,7 @@ also need a database engine. PostgreSQL_ is recommended, because we're PostgreSQL fans, and MySQL_, `SQLite 3`_, and Oracle_ are also supported. .. _Python: http://www.python.org/ -.. _WSGI: http://www.python.org/peps/pep-0333.html +.. _WSGI: http://www.python.org/dev/peps/pep-0333/ .. _server arrangements wiki page: http://code.djangoproject.com/wiki/ServerArrangements .. _PostgreSQL: http://www.postgresql.org/ .. _MySQL: http://www.mysql.com/ diff --git a/docs/howto/auth-remote-user.txt b/docs/howto/auth-remote-user.txt index 05532da0b0..b7987e14a7 100644 --- a/docs/howto/auth-remote-user.txt +++ b/docs/howto/auth-remote-user.txt @@ -12,7 +12,7 @@ Windows Authentication or Apache and `mod_authnz_ldap`_, `CAS`_, `Cosign`_, `WebAuth`_, `mod_auth_sspi`_, etc. .. _mod_authnz_ldap: http://httpd.apache.org/docs/2.2/mod/mod_authnz_ldap.html -.. _CAS: http://www.ja-sig.org/products/cas/ +.. _CAS: http://www.jasig.org/cas .. _Cosign: http://weblogin.org .. _WebAuth: http://www.stanford.edu/services/webauth/ .. _mod_auth_sspi: http://sourceforge.net/projects/mod-auth-sspi diff --git a/docs/howto/custom-model-fields.txt b/docs/howto/custom-model-fields.txt index 9f798f14d5..169f5114b8 100644 --- a/docs/howto/custom-model-fields.txt +++ b/docs/howto/custom-model-fields.txt @@ -5,6 +5,7 @@ Writing custom model fields =========================== .. versionadded:: 1.0 +.. currentmodule:: django.db.models Introduction ============ @@ -39,6 +40,8 @@ are traditionally called *north*, *east*, *south* and *west*. Our class looks something like this:: class Hand(object): + """A hand of cards (bridge style)""" + def __init__(self, north, east, south, west): # Input parameters are lists of cards ('Ah', '9s', etc) self.north = north @@ -163,6 +166,9 @@ behave like any existing field, so we'll subclass directly from from django.db import models class HandField(models.Field): + + description = "A hand of cards (bridge style)" + def __init__(self, *args, **kwargs): kwargs['max_length'] = 104 super(HandField, self).__init__(*args, **kwargs) @@ -244,6 +250,9 @@ simple: make sure your field subclass uses a special metaclass: For example:: class HandField(models.Field): + + description = "A hand of cards (bridge style)" + __metaclass__ = models.SubfieldBase def __init__(self, *args, **kwargs): @@ -252,6 +261,22 @@ For example:: This ensures that the :meth:`to_python` method, documented below, will always be called when the attribute is initialized. + +Documenting your Custom Field +----------------------------- + +.. class:: django.db.models.Field + +.. attribute:: description + +As always, you should document your field type, so users will know what it is. +In addition to providing a docstring for it, which is useful for developers, +you can also allow users of the admin app to see a short description of the +field type via the ``django.contrib.admindocs`` application. To do this simply +provide descriptive text in a ``description`` class attribute of your custom field. +In the above example, the type description displayed by the ``admindocs`` application +for a ``HandField`` will be 'A hand of cards (bridge style)'. + Useful methods -------------- @@ -263,10 +288,13 @@ approximately decreasing order of importance, so start from the top. Custom database types ~~~~~~~~~~~~~~~~~~~~~ -.. method:: db_type(self) +.. method:: db_type(self, connection) + +.. versionadded:: 1.2 + The ``connection`` argument was added to support multiple databases. Returns the database column data type for the :class:`~django.db.models.Field`, -taking into account the current :setting:`DATABASE_ENGINE` setting. +taking into account the connection object, and the settings associated with it. Say you've created a PostgreSQL custom type called ``mytype``. You can use this field with Django by subclassing ``Field`` and implementing the :meth:`db_type` @@ -275,7 +303,7 @@ method, like so:: from django.db import models class MytypeField(models.Field): - def db_type(self): + def db_type(self, connection): return 'mytype' Once you have ``MytypeField``, you can use it in any model, just like any other @@ -290,13 +318,13 @@ If you aim to build a database-agnostic application, you should account for differences in database column types. For example, the date/time column type in PostgreSQL is called ``timestamp``, while the same column in MySQL is called ``datetime``. The simplest way to handle this in a ``db_type()`` method is to -import the Django settings module and check the :setting:`DATABASE_ENGINE` setting. +check the ``connection.settings_dict['ENGINE']`` attribute. + For example:: class MyDateField(models.Field): - def db_type(self): - from django.conf import settings - if settings.DATABASE_ENGINE == 'mysql': + def db_type(self, connection): + if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql': return 'datetime' else: return 'timestamp' @@ -304,7 +332,7 @@ For example:: The :meth:`db_type` method is only called by Django when the framework constructs the ``CREATE TABLE`` statements for your application -- that is, when you first create your tables. It's not called at any other time, so it can -afford to execute slightly complex code, such as the :setting:`DATABASE_ENGINE` +afford to execute slightly complex code, such as the ``connection.settings_dict`` check in the above example. Some database column types accept parameters, such as ``CHAR(25)``, where the @@ -315,7 +343,7 @@ sense to have a ``CharMaxlength25Field``, shown here:: # This is a silly example of hard-coded parameters. class CharMaxlength25Field(models.Field): - def db_type(self): + def db_type(self, connection): return 'char(25)' # In the model: @@ -333,7 +361,7 @@ time -- i.e., when the class is instantiated. To do that, just implement self.max_length = max_length super(BetterCharField, self).__init__(*args, **kwargs) - def db_type(self): + def db_type(self, connection): return 'char(%s)' % self.max_length # In the model: @@ -396,33 +424,67 @@ Python object type we want to store in the model's attribute. called when it is created, you should be using `The SubfieldBase metaclass`_ mentioned earlier. Otherwise :meth:`to_python` won't be called automatically. -Converting Python objects to database values -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Converting Python objects to query values +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. method:: get_prep_value(self, value) -.. method:: get_db_prep_value(self, value) +.. versionadded:: 1.2 + This method was factored out of ``get_db_prep_value()`` -This is the reverse of :meth:`to_python` when working with the database backends -(as opposed to serialization). The ``value`` parameter is the current value of -the model's attribute (a field has no reference to its containing model, so it -cannot retrieve the value itself), and the method should return data in a format -that can be used as a parameter in a query for the database backend. +This is the reverse of :meth:`to_python` when working with the +database backends (as opposed to serialization). The ``value`` +parameter is the current value of the model's attribute (a field has +no reference to its containing model, so it cannot retrieve the value +itself), and the method should return data in a format that has been +prepared for use as a parameter in a query. + +This conversion should *not* include any database-specific +conversions. If database-specific conversions are required, they +should be made in the call to :meth:`get_db_prep_value`. For example:: class HandField(models.Field): # ... - def get_db_prep_value(self, value): + def get_prep_value(self, value): return ''.join([''.join(l) for l in (value.north, value.east, value.south, value.west)]) -.. method:: get_db_prep_save(self, value) +Converting query values to database values +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. method:: get_db_prep_value(self, value, connection, prepared=False) + +.. versionadded:: 1.2 + The ``connection`` and ``prepared`` arguments were added to support multiple databases. + +Some data types (for example, dates) need to be in a specific format +before they can be used by a database backend. +:meth:`get_db_prep_value` is the method where those conversions should +be made. The specific connection that will be used for the query is +passed as the ``connection`` parameter. This allows you to use +backend-specific conversion logic if it is required. + +The ``prepared`` argument describes whether or not the value has +already been passed through :meth:`get_prep_value` conversions. When +``prepared`` is False, the default implementation of +:meth:`get_db_prep_value` will call :meth:`get_prep_value` to do +initial data conversions before performing any database-specific +processing. + +.. method:: get_db_prep_save(self, value, connection) + +.. versionadded:: 1.2 + The ``connection`` argument was added to support multiple databases. -Same as the above, but called when the Field value must be *saved* to the -database. As the default implementation just calls ``get_db_prep_value``, you -shouldn't need to implement this method unless your custom field needs a -special conversion when being saved that is not the same as the conversion used -for normal query parameters (which is implemented by ``get_db_prep_value``). +Same as the above, but called when the Field value must be *saved* to +the database. As the default implementation just calls +``get_db_prep_value``, you shouldn't need to implement this method +unless your custom field needs a special conversion when being saved +that is not the same as the conversion used for normal query +parameters (which is implemented by ``get_db_prep_value``). Preprocessing values before saving ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -450,7 +512,16 @@ correct value. Preparing values for use in database lookups ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. method:: get_db_prep_lookup(self, lookup_type, value) +As with value conversions, preparing a value for database lookups is a +two phase process. + +.. method:: get_prep_lookup(self, lookup_type, value) + +.. versionadded:: 1.2 + This method was factored out of ``get_db_prep_lookup()`` + +:meth:`get_prep_lookup` performs the first phase of lookup preparation, +performing generic data validity checks Prepares the ``value`` for passing to the database when used in a lookup (a ``WHERE`` constraint in SQL). The ``lookup_type`` will be one of the valid @@ -467,34 +538,45 @@ by with handling the lookup types that need special handling for your field and pass the rest to the :meth:`get_db_prep_lookup` method of the parent class. If you needed to implement ``get_db_prep_save()``, you will usually need to -implement ``get_db_prep_lookup()``. If you don't, ``get_db_prep_value`` will be +implement ``get_prep_lookup()``. If you don't, ``get_prep_value`` will be called by the default implementation, to manage ``exact``, ``gt``, ``gte``, ``lt``, ``lte``, ``in`` and ``range`` lookups. You may also want to implement this method to limit the lookup types that could be used with your custom field type. -Note that, for ``range`` and ``in`` lookups, ``get_db_prep_lookup`` will receive +Note that, for ``range`` and ``in`` lookups, ``get_prep_lookup`` will receive a list of objects (presumably of the right type) and will need to convert them to a list of things of the right type for passing to the database. Most of the -time, you can reuse ``get_db_prep_value()``, or at least factor out some common +time, you can reuse ``get_prep_value()``, or at least factor out some common pieces. -For example, the following code implements ``get_db_prep_lookup`` to limit the +For example, the following code implements ``get_prep_lookup`` to limit the accepted lookup types to ``exact`` and ``in``:: class HandField(models.Field): # ... - def get_db_prep_lookup(self, lookup_type, value): + def get_prep_lookup(self, lookup_type, value): # We only handle 'exact' and 'in'. All others are errors. if lookup_type == 'exact': - return [self.get_db_prep_value(value)] + return [self.get_prep_value(value)] elif lookup_type == 'in': - return [self.get_db_prep_value(v) for v in value] + return [self.get_prep_value(v) for v in value] else: raise TypeError('Lookup type %r not supported.' % lookup_type) +.. method:: get_db_prep_lookup(self, lookup_type, value, connection, prepared=False) + +.. versionadded:: 1.2 + The ``connection`` and ``prepared`` arguments were added to support multiple databases. + +Performs any database-specific data conversions required by a lookup. +As with :meth:`get_db_prep_value`, the specific connection that will +be used for the query is passed as the ``connection`` parameter. +The ``prepared`` argument describes whether the value has already been +prepared with :meth:`get_prep_lookup`. + Specifying the form field for a model field ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/howto/custom-template-tags.txt b/docs/howto/custom-template-tags.txt index c6f76772de..774d12dc44 100644 --- a/docs/howto/custom-template-tags.txt +++ b/docs/howto/custom-template-tags.txt @@ -463,6 +463,85 @@ new ``Context`` in this example, the results would have *always* been automatically escaped, which may not be the desired behavior if the template tag is used inside a ``{% autoescape off %}`` block. +.. _template_tag_thread_safety: + +Thread-safety considerations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 1.2 + +Once a node is parsed, its ``render`` method may be called any number of times. +Since Django is sometimes run in multi-threaded environments, a single node may +be simultaneously rendering with different contexts in response to two separate +requests. Therefore, it's important to make sure your template tags are thread +safe. + +To make sure your template tags are thread safe, you should never store state +information on the node itself. For example, Django provides a builtin ``cycle`` +template tag that cycles among a list of given strings each time it's rendered:: + + {% for o in some_list %} + ` + * :ref:`Messages ` * :ref:`Pagination ` * :ref:`Redirects ` * :ref:`Serialization ` diff --git a/docs/internals/contributing.txt b/docs/internals/contributing.txt index 1f1161de43..43909e3828 100644 --- a/docs/internals/contributing.txt +++ b/docs/internals/contributing.txt @@ -426,6 +426,47 @@ translated, here's what to do: .. _Django i18n mailing list: http://groups.google.com/group/django-i18n/ +Django conventions +================== + +Various Django-specific code issues are detailed in this section. + +Use of ``django.conf.settings`` +------------------------------- + +Modules should not in general use settings stored in ``django.conf.settings`` at +the top level (i.e. evaluated when the module is imported). The explanation for +this is as follows: + +Manual configuration of settings (i.e. not relying on the +``DJANGO_SETTINGS_MODULE`` environment variable) is allowed and possible as +follows:: + + from django.conf import settings + + settings.configure({}, SOME_SETTING='foo') + +However, if any setting is accessed before the ``settings.configure`` line, this +will not work. (Internally, ``setttings`` is a ``LazyObject`` which configures +itself automatically when the settings are accessed if it has not already been +configured). + +So, if there is a module containing some code as follows:: + + from django.conf import settings + from django.core.urlresolvers import get_callable + + default_foo_view = get_callable(settings.FOO_VIEW) + +...then importing this module will cause the settings object to be configured. +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``. + Coding style ============ @@ -752,27 +793,53 @@ To run the tests, ``cd`` to the ``tests/`` directory and type: ./runtests.py --settings=path.to.django.settings Yes, the unit tests need a settings module, but only for database connection -info, with the ``DATABASE_ENGINE`` setting. +info. Your :setting:`DATABASES` setting needs to define two databases: + + * A ``default`` database. This database should use the backend that + you want to use for primary testing + + * A database with the alias ``other``. The ``other`` database is + used to establish that queries can be directed to different + databases. As a result, this database can use any backend you + want. It doesn't need to use the same backend as the ``default`` + database (although it can use the same backend if you want to). + +If you're using the SQLite database backend, you need to define +:setting:`ENGINE` for both databases, plus a +:setting:`TEST_NAME` for the ``other`` database. The +following is a minimal settings file that can be used to test SQLite:: + + DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3' + }, + 'other': { + 'ENGINE': 'django.db.backends.sqlite3', + 'TEST_NAME': 'other_db' + } + } + -If you're using the ``sqlite3`` database backend, no further settings are -needed. A temporary database will be created in memory when running the tests. +If you're using another backend, you will need to provide other details for +each database: -If you're using another backend: + * The :setting:`USER` option for each of your databases needs to + specify an existing user account for the database. - * Your :setting:`DATABASE_USER` setting needs to specify an existing user account - for the database engine. + * The :setting:`PASSWORD` option needs to provide the password for + the :setting:`USER` that has been specified. - * The :setting:`DATABASE_NAME` setting must be the name of an existing database to + * The :setting:`NAME` option must be the name of an existing database to which the given user has permission to connect. The unit tests will not touch this database; the test runner creates a new database whose name is - :setting:`DATABASE_NAME` prefixed with ``test_``, and this test database is + :setting:`NAME` prefixed with ``test_``, and this test database is deleted when the tests are finished. This means your user account needs permission to execute ``CREATE DATABASE``. You will also need to ensure that your database uses UTF-8 as the default character set. If your database server doesn't use UTF-8 as a default charset, -you will need to include a value for ``TEST_DATABASE_CHARSET`` in your settings -file. +you will need to include a value for ``TEST_CHARSET`` in the settings +dictionary for the applicable database. If you want to run the full suite of tests, you'll need to install a number of dependencies: @@ -782,7 +849,8 @@ dependencies: * Textile_ * Docutils_ * setuptools_ - * memcached_, plus the either the python-memcached_ or cmemcached_ Python binding + * memcached_, plus the either the python-memcached_ or cmemcached_ + Python binding If you want to test the memcached cache backend, you will also need to define a :setting:`CACHE_BACKEND` setting that points at your memcached instance. @@ -797,7 +865,7 @@ associated tests will be skipped. .. _setuptools: http://pypi.python.org/pypi/setuptools/ .. _memcached: http://www.danga.com/memcached/ .. _python-memcached: http://pypi.python.org/pypi/python-memcached/ -.. _cmemcached: http://pypi.python.org/pypi/cmemcache +.. _cmemcached: http://gijsbert.org/cmemcache/index.html To run a subset of the unit tests, append the names of the test modules to the ``runtests.py`` command line. See the list of directories in @@ -892,9 +960,9 @@ for feature branches: If you want a feature branch in SVN, you'll need to ask in `django-developers`_ for a mentor. -.. _git: http://git.or.cz/ -.. _mercurial: http://www.selenic.com/mercurial/ -.. _bazaar: http://bazaar-vcs.org/ +.. _git: http://git-scm.com/ +.. _mercurial: http://mercurial.selenic.com/ +.. _bazaar: http://bazaar.canonical.com/ .. _django branches: http://code.djangoproject.com/wiki/DjangoBranches Branch rules @@ -1026,7 +1094,7 @@ If you're using Django 0.95 or earlier and installed it using file. Then copy the branch's version of the ``django`` directory into ``site-packages``. -.. _path file: http://docs.python.org/lib/module-site.html +.. _path file: http://docs.python.org/library/site.html Deciding on features ==================== @@ -1092,6 +1160,6 @@ requests for commit access are potential flame-war starters, and will be ignored .. _django-users: http://groups.google.com/group/django-users .. _`#django`: irc://irc.freenode.net/django .. _list of tickets with patches: http://code.djangoproject.com/query?status=new&status=assigned&status=reopened&has_patch=1&order=priority -.. _pep8.py: http://svn.browsershots.org/trunk/devtools/pep8/pep8.py +.. _pep8.py: http://pypi.python.org/pypi/pep8/ .. _i18n branch: http://code.djangoproject.com/browser/django/branches/i18n .. _`tags/releases`: http://code.djangoproject.com/browser/django/tags/releases diff --git a/docs/internals/deprecation.txt b/docs/internals/deprecation.txt index 480b527d6b..1bd58ec0b3 100644 --- a/docs/internals/deprecation.txt +++ b/docs/internals/deprecation.txt @@ -13,6 +13,10 @@ their deprecation, as per the :ref:`Django deprecation policy hooking up admin URLs. This has been deprecated since the 1.1 release. + * Authentication backends need to define the boolean attribute + ``supports_object_permissions``. The old backend style is deprecated + since the 1.2 release. + * 1.4 * ``CsrfResponseMiddleware``. This has been deprecated since the 1.2 release, in favour of the template tag method for inserting the CSRF @@ -26,7 +30,49 @@ their deprecation, as per the :ref:`Django deprecation policy class in favor of a generic E-mail backend API. * The many to many SQL generation functions on the database backends - will be removed. These have been deprecated since the 1.2 release. + will be removed. + + * The ability to use the ``DATABASE_*`` family of top-level settings to + define database connections will be removed. + + * The ability to use shorthand notation to specify a database backend + (i.e., ``sqlite3`` instead of ``django.db.backends.sqlite3``) will be + removed. + + * The ``get_db_prep_save``, ``get_db_prep_value`` and + ``get_db_prep_lookup`` methods on Field were modified in 1.2 to support + multiple databases. In 1.4, the support functions that allow methods + with the old prototype to continue working will be removed. + + * The ``Message`` model (in ``django.contrib.auth``), its related + manager in the ``User`` model (``user.message_set``), and the + associated methods (``user.message_set.create()`` and + ``user.get_and_delete_messages()``), which have + been deprecated since the 1.2 release, will be removed. The + :ref:`messages framework ` should be used + instead. + + * Authentication backends need to support the ``obj`` parameter for + permission checking. The ``supports_object_permissions`` variable + is not checked any longer and can be removed. + + * The ability to specify a callable template loader rather than a + ``Loader`` class will be removed, as will the ``load_template_source`` + functions that are included with the built in template loaders for + backwards compatibility. These have been deprecated since the 1.2 + release. + + * ``django.utils.translation.get_date_formats()`` and + ``django.utils.translation.get_partial_date_formats()``. These + functions are replaced by the new locale aware formatting; use + ``django.utils.formats.get_format()`` to get the appropriate + formats. + + * In ``django.forms.fields``: ``DEFAULT_DATE_INPUT_FORMATS``, + ``DEFAULT_TIME_INPUT_FORMATS`` and + ``DEFAULT_DATETIME_INPUT_FORMATS``. Use + ``django.utils.formats.get_format()`` to get the appropriate + formats. * 2.0 * ``django.views.defaults.shortcut()``. This function has been moved diff --git a/docs/internals/documentation.txt b/docs/internals/documentation.txt index f33af32597..81480abf9a 100644 --- a/docs/internals/documentation.txt +++ b/docs/internals/documentation.txt @@ -10,7 +10,7 @@ based on docutils__. The basic idea is that lightly-formatted plain-text documentation is transformed into HTML, PDF, and any other output format. __ http://sphinx.pocoo.org/ -__ http://docutils.sf.net/ +__ http://docutils.sourceforge.net/ To actually build the documentation locally, you'll currently need to install Sphinx -- ``easy_install Sphinx`` should do the trick. @@ -130,15 +130,6 @@ TODO The work is mostly done, but here's what's left, in rough order of priority. - * Change the "Added/changed in development version" callouts to proper - Sphinx ``.. versionadded::`` or ``.. versionchanged::`` directives. - - * Check for and fix malformed links. Do this by running ``make linkcheck`` - and fix all of the 300+ errors/warnings. - - In particular, look at all the relative links; these need to be - changed to proper references. - * Most of the various ``index.txt`` documents have *very* short or even non-existent intro text. Each of those documents needs a good short intro the content below that point. diff --git a/docs/intro/tutorial01.txt b/docs/intro/tutorial01.txt index afda1f28a2..c2864b8f38 100644 --- a/docs/intro/tutorial01.txt +++ b/docs/intro/tutorial01.txt @@ -102,7 +102,7 @@ These files are: contents" of your Django-powered site. You can read more about URLs in :ref:`topics-http-urls`. -.. _more about packages: http://docs.python.org/tut/node8.html#packages +.. _more about packages: http://docs.python.org/tutorial/modules.html#packages The development server ---------------------- @@ -158,34 +158,40 @@ It worked! Database setup -------------- -Now, edit :file:`settings.py`. It's a normal Python module with module-level -variables representing Django settings. Change these settings to match your -database's connection parameters: +Now, edit :file:`settings.py`. It's a normal Python module with +module-level variables representing Django settings. Change the +following keys in the :setting:`DATABASES` ``'default'`` item to match +your databases connection settings. - * :setting:`DATABASE_ENGINE` -- Either 'postgresql_psycopg2', 'mysql' or - 'sqlite3'. Other backends are :setting:`also available `. + * :setting:`ENGINE` -- Either + ``'django.db.backends.postgresql_psycopg2'``, + ``'django.db.backends.mysql'`` or + ``'django.db.backends.sqlite3'``. Other backends are + :setting:`also available `. - * :setting:`DATABASE_NAME` -- The name of your database. If you're using - SQLite, the database will be a file on your computer; in that case, - ``DATABASE_NAME`` should be the full absolute path, including filename, of - that file. If the file doesn't exist, it will automatically be created - when you synchronize the database for the first time (see below). + * :setting:`NAME` -- The name of your database. If you're using + SQLite, the database will be a file on your computer; in that + case, :setting:`NAME` should be the full absolute path, + including filename, of that file. If the file doesn't exist, it + will automatically be created when you synchronize the database + for the first time (see below). - When specifying the path, always use forward slashes, even on Windows - (e.g. ``C:/homes/user/mysite/sqlite3.db``). + When specifying the path, always use forward slashes, even on + Windows (e.g. ``C:/homes/user/mysite/sqlite3.db``). - * :setting:`DATABASE_USER` -- Your database username (not used for SQLite). + * :setting:`USER` -- Your database username (not used for SQLite). - * :setting:`DATABASE_PASSWORD` -- Your database password (not used for + * :setting:`PASSWORD` -- Your database password (not used for SQLite). - * :setting:`DATABASE_HOST` -- The host your database is on. Leave this as an - empty string if your database server is on the same physical machine (not - used for SQLite). + * :setting:`HOST` -- The host your database is on. Leave this as + an empty string if your database server is on the same physical + machine (not used for SQLite). -If you're new to databases, we recommend simply using SQLite (by setting -:setting:`DATABASE_ENGINE` to ``'sqlite3'``). SQLite is included as part of -Python 2.5 and later, so you won't need to install anything else. +If you're new to databases, we recommend simply using SQLite (by +setting :setting:`ENGINE` to ``'django.db.backends.sqlite3'``). SQLite +is included as part of Python 2.5 and later, so you won't need to +install anything else. .. note:: @@ -361,7 +367,7 @@ Finally, note a relationship is defined, using to a single Poll. Django supports all the common database relationships: many-to-ones, many-to-manys and one-to-ones. -.. _`Python path`: http://docs.python.org/tut/node8.html#SECTION008110000000000000000 +.. _`Python path`: http://docs.python.org/tutorial/modules.html#the-module-search-path Activating models ================= diff --git a/docs/man/django-admin.1 b/docs/man/django-admin.1 index 6407ee5e1d..dff7d0d3da 100644 --- a/docs/man/django-admin.1 +++ b/docs/man/django-admin.1 @@ -28,8 +28,8 @@ Compiles .po files to .mo files for use with builtin gettext support. Creates the table needed to use the SQL cache backend .TP .B dbshell -Runs the command\-line client for the current -.BI DATABASE_ENGINE. +Runs the command\-line client for the specified +.BI database ENGINE. .TP .B diffsettings Displays differences between the current diff --git a/docs/ref/authbackends.txt b/docs/ref/authbackends.txt index 7cb54df7ea..0e98c21b21 100644 --- a/docs/ref/authbackends.txt +++ b/docs/ref/authbackends.txt @@ -1,14 +1,14 @@ .. _ref-authentication-backends: -========================================== -Built-in authentication backends reference -========================================== +======================= +Authentication backends +======================= .. module:: django.contrib.auth.backends :synopsis: Django's built-in authentication backend classes. This document details the authentication backends that come with Django. For -information on how how to use them and how to write your own authentication +information on how to use them and how to write your own authentication backends, see the :ref:`Other authentication sources section ` of the :ref:`User authentication guide `. diff --git a/docs/ref/contrib/admin/index.txt b/docs/ref/contrib/admin/index.txt index 0f746bf01b..97e9c8bcc9 100644 --- a/docs/ref/contrib/admin/index.txt +++ b/docs/ref/contrib/admin/index.txt @@ -172,6 +172,11 @@ The ``field_options`` dictionary can have the following keys: 'fields': (('first_name', 'last_name'), 'address', 'city', 'state'), } + .. versionadded:: 1.2 + + ``fields`` can contain values defined in + :attr:`ModelAdmin.readonly_fields` to be displayed as read-only. + * ``classes`` A list containing extra CSS classes to apply to the fieldset. @@ -210,6 +215,11 @@ the ``django.contrib.flatpages.FlatPage`` model as follows:: In the above example, only the fields 'url', 'title' and 'content' will be displayed, sequentially, in the form. +.. versionadded:: 1.2 + +``fields`` can contain values defined in :attr:`ModelAdmin.readonly_fields` +to be displayed as read-only. + .. admonition:: Note This ``fields`` option should not be confused with the ``fields`` @@ -540,6 +550,21 @@ into a ``Input`` widget for either a ``ForeignKey`` or ``ManyToManyField``:: class ArticleAdmin(admin.ModelAdmin): raw_id_fields = ("newspaper",) +.. attribute:: ModelAdmin.readonly_fields + +.. versionadded:: 1.2 + +By default the admin shows all fields as editable. Any fields in this option +(which should be a ``list`` or ``tuple``) will display its data as-is and +non-editable. This option behaves nearly identical to :attr:`ModelAdmin.list_display`. +Usage is the same, however, when you specify :attr:`ModelAdmin.fields` or +:attr:`ModelAdmin.fieldsets` the read-only fields must be present to be shown +(they are ignored otherwise). + +If ``readonly_fields`` is used without defining explicit ordering through +:attr:`ModelAdmin.fields` or :attr:`ModelAdmin.fieldsets` they will be added +last after all editable fields. + .. attribute:: ModelAdmin.save_as Set ``save_as`` to enable a "save as" feature on admin change forms. @@ -744,6 +769,15 @@ model instance:: instance.save() formset.save_m2m() +.. method:: ModelAdmin.get_readonly_fields(self, request, obj=None) + +.. versionadded:: 1.2 + +The ``get_readonly_fields`` method is given the ``HttpRequest`` and the +``obj`` being edited (or ``None`` on an add form) and is expected to return a +``list`` or ``tuple`` of field names that will be displayed as read-only, as +described above in the :attr:`ModelAdmin.readonly_fields` section. + .. method:: ModelAdmin.get_urls(self) .. versionadded:: 1.1 diff --git a/docs/ref/contrib/flatpages.txt b/docs/ref/contrib/flatpages.txt index 875a1c05e5..f934919412 100644 --- a/docs/ref/contrib/flatpages.txt +++ b/docs/ref/contrib/flatpages.txt @@ -26,7 +26,6 @@ content in a custom template. Here are some examples of flatpages on Django-powered sites: - * http://www.chicagocrime.org/about/ * http://www.everyblock.com/about/ * http://www.lawrence.com/about/contact/ diff --git a/docs/ref/contrib/formtools/form-wizard.txt b/docs/ref/contrib/formtools/form-wizard.txt index 11a2aed091..0449bb9cd0 100644 --- a/docs/ref/contrib/formtools/form-wizard.txt +++ b/docs/ref/contrib/formtools/form-wizard.txt @@ -47,36 +47,34 @@ Usage This application handles as much machinery for you as possible. Generally, you just have to do these things: - 1. Define a number of :mod:`django.forms` - :class:`~django.forms.forms.Form` classes -- one per wizard page. - - 2. Create a :class:`~django.contrib.formtools.wizard.FormWizard` class - that specifies what to do once all of your forms have been submitted - and validated. This also lets you override some of the wizard's behavior. - + 1. Define a number of :class:`~django.forms.Form` classes -- one per wizard + page. + + 2. Create a :class:`FormWizard` class that specifies what to do once all of + your forms have been submitted and validated. This also lets you + override some of the wizard's behavior. + 3. Create some templates that render the forms. You can define a single, generic template to handle every one of the forms, or you can define a specific template for each form. - - 4. Point your URLconf at your - :class:`~django.contrib.formtools.wizard.FormWizard` class. + + 4. Point your URLconf at your :class:`FormWizard` class. Defining ``Form`` classes ========================= -The first step in creating a form wizard is to create the :class:`~django.forms.forms.Form` classes. -These should be standard :mod:`django.forms` -:class:`~django.forms.forms.Form` classes, covered in the -:ref:`forms documentation `. - -These classes can live anywhere in your codebase, but convention is to put them -in a file called :file:`forms.py` in your application. +The first step in creating a form wizard is to create the +:class:`~django.forms.Form` classes. These should be standard +:class:`django.forms.Form` classes, covered in the :ref:`forms documentation +`. These classes can live anywhere in your codebase, but +convention is to put them in a file called :file:`forms.py` in your +application. For example, let's write a "contact form" wizard, where the first page's form collects the sender's e-mail address and subject, and the second page collects the message itself. Here's what the :file:`forms.py` might look like:: - from django import forms + from django import forms class ContactForm1(forms.Form): subject = forms.CharField(max_length=100) @@ -86,27 +84,27 @@ the message itself. Here's what the :file:`forms.py` might look like:: message = forms.CharField(widget=forms.Textarea) **Important limitation:** Because the wizard uses HTML hidden fields to store -data between pages, you may not include a :class:`~django.forms.fields.FileField` +data between pages, you may not include a :class:`~django.forms.FileField` in any form except the last one. Creating a ``FormWizard`` class =============================== -The next step is to create a :class:`~django.contrib.formtools.wizard.FormWizard` -class, which should be a subclass of ``django.contrib.formtools.wizard.FormWizard``. - -As with your :class:`~django.forms.forms.Form` classes, this -:class:`~django.contrib.formtools.wizard.FormWizard` class can live anywhere -in your codebase, but convention is to put it in :file:`forms.py`. +The next step is to create a +:class:`django.contrib.formtools.wizard.FormWizard` subclass. As with your +:class:`~django.forms.Form` classes, this :class:`FormWizard` class can live +anywhere in your codebase, but convention is to put it in :file:`forms.py`. The only requirement on this subclass is that it implement a -:meth:`~django.contrib.formtools.wizard.FormWizard.done()` method, -which specifies what should happen when the data for *every* form is submitted -and validated. This method is passed two arguments: +:meth:`~FormWizard.done()` method. - * ``request`` -- an :class:`~django.http.HttpRequest` object - * ``form_list`` -- a list of :mod:`django.forms` - :class:`~django.forms.forms.Form` classes +.. method:: FormWizard.done + + This method specifies what should happen when the data for *every* form is + submitted and validated. This method is passed two arguments: + + * ``request`` -- an :class:`~django.http.HttpRequest` object + * ``form_list`` -- a list of :class:`~django.forms.Form` classes In this simplistic example, rather than perform any database operation, the method simply renders a template of the validated data:: @@ -133,16 +131,16 @@ example:: return HttpResponseRedirect('/page-to-redirect-to-when-done/') See the section `Advanced FormWizard methods`_ below to learn about more -:class:`~django.contrib.formtools.wizard.FormWizard` hooks. +:class:`FormWizard` hooks. Creating templates for the forms ================================ Next, you'll need to create a template that renders the wizard's forms. By default, every form uses a template called :file:`forms/wizard.html`. (You can -change this template name by overriding -:meth:`~django.contrib.formtools.wizard..get_template()`, which is documented -below. This hook also allows you to use a different template for each form.) +change this template name by overriding :meth:`~FormWizard.get_template()`, +which is documented below. This hook also allows you to use a different +template for each form.) This template expects the following context: @@ -150,24 +148,20 @@ This template expects the following context: * ``step0`` -- The current step (zero-based). * ``step`` -- The current step (one-based). * ``step_count`` -- The total number of steps. - * ``form`` -- The :class:`~django.forms.forms.Form` instance for the - current step (either empty or with errors). + * ``form`` -- The :class:`~django.forms.Form` instance for the current step + (either empty or with errors). * ``previous_fields`` -- A string representing every previous data field, plus hashes for completed forms, all in the form of hidden fields. Note - that you'll need to run this through the - :meth:`~django.template.defaultfilters.safe` template filter, to prevent - auto-escaping, because it's raw HTML. + that you'll need to run this through the :tfilter:`safe` template filter, + to prevent auto-escaping, because it's raw HTML. -It will also be passed any objects in :data:`extra_context`, which is a -dictionary you can specify that contains extra values to add to the context. -You can specify it in two ways: +You can supply extra context to this template in two ways: - * Set the :attr:`~django.contrib.formtools.wizard.FormWizard.extra_context` - attribute on your :class:`~django.contrib.formtools.wizard.FormWizard` - subclass to a dictionary. + * Set the :attr:`~FormWizard.extra_context` attribute on your + :class:`FormWizard` subclass to a dictionary. - * Pass :attr:`~django.contrib.formtools.wizard.FormWizard.extra_context` - as extra parameters in the URLconf. + * Pass a dictionary as a parameter named ``extra_context`` to your wizard's + URL pattern in your URLconf. See :ref:`hooking-wizard-into-urlconf`. Here's a full example template: @@ -190,12 +184,13 @@ Here's a full example template: Note that ``previous_fields``, ``step_field`` and ``step0`` are all required for the wizard to work properly. +.. _hooking-wizard-into-urlconf: + Hooking the wizard into a URLconf ================================= -Finally, give your new :class:`~django.contrib.formtools.wizard.FormWizard` -object a URL in ``urls.py``. The wizard takes a list of your form objects as -arguments:: +Finally, give your new :class:`FormWizard` object a URL in ``urls.py``. The +wizard takes a list of your :class:`~django.forms.Form` objects as arguments:: from django.conf.urls.defaults import * from mysite.testapp.forms import ContactForm1, ContactForm2, ContactWizard @@ -209,19 +204,18 @@ Advanced FormWizard methods .. class:: FormWizard - Aside from the :meth:`~django.contrib.formtools.wizard.FormWizard.done()` - method, :class:`~django.contrib.formtools.wizard.FormWizard` offers a few + Aside from the :meth:`~done()` method, :class:`FormWizard` offers a few advanced method hooks that let you customize how your wizard works. - Some of these methods take an argument ``step``, which is a zero-based counter - representing the current step of the wizard. (E.g., the first form is ``0`` and - the second form is ``1``.) + Some of these methods take an argument ``step``, which is a zero-based + counter representing the current step of the wizard. (E.g., the first form + is ``0`` and the second form is ``1``.) .. method:: FormWizard.prefix_for_step - Given the step, returns a :class:`~django.forms.forms.Form` prefix to - use. By default, this simply uses the step itself. For more, see the - :ref:`form prefix documentation `. + Given the step, returns a form prefix to use. By default, this simply uses + the step itself. For more, see the :ref:`form prefix documentation + `. Default implementation:: @@ -237,15 +231,18 @@ Advanced FormWizard methods def render_hash_failure(self, request, step): return self.render(self.get_form(step), request, step, - context={'wizard_error': 'We apologize, but your form has expired. Please continue filling out the form from this page.'}) + context={'wizard_error': + 'We apologize, but your form has expired. Please' + ' continue filling out the form from this page.'}) .. method:: FormWizard.security_hash - Calculates the security hash for the given request object and :class:`~django.forms.forms.Form` instance. + Calculates the security hash for the given request object and + :class:`~django.forms.Form` instance. By default, this uses an MD5 hash of the form data and your - :setting:`SECRET_KEY` setting. It's rare that somebody would need to override - this. + :setting:`SECRET_KEY` setting. It's rare that somebody would need to + override this. Example:: @@ -254,8 +251,8 @@ Advanced FormWizard methods .. method:: FormWizard.parse_params - A hook for saving state from the request object and ``args`` / ``kwargs`` that - were captured from the URL by your URLconf. + A hook for saving state from the request object and ``args`` / ``kwargs`` + that were captured from the URL by your URLconf. By default, this does nothing. @@ -275,26 +272,23 @@ Advanced FormWizard methods def get_template(self, step): return 'myapp/wizard_%s.html' % step - If :meth:`~FormWizard.get_template` returns a list of strings, then the wizard will use the - template system's :func:`~django.template.loader.select_template()` - function, - :ref:`explained in the template docs `. + If :meth:`~FormWizard.get_template` returns a list of strings, then the + wizard will use the template system's + :func:`~django.template.loader.select_template` function. This means the system will use the first template that exists on the filesystem. For example:: def get_template(self, step): return ['myapp/wizard_%s.html' % step, 'myapp/wizard.html'] - .. _explained in the template docs: ../templates_python/#the-python-api - .. method:: FormWizard.render_template Renders the template for the given step, returning an :class:`~django.http.HttpResponse` object. - Override this method if you want to add a custom context, return a different - MIME type, etc. If you only need to override the template name, use - :meth:`~FormWizard.get_template` instead. + Override this method if you want to add a custom context, return a + different MIME type, etc. If you only need to override the template name, + use :meth:`~FormWizard.get_template` instead. The template will be rendered with the context documented in the "Creating templates for the forms" section above. @@ -302,12 +296,12 @@ Advanced FormWizard methods .. method:: FormWizard.process_step Hook for modifying the wizard's internal state, given a fully validated - :class:`~django.forms.forms.Form` object. The Form is guaranteed to - have clean, valid data. + :class:`~django.forms.Form` object. The Form is guaranteed to have clean, + valid data. - This method should *not* modify any of that data. Rather, it might want to set - ``self.extra_context`` or dynamically alter ``self.form_list``, based on - previously submitted forms. + This method should *not* modify any of that data. Rather, it might want to + set ``self.extra_context`` or dynamically alter ``self.form_list``, based + on previously submitted forms. Note that this method is called every time a page is rendered for *all* submitted steps. diff --git a/docs/ref/contrib/index.txt b/docs/ref/contrib/index.txt index 4f401d6836..2d15c25dfe 100644 --- a/docs/ref/contrib/index.txt +++ b/docs/ref/contrib/index.txt @@ -1,8 +1,8 @@ .. _ref-contrib-index: -============================ -The "django.contrib" add-ons -============================ +==================== +``contrib`` packages +==================== Django aims to follow Python's `"batteries included" philosophy`_. It ships with a variety of extra, optional tools that solve common Web-development @@ -19,7 +19,7 @@ those packages have. ``'django.contrib.admin'``) to your ``INSTALLED_APPS`` setting and re-run ``manage.py syncdb``. -.. _"batteries included" philosophy: http://docs.python.org/tut/node12.html#batteries-included +.. _"batteries included" philosophy: http://docs.python.org/tutorial/stdlib.html#batteries-included .. toctree:: :maxdepth: 1 @@ -34,6 +34,7 @@ those packages have. formtools/index humanize localflavor + messages redirects sitemaps sites @@ -150,6 +151,17 @@ read the source code in django/contrib/markup/templatetags/markup.py. .. _Markdown: http://en.wikipedia.org/wiki/Markdown .. _ReST (ReStructured Text): http://en.wikipedia.org/wiki/ReStructuredText +messages +======== + +.. versionchanged:: 1.2 + The messages framework was added. + +A framework for storing and retrieving temporary cookie- or session-based +messages + +See the :ref:`messages documentation `. + redirects ========= diff --git a/docs/ref/contrib/localflavor.txt b/docs/ref/contrib/localflavor.txt index d63d546efa..660b7c623b 100644 --- a/docs/ref/contrib/localflavor.txt +++ b/docs/ref/contrib/localflavor.txt @@ -61,6 +61,7 @@ Countries currently supported by :mod:`~django.contrib.localflavor` are: * Slovakia_ * `South Africa`_ * Spain_ + * Sweden_ * Switzerland_ * `United Kingdom`_ * `United States of America`_ @@ -101,6 +102,7 @@ Here's an example of how to use them:: .. _Slovakia: `Slovakia (sk)`_ .. _South Africa: `South Africa (za)`_ .. _Spain: `Spain (es)`_ +.. _Sweden: `Sweden (se)`_ .. _Switzerland: `Switzerland (ch)`_ .. _United Kingdom: `United Kingdom (uk)`_ .. _United States of America: `United States of America (us)`_ @@ -166,7 +168,7 @@ Austria (``at``) .. class:: at.forms.ATStateSelect - A ``Select`` widget that uses a list of Austrian states as its choices. + A ``Select`` widget that uses a list of Austrian states as its choices. .. class:: at.forms.ATSocialSecurityNumberField @@ -516,7 +518,7 @@ Romania (``ro``) .. class:: ro.forms.ROIBANField - A form field that validates its input as a Romanian International Bank + A form field that validates its input as a Romanian International Bank Account Number (IBAN). The valid format is ROXX-XXXX-XXXX-XXXX-XXXX-XXXX, with or without hyphens. @@ -596,6 +598,60 @@ Spain (``es``) A ``Select`` widget that uses a list of Spanish regions as its choices. +Sweden (``se``) +=============== + +.. class:: se.forms.SECountySelect + + A Select form widget that uses a list of the Swedish counties (län) as its + choices. + + The cleaned value is the official county code -- see + http://en.wikipedia.org/wiki/Counties_of_Sweden for a list. + +.. class:: se.forms.SEOrganisationNumber + + A form field that validates input as a Swedish organisation number + (organisationsnummer). + + It accepts the same input as SEPersonalIdentityField (for sole + proprietorships (enskild firma). However, co-ordination numbers are not + accepted. + + It also accepts ordinary Swedish organisation numbers with the format + NNNNNNNNNN. + + The return value will be YYYYMMDDXXXX for sole proprietors, and NNNNNNNNNN + for other organisations. + +.. class:: se.forms.SEPersonalIdentityNumber + + A form field that validates input as a Swedish personal identity number + (personnummer). + + The correct formats are YYYYMMDD-XXXX, YYYYMMDDXXXX, YYMMDD-XXXX, + YYMMDDXXXX and YYMMDD+XXXX. + + A \+ indicates that the person is older than 100 years, which will be taken + into consideration when the date is validated. + + The checksum will be calculated and checked. The birth date is checked + to be a valid date. + + By default, co-ordination numbers (samordningsnummer) will be accepted. To + only allow real personal identity numbers, pass the keyword argument + coordination_number=False to the constructor. + + The cleaned value will always have the format YYYYMMDDXXXX. + +.. class:: se.forms.SEPostalCodeField + + A form field that validates input as a Swedish postal code (postnummer). + Valid codes consist of five digits (XXXXX). The number can optionally be + formatted with a space after the third digit (XXX XX). + + The cleaned value will never contain the space. + Switzerland (``ch``) ==================== @@ -627,7 +683,7 @@ United Kingdom (``uk``) A form field that validates input as a UK postcode. The regular expression used is sourced from the schema for British Standard BS7666 - address types at http://www.govtalk.gov.uk/gdsc/schemas/bs7666-v2-0.xsd. + address types at http://www.cabinetoffice.gov.uk/media/291293/bs7666-v2-0.xml. .. class:: uk.forms.UKCountySelect diff --git a/docs/ref/contrib/messages.txt b/docs/ref/contrib/messages.txt new file mode 100644 index 0000000000..20b509388c --- /dev/null +++ b/docs/ref/contrib/messages.txt @@ -0,0 +1,405 @@ +.. _ref-contrib-messages: + +====================== +The messages framework +====================== + +.. module:: django.contrib.messages + :synopsis: Provides cookie- and session-based temporary message storage. + +Django provides full support for cookie- and session-based messaging, for +both anonymous and authenticated clients. The messages framework allows you +to temporarily store messages in one request and retrieve them for display +in a subsequent request (usually the next one). Every message is tagged +with a specific ``level`` that determines its priority (e.g., ``info``, +``warning``, or ``error``). + +.. versionadded:: 1.2 + The messages framework was added. + +Enabling messages +================= + +Messages are implemented through a :ref:`middleware ` +class and corresponding :ref:`context processor `. + +To enable message functionality, do the following: + + * Edit the :setting:`MIDDLEWARE_CLASSES` setting and make sure + it contains ``'django.contrib.messages.middleware.MessageMiddleware'``. + + If you are using a :ref:`storage backend ` that + relies on :ref:`sessions ` (the default), + ``'django.contrib.sessions.middleware.SessionMiddleware'`` must be + enabled and appear before ``MessageMiddleware`` in your + :setting:`MIDDLEWARE_CLASSES`. + + * Edit the :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting and make sure + it contains ``'django.contrib.messages.context_processors.messages'``. + + * Add ``'django.contrib.messages'`` to your :setting:`INSTALLED_APPS` + setting + +The default ``settings.py`` created by ``django-admin.py startproject`` has +``MessageMiddleware`` activated and the ``django.contrib.messages`` app +installed. Also, the default value for :setting:`TEMPLATE_CONTEXT_PROCESSORS` +contains ``'django.contrib.messages.context_processors.messages'``. + +If you don't want to use messages, you can remove the +``MessageMiddleware`` line from :setting:`MIDDLEWARE_CLASSES`, the ``messages`` +context processor from :setting:`TEMPLATE_CONTEXT_PROCESSORS` and +``'django.contrib.messages'`` from your :setting:`INSTALLED_APPS`. + +Configuring the message engine +============================== + +.. _message-storage-backends: + +Storage backends +---------------- + +The messages framework can use different backends to store temporary messages. +To change which backend is being used, add a `MESSAGE_STORAGE`_ to your +settings, referencing the module and class of the storage class. For +example:: + + MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage' + +The value should be the full path of the desired storage class. + +Four storage classes are included: + +``'django.contrib.messages.storage.session.SessionStorage'`` + This class stores all messages inside of the request's session. It + requires Django's ``contrib.session`` application. + +``'django.contrib.messages.storage.cookie.CookieStorage'`` + This class stores the message data in a cookie (signed with a secret hash + to prevent manipulation) to persist notifications across requests. Old + messages are dropped if the cookie data size would exceed 4096 bytes. + +``'django.contrib.messages.storage.fallback.FallbackStorage'`` + This class first uses CookieStorage for all messages, falling back to using + SessionStorage for the messages that could not fit in a single cookie. + + Since it is uses SessionStorage, it also requires Django's + ``contrib.session`` application. + +``'django.contrib.messages.storage.user_messages.LegacyFallbackStorage'`` + This is the default temporary storage class. + + This class extends FallbackStorage and adds compatibility methods to + to retrieve any messages stored in the user Message model by code that + has not yet been updated to use the new API. This storage is temporary + (because it makes use of code that is pending deprecation) and will be + removed in Django 1.4. At that time, the default storage will become + ``django.contrib.messages.storage.fallback.FallbackStorage``. For more + information, see `LegacyFallbackStorage`_ below. + +To write your own storage class, subclass the ``BaseStorage`` class in +``django.contrib.messages.storage.base`` and implement the ``_get`` and +``_store`` methods. + +LegacyFallbackStorage +^^^^^^^^^^^^^^^^^^^^^ + +The ``LegacyFallbackStorage`` is a temporary tool to facilitate the transition +from the deprecated ``user.message_set`` API and will be removed in Django 1.4 +according to Django's standard deprecation policy. For more information, see +the full :ref:`release process documentation `. + +In addition to the functionality in the ``FallbackStorage``, it adds a custom, +read-only storage class that retrieves messages from the user ``Message`` +model. Any messages that were stored in the ``Message`` model (e.g., by code +that has not yet been updated to use the messages framework) will be retrieved +first, followed by those stored in a cookie and in the session, if any. Since +messages stored in the ``Message`` model do not have a concept of levels, they +will be assigned the ``INFO`` level by default. + +Message levels +-------------- + +The messages framework is based on a configurable level architecture similar +to that of the Python logging module. Message levels allow you to group +messages by type so they can be filtered or displayed differently in views and +templates. + +The built-in levels (which can be imported from ``django.contrib.messages`` +directly) are: + +=========== ======== +Constant Purpose +=========== ======== +``DEBUG`` Development-related messages that will be ignored (or removed) in a production deployment +``INFO`` Informational messages for the user +``SUCCESS`` An action was successful, e.g. "Your profile was updated successfully" +``WARNING`` A failure did not occur but may be imminent +``ERROR`` An action was **not** successful or some other failure occurred +=========== ======== + +The `MESSAGE_LEVEL`_ setting can be used to change the minimum recorded +level. Attempts to add messages of a level less than this will be ignored. + +Message tags +------------ + +Message tags are a string representation of the message level plus any +extra tags that were added directly in the view (see +`Adding extra message tags`_ below for more details). Tags are stored in a +string and are separated by spaces. Typically, message tags +are used as CSS classes to customize message style based on message type. By +default, each level has a single tag that's a lowercase version of its own +constant: + +============== =========== +Level Constant Tag +============== =========== +``DEBUG`` ``debug`` +``INFO`` ``info`` +``SUCCESS`` ``success`` +``WARNING`` ``warning`` +``ERROR`` ``error`` +============== =========== + +To change the default tags for a message level (either built-in or custom), +set the `MESSAGE_TAGS`_ setting to a dictionary containing the levels +you wish to change. As this extends the default tags, you only need to provide +tags for the levels you wish to override:: + + from django.contrib.messages import constants as messages + MESSAGE_TAGS = { + messages.INFO: '', + 50: 'critical', + } + +Using messages in views and templates +===================================== + +Adding a message +---------------- + +To add a message, call:: + + from django.contrib import messages + messages.add_message(request, messages.INFO, 'Hello world.') + +Some shortcut methods provide a standard way to add messages with commonly +used tags (which are usually represented as HTML classes for the message):: + + messages.debug(request, '%s SQL statements were executed.' % count) + messages.info(request, 'Three credits remain in your account.') + messages.success(request, 'Profile details updated.') + messages.warning(request, 'Your account expires in three days.') + messages.error(request, 'Document deleted.') + +Displaying messages +------------------- + +In your template, use something like:: + + {% if messages %} +
    + {% for message in messages %} + {{ message }} + {% endfor %} +
+ {% endif %} + +If you're using the context processor, your template should be rendered with a +``RequestContext``. Otherwise, ensure ``messages`` is available to +the template context. + +Creating custom message levels +------------------------------ + +Messages levels are nothing more than integers, so you can define your own +level constants and use them to create more customized user feedback, e.g.:: + + CRITICAL = 50 + + def my_view(request): + messages.add_message(request, CRITICAL, 'A serious error occurred.') + +When creating custom message levels you should be careful to avoid overloading +existing levels. The values for the built-in levels are: + +.. _message-level-constants: + +============== ===== +Level Constant Value +============== ===== +``DEBUG`` 10 +``INFO`` 20 +``SUCCESS`` 25 +``WARNING`` 30 +``ERROR`` 40 +============== ===== + +If you need to identify the custom levels in your HTML or CSS, you need to +provide a mapping via the `MESSAGE_TAGS`_ setting. + +.. note:: + If you are creating a reusable application, it is recommended to use + only the built-in `message levels`_ and not rely on any custom levels. + +Changing the minimum recorded level per-request +----------------------------------------------- + +The minimum recorded level can be set per request by changing the ``level`` +attribute of the messages storage instance:: + + from django.contrib import messages + + # Change the messages level to ensure the debug message is added. + messages.get_messages(request).level = messages.DEBUG + messages.debug(request, 'Test message...') + + # In another request, record only messages with a level of WARNING and higher + messages.get_messages(request).level = messages.WARNING + messages.success(request, 'Your profile was updated.') # ignored + messages.warning(request, 'Your account is about to expire.') # recorded + + # Set the messages level back to default. + messages.get_messages(request).level = None + +For more information on how the minimum recorded level functions, see +`Message levels`_ above. + +Adding extra message tags +------------------------- + +For more direct control over message tags, you can optionally provide a string +containing extra tags to any of the add methods:: + + messages.add_message(request, messages.INFO, 'Over 9000!', + extra_tags='dragonball') + messages.error(request, 'Email box full', extra_tags='email') + +Extra tags are added before the default tag for that level and are space +separated. + +Failing silently when the message framework is disabled +------------------------------------------------------- + +If you're writing a reusable app (or other piece of code) and want to include +messaging functionality, but don't want to require your users to enable it +if they don't want to, you may pass an additional keyword argument +``fail_silently=True`` to any of the ``add_message`` family of methods. For +example:: + + messages.add_message(request, messages.SUCCESS, 'Profile details updated.', + fail_silently=True) + messages.info(request, 'Hello world.', fail_silently=True) + +Internally, Django uses this functionality in the create, update, and delete +:ref:`generic views ` so that they work even if the +message framework is disabled. + +.. note:: + Setting ``fail_silently=True`` only hides the ``MessageFailure`` that would + otherwise occur when the messages framework disabled and one attempts to + use one of the ``add_message`` family of methods. It does not hide failures + that may occur for other reasons. + +Expiration of messages +====================== + +The messages are marked to be cleared when the storage instance is iterated +(and cleared when the response is processed). + +To avoid the messages being cleared, you can set the messages storage to +``False`` after iterating:: + + storage = messages.get_messages(request) + for message in storage: + do_something_with(message) + storage.used = False + +Behavior of parallel requests +============================= + +Due to the way cookies (and hence sessions) work, **the behavior of any +backends that make use of cookies or sessions is undefined when the same +client makes multiple requests that set or get messages in parallel**. For +example, if a client initiates a request that creates a message in one window +(or tab) and then another that fetches any uniterated messages in another +window, before the first window redirects, the message may appear in the +second window instead of the first window where it may be expected. + +In short, when multiple simultaneous requests from the same client are +involved, messages are not guaranteed to be delivered to the same window that +created them nor, in some cases, at all. Note that this is typically not a +problem in most applications and will become a non-issue in HTML5, where each +window/tab will have its own browsing context. + +Settings +======== + +A few :ref:`Django settings ` give you control over message +behavior: + +MESSAGE_LEVEL +------------- + +Default: ``messages.INFO`` + +This sets the minimum message that will be saved in the message storage. See +`Message levels`_ above for more details. + +.. admonition:: Important + + If you override ``MESSAGE_LEVEL`` in your settings file and rely on any of + the built-in constants, you must import the constants module directly to + avoid the potential for circular imports, e.g.:: + + from django.contrib.messages import constants as message_constants + MESSAGE_LEVEL = message_constants.DEBUG + + If desired, you may specify the numeric values for the constants directly + according to the values in the above :ref:`constants table + `. + +MESSAGE_STORAGE +--------------- + +Default: ``'django.contrib.messages.storage.user_messages.LegacyFallbackStorage'`` + +Controls where Django stores message data. Valid values are: + + * ``'django.contrib.messages.storage.fallback.FallbackStorage'`` + * ``'django.contrib.messages.storage.session.SessionStorage'`` + * ``'django.contrib.messages.storage.cookie.CookieStorage'`` + * ``'django.contrib.messages.storage.user_messages.LegacyFallbackStorage'`` + +See `Storage backends`_ for more details. + +MESSAGE_TAGS +------------ + +Default:: + + {messages.DEBUG: 'debug', + messages.INFO: 'info', + messages.SUCCESS: 'success', + messages.WARNING: 'warning', + messages.ERROR: 'error',} + +This sets the mapping of message level to message tag, which is typically +rendered as a CSS class in HTML. If you specify a value, it will extend +the default. This means you only have to specify those values which you need +to override. See `Displaying messages`_ above for more details. + +.. admonition:: Important + + If you override ``MESSAGE_TAGS`` in your settings file and rely on any of + the built-in constants, you must import the ``constants`` module directly to + avoid the potential for circular imports, e.g.:: + + from django.contrib.messages import constants as message_constants + MESSAGE_TAGS = {message_constants.INFO: ''} + + If desired, you may specify the numeric values for the constants directly + according to the values in the above :ref:`constants table + `. + +.. _Django settings: ../settings/ diff --git a/docs/ref/contrib/sitemaps.txt b/docs/ref/contrib/sitemaps.txt index e7cd224e3e..82a4d15cf4 100644 --- a/docs/ref/contrib/sitemaps.txt +++ b/docs/ref/contrib/sitemaps.txt @@ -36,7 +36,7 @@ To install the sitemap app, follow these steps: 1. Add ``'django.contrib.sitemaps'`` to your :setting:`INSTALLED_APPS` setting. - 2. Make sure ``'django.template.loaders.app_directories.load_template_source'`` + 2. Make sure ``'django.template.loaders.app_directories.Loader'`` is in your :setting:`TEMPLATE_LOADERS` setting. It's in there by default, so you'll only need to change this if you've changed that setting. @@ -45,7 +45,7 @@ To install the sitemap app, follow these steps: (Note: The sitemap application doesn't install any database tables. The only reason it needs to go into :setting:`INSTALLED_APPS` is so that the -:func:`~django.template.loaders.app_directories.load_template_source` template +:func:`~django.template.loaders.app_directories.Loader` template loader can find the default templates.) Initialization diff --git a/docs/ref/contrib/syndication.txt b/docs/ref/contrib/syndication.txt index cb9c22b8bd..c27666303c 100644 --- a/docs/ref/contrib/syndication.txt +++ b/docs/ref/contrib/syndication.txt @@ -940,7 +940,7 @@ attributes. Thus, you can subclass the appropriate feed generator class (``Atom1Feed`` or ``Rss201rev2Feed``) and extend these callbacks. They are: .. _georss: http://georss.org/ -.. _itunes podcast format: http://www.apple.com/itunes/store/podcaststechspecs.html +.. _itunes podcast format: http://www.apple.com/itunes/podcasts/specs.html ``SyndicationFeed.root_attributes(self, )`` Return a ``dict`` of attributes to add to the root feed element diff --git a/docs/ref/databases.txt b/docs/ref/databases.txt index fc58dbaf47..df8c64c97e 100644 --- a/docs/ref/databases.txt +++ b/docs/ref/databases.txt @@ -1,8 +1,8 @@ .. _ref-databases: -=============================== -Notes about supported databases -=============================== +========= +Databases +========= Django attempts to support as many features as possible on all database backends. However, not all database backends are alike, and we've had to make @@ -44,18 +44,20 @@ Autocommit mode .. versionadded:: 1.1 -If your application is particularly read-heavy and doesn't make many database -writes, the overhead of a constantly open transaction can sometimes be -noticeable. For those situations, if you're using the ``postgresql_psycopg2`` -backend, you can configure Django to use *"autocommit"* behavior for the -connection, meaning that each database operation will normally be in its own -transaction, rather than having the transaction extend over multiple -operations. In this case, you can still manually start a transaction if you're -doing something that requires consistency across multiple database operations. -The autocommit behavior is enabled by setting the ``autocommit`` key in the -:setting:`DATABASE_OPTIONS` setting:: - - DATABASE_OPTIONS = { +If your application is particularly read-heavy and doesn't make many +database writes, the overhead of a constantly open transaction can +sometimes be noticeable. For those situations, if you're using the +``postgresql_psycopg2`` backend, you can configure Django to use +*"autocommit"* behavior for the connection, meaning that each database +operation will normally be in its own transaction, rather than having +the transaction extend over multiple operations. In this case, you can +still manually start a transaction if you're doing something that +requires consistency across multiple database operations. The +autocommit behavior is enabled by setting the ``autocommit`` key in +the :setting:`OPTIONS` part of your database configuration in +:setting:`DATABASES`:: + + OPTIONS = { "autocommit": True, } @@ -67,11 +69,11 @@ objects are changed or none of them are. .. admonition:: This is database-level autocommit This functionality is not the same as the - :ref:`topics-db-transactions-autocommit` decorator. That decorator is a - Django-level implementation that commits automatically after data changing - operations. The feature enabled using the :setting:`DATABASE_OPTIONS` - settings provides autocommit behavior at the database adapter level. It - commits after *every* operation. + :ref:`topics-db-transactions-autocommit` decorator. That decorator + is a Django-level implementation that commits automatically after + data changing operations. The feature enabled using the + :setting:`OPTIONS` option provides autocommit behavior at the + database adapter level. It commits after *every* operation. If you are using this feature and performing an operation akin to delete or updating that requires multiple operations, you are strongly recommended to @@ -80,6 +82,21 @@ You should also audit your existing code for any instances of this behavior before enabling this feature. It's faster, but it provides less automatic protection for multi-call operations. +Indexes for ``varchar`` and ``text`` columns +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. versionadded:: 1.1.2 + +When specifying ``db_index=True`` on your model fields, Django typically +outputs a single ``CREATE INDEX`` statement. However, if the database type +for the field is either ``varchar`` or ``text`` (e.g., used by ``CharField``, +``FileField``, and ``TextField``), then Django will create +an additional index that uses an appropriate `PostgreSQL operator class`_ +for the column. The extra index is necessary to correctly perfrom +lookups that use the ``LIKE`` operator in their SQL, as is done with the +``contains`` and ``startswith`` lookup types. + +.. _PostgreSQL operator class: http://www.postgresql.org/docs/8.4/static/indexes-opclass.html + .. _mysql-notes: MySQL notes @@ -234,29 +251,33 @@ Refer to the :ref:`settings documentation `. Connection settings are used in this order: - 1. :setting:`DATABASE_OPTIONS`. - 2. :setting:`DATABASE_NAME`, :setting:`DATABASE_USER`, - :setting:`DATABASE_PASSWORD`, :setting:`DATABASE_HOST`, - :setting:`DATABASE_PORT` + 1. :setting:`OPTIONS`. + 2. :setting:`NAME`, :setting:`USER`, :setting:`PASSWORD`, + :setting:`HOST`, :setting:`PORT` 3. MySQL option files. -In other words, if you set the name of the database in ``DATABASE_OPTIONS``, -this will take precedence over ``DATABASE_NAME``, which would override +In other words, if you set the name of the database in ``OPTIONS``, +this will take precedence over ``NAME``, which would override anything in a `MySQL option file`_. Here's a sample configuration which uses a MySQL option file:: # settings.py - DATABASE_ENGINE = "mysql" - DATABASE_OPTIONS = { - 'read_default_file': '/path/to/my.cnf', + DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.mysql', + 'OPTIONS': { + 'read_default_file': '/path/to/my.cnf', + }, + } } + # my.cnf [client] - database = DATABASE_NAME - user = DATABASE_USER - password = DATABASE_PASSWORD + database = NAME + user = USER + password = PASSWORD default-character-set = utf8 Several other MySQLdb connection options may be useful, such as ``ssl``, @@ -287,7 +308,7 @@ storage engine, you have a couple of options. * Another option is to use the ``init_command`` option for MySQLdb prior to creating your tables:: - DATABASE_OPTIONS = { + OPTIONS = { "init_command": "SET storage_engine=INNODB", } @@ -452,7 +473,7 @@ If you're getting this error, you can solve it by: * Increase the default timeout value by setting the ``timeout`` database option option:: - DATABASE_OPTIONS = { + OPTIONS = { # ... "timeout": 20, # ... @@ -505,25 +526,34 @@ Connecting to the database Your Django settings.py file should look something like this for Oracle:: - DATABASE_ENGINE = 'oracle' - DATABASE_NAME = 'xe' - DATABASE_USER = 'a_user' - DATABASE_PASSWORD = 'a_password' - DATABASE_HOST = '' - DATABASE_PORT = '' + DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.oracle', + 'NAME': 'xe', + 'USER': 'a_user', + 'PASSWORD': 'a_password', + 'HOST': '', + 'PORT': '' , + } + } + If you don't use a ``tnsnames.ora`` file or a similar naming method that recognizes the SID ("xe" in this example), then fill in both -:setting:`DATABASE_HOST` and :setting:`DATABASE_PORT` like so:: - - DATABASE_ENGINE = 'oracle' - DATABASE_NAME = 'xe' - DATABASE_USER = 'a_user' - DATABASE_PASSWORD = 'a_password' - DATABASE_HOST = 'dbprod01ned.mycompany.com' - DATABASE_PORT = '1540' +``HOST`` and ``PORT`` like so:: + + DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.oracle', + 'NAME': 'xe', + 'USER': 'a_user', + 'PASSWORD': 'a_password', + 'HOST': 'dbprod01ned.mycompany.com', + 'PORT': '1540', + } + } -You should supply both :setting:`DATABASE_HOST` and :setting:`DATABASE_PORT`, or leave both +You should supply both ``HOST`` and ``PORT``, or leave both as empty strings. Tablespace options diff --git a/docs/ref/django-admin.txt b/docs/ref/django-admin.txt index 80e368286e..2cd879423c 100644 --- a/docs/ref/django-admin.txt +++ b/docs/ref/django-admin.txt @@ -121,6 +121,11 @@ createcachetable Creates a cache table named ``tablename`` for use with the database cache backend. See :ref:`topics-cache` for more information. +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database +onto which the cachetable will be installed. + createsuperuser --------------- @@ -155,8 +160,8 @@ dbshell .. django-admin:: dbshell Runs the command-line client for the database engine specified in your -``DATABASE_ENGINE`` setting, with the connection parameters specified in your -``DATABASE_USER``, ``DATABASE_PASSWORD``, etc., settings. +``ENGINE`` setting, with the connection parameters specified in your +``USER``, ``PASSWORD``, etc., settings. * For PostgreSQL, this runs the ``psql`` command-line client. * For MySQL, this runs the ``mysql`` command-line client. @@ -167,6 +172,12 @@ the program name (``psql``, ``mysql``, ``sqlite3``) will find the program in the right place. There's no way to specify the location of the program manually. +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database +onto which to open a shell. + + diffsettings ------------ @@ -199,21 +210,6 @@ records to dump. If you're using a :ref:`custom manager ` as the default manager and it filters some of the available records, not all of the objects will be dumped. -.. django-admin-option:: --exclude - -.. versionadded:: 1.0 - -Exclude a specific application from the applications whose contents is -output. For example, to specifically exclude the `auth` application from -the output, you would call:: - - django-admin.py dumpdata --exclude=auth - -If you want to exclude multiple applications, use multiple ``--exclude`` -directives:: - - django-admin.py dumpdata --exclude=auth --exclude=contenttypes - .. django-admin-option:: --format By default, ``dumpdata`` will format its output in JSON, but you can use the @@ -226,6 +222,11 @@ By default, ``dumpdata`` will output all data on a single line. This isn't easy for humans to read, so you can use the ``--indent`` option to pretty-print the output with a number of indentation spaces. +.. versionadded:: 1.0 + +The :djadminopt:`--exclude` option may be provided to prevent specific +applications from being dumped. + .. versionadded:: 1.1 In addition to specifying application names, you can provide a list of @@ -234,6 +235,21 @@ name to ``dumpdata``, the dumped output will be restricted to that model, rather than the entire application. You can also mix application names and model names. +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database +onto which the data will be loaded. + +.. django-admin-option:: --natural + +.. versionadded:: 1.2 + +Use :ref:`natural keys ` to represent +any foreign key and many-to-many relationship with a model that provides +a natural key definition. If you are dumping ``contrib.auth`` ``Permission`` +objects or ``contrib.contenttypes`` ``ContentType`` objects, you should +probably be using this flag. + flush ----- @@ -247,13 +263,19 @@ fixture will be re-installed. The :djadminopt:`--noinput` option may be provided to suppress all user prompts. +.. versionadded:: 1.2 + +The :djadminopt:`--database` option may be used to specify the database +to flush. + + inspectdb --------- .. django-admin:: inspectdb Introspects the database tables in the database pointed-to by the -``DATABASE_NAME`` setting and outputs a Django model module (a ``models.py`` +``NAME`` setting and outputs a Django model module (a ``models.py`` file) to standard output. Use this if you have a legacy database with which you'd like to use Django. @@ -290,6 +312,12 @@ needed. ``inspectdb`` works with PostgreSQL, MySQL and SQLite. Foreign-key detection only works in PostgreSQL and with certain types of MySQL tables. +.. versionadded:: 1.2 + +The :djadminopt:`--database` option may be used to specify the +database to introspect. + + loaddata ------------------------------ @@ -297,6 +325,11 @@ loaddata Searches for and loads the contents of the named fixture into the database. +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database +onto which the data will be loaded. + What's a "fixture"? ~~~~~~~~~~~~~~~~~~~ @@ -378,6 +411,37 @@ installation will be aborted, and any data installed in the call to references in your data files - MySQL doesn't provide a mechanism to defer checking of row constraints until a transaction is committed. +Database-specific fixtures +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you are in a multi-database setup, you may have fixture data that +you want to load onto one database, but not onto another. In this +situation, you can add database identifier into . If your +:setting:`DATABASES` setting has a 'master' database defined, you can +define the fixture ``mydata.master.json`` or +``mydata.master.json.gz``. This fixture will only be loaded if you +have specified that you want to load data onto the ``master`` +database. + +Excluding applications from loading +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 1.2 + +The :djadminopt:`--exclude` option may be provided to prevent specific +applications from being loaded. + +For example, if you wanted to exclude models from ``django.contrib.auth`` +from being loaded into your database, you would call:: + + django-admin.py loaddata mydata.json --exclude auth + +This will look for for a JSON fixture called ``mydata`` in all the +usual locations - including the ``fixtures`` directory of the +``django.contrib.auth`` application. However, any fixture object that +identifies itself as belonging to the ``auth`` application (e.g., +instance of ``auth.User``) would be ignored by loaddata. + makemessages ------------ @@ -439,6 +503,11 @@ Executes the equivalent of ``sqlreset`` for the given app name(s). The :djadminopt:`--noinput` option may be provided to suppress all user prompts. +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the alias +of the database to reset. + runfcgi [options] ----------------- @@ -556,6 +625,11 @@ sql Prints the CREATE TABLE SQL statements for the given app name(s). +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database for +which to print the SQL. + sqlall ---------------------------- @@ -566,6 +640,11 @@ Prints the CREATE TABLE and initial-data SQL statements for the given app name(s Refer to the description of ``sqlcustom`` for an explanation of how to specify initial data. +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database for +which to print the SQL. + sqlclear ------------------------------ @@ -573,6 +652,11 @@ sqlclear Prints the DROP TABLE SQL statements for the given app name(s). +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database for +which to print the SQL. + sqlcustom ------------------------------- @@ -594,6 +678,11 @@ table modifications, or insert any SQL functions into the database. Note that the order in which the SQL files are processed is undefined. +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database for +which to print the SQL. + sqlflush -------- @@ -602,6 +691,11 @@ sqlflush Prints the SQL statements that would be executed for the :djadmin:`flush` command. +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database for +which to print the SQL. + sqlindexes -------------------------------- @@ -609,6 +703,11 @@ sqlindexes Prints the CREATE INDEX SQL statements for the given app name(s). +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database for +which to print the SQL. + sqlreset ------------------------------ @@ -616,6 +715,11 @@ sqlreset Prints the DROP TABLE SQL, then the CREATE TABLE SQL, for the given app name(s). +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database for +which to print the SQL. + sqlsequencereset -------------------------------------- @@ -629,6 +733,11 @@ number for automatically incremented fields. Use this command to generate SQL which will fix cases where a sequence is out of sync with its automatically incremented field data. +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database for +which to print the SQL. + startapp ------------------ @@ -685,9 +794,16 @@ with an appropriate extension (e.g. ``json`` or ``xml``). See the documentation for ``loaddata`` for details on the specification of fixture data files. +--noinput +~~~~~~~~~ The :djadminopt:`--noinput` option may be provided to suppress all user prompts. +.. versionadded:: 1.2 + +The :djadminopt:`--database` option can be used to specify the database to +synchronize. + test ----------------------------- @@ -696,6 +812,14 @@ test Runs tests for all installed models. See :ref:`topics-testing` for more information. +--failfast +~~~~~~~~~~ + +.. versionadded:: 1.2 + +Use the ``--failfast`` option to stop running tests and report the failure +immediately after a test fails. + testserver -------------------------------- @@ -829,6 +953,30 @@ Common options The following options are not available on every commands, but they are common to a number of commands. +.. django-admin-option:: --database + +.. versionadded:: 1.2 + +Used to specify the database on which a command will operate. If not +specified, this option will default to an alias of ``default``. + +For example, to dump data from the database with the alias ``master``:: + + django-admin.py dumpdata --database=master + +.. django-admin-option:: --exclude + +Exclude a specific application from the applications whose contents is +output. For example, to specifically exclude the `auth` application from +the output of dumpdata, you would call:: + + django-admin.py dumpdata --exclude=auth + +If you want to exclude multiple applications, use multiple ``--exclude`` +directives:: + + django-admin.py dumpdata --exclude=auth --exclude=contenttypes + .. django-admin-option:: --locale Use the ``--locale`` or ``-l`` option to specify the locale to process. @@ -843,13 +991,92 @@ being executed as an unattended, automated script. Extra niceties ============== +.. _syntax-coloring: + Syntax coloring --------------- -The ``django-admin.py`` / ``manage.py`` commands that output SQL to standard -output will use pretty color-coded output if your terminal supports -ANSI-colored output. It won't use the color codes if you're piping the -command's output to another program. +The ``django-admin.py`` / ``manage.py`` commands that output SQL to +standard output will use pretty color-coded output if your terminal +supports ANSI-colored output. It won't use the color codes if you're +piping the command's output to another program. + +The colors used for syntax highlighting can be customized. Django +ships with three color palettes: + + * ``dark``, suited to terminals that show white text on a black + background. This is the default palette. + + * ``light``, suited to terminals that show white text on a black + background. + + * ``nocolor``, which disables syntax highlighting. + +You select a palette by setting a ``DJANGO_COLORS`` environment +variable to specify the palette you want to use. For example, to +specify the ``light`` palette under a Unix or OS/X BASH shell, you +would run the following at a command prompt:: + + export DJANGO_COLORS="light" + +You can also customize the colors that are used. Django specifies a +number of roles in which color is used: + + * ``error`` - A major error. + * ``notice`` - A minor error. + * ``sql_field`` - The name of a model field in SQL. + * ``sql_coltype`` - The type of a model field in SQL. + * ``sql_keyword`` - A SQL keyword. + * ``sql_table`` - The name of a model in SQL. + +Each of these roles can be assigned a specific foreground and +background color, from the following list: + + * ``black`` + * ``red`` + * ``green`` + * ``yellow`` + * ``blue`` + * ``magenta`` + * ``cyan`` + * ``white`` + +Each of these colors can then be modified by using the following +display options: + + * ``bold`` + * ``underscore`` + * ``blink`` + * ``reverse`` + * ``conceal`` + +A color specification follows one of the the following patterns: + + * ``role=fg`` + * ``role=fg/bg`` + * ``role=fg,option,option`` + * ``role=fg/bg,option,option`` + +where ``role`` is the name of a valid color role, ``fg`` is the +foreground color, ``bg`` is the background color and each ``option`` +is one of the color modifying options. Multiple color specifications +are then separated by semicolon. For example:: + + export DJANGO_COLORS="error=yellow/blue,blink;notice=magenta" + +would specify that errors be displayed using blinking yellow on blue, +and notices displayed using magenta. All other color roles would be +left uncolored. + +Colors can also be specified by extending a base palette. If you put +a palette name in a color specification, all the colors implied by that +palette will be loaded. So:: + + export DJANGO_COLORS="light;error=yellow/blue,blink;notice=magenta" + +would specify the use of all the colors in the light color palette, +*except* for the colors for errors and notices which would be +overridden as specified. Bash completion --------------- diff --git a/docs/ref/files/index.txt b/docs/ref/files/index.txt index bdc327b2d7..1d59d5fa23 100644 --- a/docs/ref/files/index.txt +++ b/docs/ref/files/index.txt @@ -1,13 +1,14 @@ .. _ref-files-index: -File handling reference -======================= +============= +File handling +============= .. module:: django.core.files :synopsis: File handling and storage .. toctree:: :maxdepth: 1 - + file - storage \ No newline at end of file + storage diff --git a/docs/ref/forms/api.txt b/docs/ref/forms/api.txt index 7a2341f69b..c313eb5c6b 100644 --- a/docs/ref/forms/api.txt +++ b/docs/ref/forms/api.txt @@ -4,6 +4,8 @@ The Forms API ============= +.. module:: django.forms.forms + .. currentmodule:: django.forms .. admonition:: About this document @@ -25,6 +27,8 @@ A :class:`Form` instance is either **bound** to a set of data, or **unbound**. * If it's **unbound**, it cannot do validation (because there's no data to validate!), but it can still render the blank form as HTML. +.. class:: Form + To create an unbound :class:`Form` instance, simply instantiate the class:: >>> f = ContactForm() @@ -134,24 +138,25 @@ Dynamic initial values .. attribute:: Form.initial -Use ``initial`` to declare the initial value of form fields at runtime. For -example, you might want to fill in a ``username`` field with the username of the -current session. +Use :attr:`~Form.initial` to declare the initial value of form fields at +runtime. For example, you might want to fill in a ``username`` field with the +username of the current session. -To accomplish this, use the ``initial`` argument to a ``Form``. This argument, -if given, should be a dictionary mapping field names to initial values. Only -include the fields for which you're specifying an initial value; it's not -necessary to include every field in your form. For example:: +To accomplish this, use the :attr:`~Form.initial` argument to a :class:`Form`. +This argument, if given, should be a dictionary mapping field names to initial +values. Only include the fields for which you're specifying an initial value; +it's not necessary to include every field in your form. For example:: >>> f = ContactForm(initial={'subject': 'Hi there!'}) These values are only displayed for unbound forms, and they're not used as fallback values if a particular value isn't provided. -Note that if a ``Field`` defines ``initial`` *and* you include ``initial`` when -instantiating the ``Form``, then the latter ``initial`` will have precedence. In -this example, ``initial`` is provided both at the field level and at the form -instance level, and the latter gets precedence:: +Note that if a :class:`~django.forms.fields.Field` defines +:attr:`~Form.initial` *and* you include ``initial`` when instantiating the +``Form``, then the latter ``initial`` will have precedence. In this example, +``initial`` is provided both at the field level and at the form instance level, +and the latter gets precedence:: >>> class CommentForm(forms.Form): ... name = forms.CharField(initial='class') @@ -166,20 +171,21 @@ instance level, and the latter gets precedence:: Accessing "clean" data ---------------------- -Each ``Field`` in a ``Form`` class is responsible not only for validating data, -but also for "cleaning" it -- normalizing it to a consistent format. This is a -nice feature, because it allows data for a particular field to be input in +.. attribute:: Form.cleaned_data + +Each field in a :class:`Form` class is responsible not only for validating +data, but also for "cleaning" it -- normalizing it to a consistent format. This +is a nice feature, because it allows data for a particular field to be input in a variety of ways, always resulting in consistent output. -For example, ``DateField`` normalizes input into a Python ``datetime.date`` -object. Regardless of whether you pass it a string in the format -``'1994-07-15'``, a ``datetime.date`` object or a number of other formats, -``DateField`` will always normalize it to a ``datetime.date`` object as long as -it's valid. +For example, :class:`~django.forms.DateField` normalizes input into a +Python ``datetime.date`` object. Regardless of whether you pass it a string in +the format ``'1994-07-15'``, a ``datetime.date`` object, or a number of other +formats, ``DateField`` will always normalize it to a ``datetime.date`` object +as long as it's valid. -Once you've created a ``Form`` instance with a set of data and validated it, -you can access the clean data via the ``cleaned_data`` attribute of the ``Form`` -object:: +Once you've created a :class:`~Form` instance with a set of data and validated +it, you can access the clean data via its ``cleaned_data`` attribute:: >>> data = {'subject': 'hello', ... 'message': 'Hi there', @@ -322,49 +328,86 @@ a form object, and each rendering method returns a Unicode object. ``as_p()`` ~~~~~~~~~~ -``Form.as_p()`` renders the form as a series of ``

`` tags, with each ``

`` -containing one field:: +.. method:: Form.as_p - >>> f = ContactForm() - >>> f.as_p() - u'

\n

\n

\n

' - >>> print f.as_p() -

-

-

-

+ ``as_p()`` renders the form as a series of ``

`` tags, with each ``

`` + containing one field:: + + >>> f = ContactForm() + >>> f.as_p() + u'

\n

\n

\n

' + >>> print f.as_p() +

+

+

+

``as_ul()`` ~~~~~~~~~~~ -``Form.as_ul()`` renders the form as a series of ``
  • `` tags, with each -``
  • `` containing one field. It does *not* include the ``
      `` or ``
    ``, -so that you can specify any HTML attributes on the ``
      `` for flexibility:: +.. method:: Form.as_ul - >>> f = ContactForm() - >>> f.as_ul() - u'
    • \n
    • \n
    • \n
    • ' - >>> print f.as_ul() -
    • -
    • -
    • -
    • + ``as_ul()`` renders the form as a series of ``
    • `` tags, with each + ``
    • `` containing one field. It does *not* include the ``
        `` or + ``
      ``, so that you can specify any HTML attributes on the ``
        `` for + flexibility:: + + >>> f = ContactForm() + >>> f.as_ul() + u'
      • \n
      • \n
      • \n
      • ' + >>> print f.as_ul() +
      • +
      • +
      • +
      • ``as_table()`` ~~~~~~~~~~~~~~ -Finally, ``Form.as_table()`` outputs the form as an HTML ````. This is -exactly the same as ``print``. In fact, when you ``print`` a form object, it -calls its ``as_table()`` method behind the scenes:: +.. method:: Form.as_table - >>> f = ContactForm() - >>> f.as_table() - u'\n\n\n' + Finally, ``as_table()`` outputs the form as an HTML ``
        ``. This is + exactly the same as ``print``. In fact, when you ``print`` a form object, + it calls its ``as_table()`` method behind the scenes:: + + >>> f = ContactForm() + >>> f.as_table() + u'\n\n\n' + >>> print f.as_table() + + + + + +Styling required or erroneous form rows +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 1.2 + +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. + +The :class:`Form` class has a couple of hooks you can use to add ``class`` +attributes to required rows or to rows with errors: simple set the +:attr:`Form.error_css_class` and/or :attr:`Form.required_css_class` +attributes:: + + class ContactForm(Form): + error_css_class = 'error' + required_css_class = 'required' + + # ... and the rest of your fields here + +Once you've done that, rows will be given ``"error"`` and/or ``"required"`` +classes, as needed. The HTML will look something like:: + + >>> f = ContactForm(data) >>> print f.as_table() - - - - +
        ... +
        ... +
        ... +