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/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 +- 28 files changed, 1899 insertions(+), 380 deletions(-) create mode 100644 docs/ref/contrib/messages.txt (limited to 'docs/ref') 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() - - - - +
        ... +
        ... +
        ... +