diff options
| author | Honza Král <honza.kral@gmail.com> | 2009-12-28 16:35:23 +0000 |
|---|---|---|
| committer | Honza Král <honza.kral@gmail.com> | 2009-12-28 16:35:23 +0000 |
| commit | f911df19a455246198b0c8c81ab96bf2abec04f8 (patch) | |
| tree | 0c0bfb72d622994419492db943d9d37857224f97 /docs/ref | |
| parent | 695de8cc9145e139c2b22e05aa44f5ac04da6f85 (diff) | |
[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
Diffstat (limited to 'docs/ref')
28 files changed, 1897 insertions, 378 deletions
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 <authentication-backends>` of the :ref:`User authentication guide <topics-auth>`. 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 <topics-forms-index>`. - -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 +<topics-forms-index>`. 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 <form-prefix>`. + 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 + <form-prefix>`. 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 <ref-templates-api-the-python-api>`. + 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 <ref-contrib-messages>`. + 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 <ref-middleware>` +class and corresponding :ref:`context processor <ref-templates-api>`. + +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 <message-storage-backends>` that + relies on :ref:`sessions <topics-http-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 <internals-release-process>`. + +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 %} + <ul class="messages"> + {% for message in messages %} + <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> + {% endfor %} + </ul> + {% 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 <topics-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 <ref-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-level-constants>`. + +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 + <message-level-constants>`. + +.. _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:: +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`:: - DATABASE_OPTIONS = { + 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 <ref-settings>`. 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:: +``HOST`` and ``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' + 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 <custom-managers>` 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 <fmt> 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 <topics-serialization-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 <fixture fixture ...> ------------------------------ @@ -297,6 +325,11 @@ loaddata <fixture fixture ...> 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 <appname appname ...> 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 <appname appname ...> ---------------------------- @@ -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 <appname appname ...> ------------------------------ @@ -573,6 +652,11 @@ sqlclear <appname appname ...> 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 <appname appname ...> ------------------------------- @@ -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 <appname appname ...> -------------------------------- @@ -609,6 +703,11 @@ sqlindexes <appname appname ...> 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 <appname appname ...> ------------------------------ @@ -616,6 +715,11 @@ sqlreset <appname appname ...> 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 <appname appname ...> -------------------------------------- @@ -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 <appname> ------------------ @@ -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 <app or test identifier> ----------------------------- @@ -696,6 +812,14 @@ test <app or test identifier> 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 <fixture fixture ...> -------------------------------- @@ -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 ``<p>`` tags, with each ``<p>`` -containing one field:: +.. method:: Form.as_p - >>> f = ContactForm() - >>> f.as_p() - u'<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p>\n<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>\n<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></p>\n<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>' - >>> print f.as_p() - <p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p> - <p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p> - <p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></p> - <p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p> + ``as_p()`` renders the form as a series of ``<p>`` tags, with each ``<p>`` + containing one field:: + + >>> f = ContactForm() + >>> f.as_p() + u'<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p>\n<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>\n<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></p>\n<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>' + >>> print f.as_p() + <p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p> + <p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p> + <p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></p> + <p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p> ``as_ul()`` ~~~~~~~~~~~ -``Form.as_ul()`` renders the form as a series of ``<li>`` tags, with each -``<li>`` containing one field. It does *not* include the ``<ul>`` or ``</ul>``, -so that you can specify any HTML attributes on the ``<ul>`` for flexibility:: +.. method:: Form.as_ul - >>> f = ContactForm() - >>> f.as_ul() - u'<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li>\n<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>\n<li><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></li>\n<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>' - >>> print f.as_ul() - <li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li> - <li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li> - <li><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></li> - <li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li> + ``as_ul()`` renders the form as a series of ``<li>`` tags, with each + ``<li>`` containing one field. It does *not* include the ``<ul>`` or + ``</ul>``, so that you can specify any HTML attributes on the ``<ul>`` for + flexibility:: + + >>> f = ContactForm() + >>> f.as_ul() + u'<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li>\n<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>\n<li><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></li>\n<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>' + >>> print f.as_ul() + <li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li> + <li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li> + <li><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></li> + <li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li> ``as_table()`` ~~~~~~~~~~~~~~ -Finally, ``Form.as_table()`` outputs the form as an HTML ``<table>``. 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'<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>\n<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>\n<tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr>\n<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>' + Finally, ``as_table()`` outputs the form as an HTML ``<table>``. 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'<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>\n<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>\n<tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr>\n<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>' + >>> print f.as_table() + <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr> + <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr> + <tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr> + <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr> + +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() - <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr> - <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr> - <tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr> - <tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr> + <tr class="required"><th><label for="id_subject">Subject:</label> ... + <tr class="required"><th><label for="id_message">Message:</label> ... + <tr class="required error"><th><label for="id_sender">Sender:</label> ... + <tr><th><label for="id_cc_myself">Cc myself:<label> ... .. _ref-forms-api-configuring-label: diff --git a/docs/ref/forms/index.txt b/docs/ref/forms/index.txt index a9e041c2a7..e310863c7a 100644 --- a/docs/ref/forms/index.txt +++ b/docs/ref/forms/index.txt @@ -1,5 +1,6 @@ .. _ref-forms-index: +===== Forms ===== @@ -7,8 +8,8 @@ Detailed form API reference. For introductory material, see :ref:`topics-forms-i .. toctree:: :maxdepth: 1 - + api fields widgets - validation
\ No newline at end of file + validation diff --git a/docs/ref/generic-views.txt b/docs/ref/generic-views.txt index 4752a705a0..af23506505 100644 --- a/docs/ref/generic-views.txt +++ b/docs/ref/generic-views.txt @@ -1088,4 +1088,3 @@ In addition to ``extra_context``, the template's context will be: variable's name depends on the ``template_object_name`` parameter, which is ``'object'`` by default. If ``template_object_name`` is ``'foo'``, this variable's name will be ``foo``. - diff --git a/docs/ref/index.txt b/docs/ref/index.txt index 6cc796d8e4..f1466c3496 100644 --- a/docs/ref/index.txt +++ b/docs/ref/index.txt @@ -1,5 +1,6 @@ .. _ref-index: +============= API Reference ============= @@ -20,4 +21,3 @@ API Reference signals templates/index unicode - diff --git a/docs/ref/middleware.txt b/docs/ref/middleware.txt index b0b26cc227..27a2d9a95a 100644 --- a/docs/ref/middleware.txt +++ b/docs/ref/middleware.txt @@ -1,8 +1,8 @@ .. _ref-middleware: -============================= -Built-in middleware reference -============================= +========== +Middleware +========== .. module:: django.middleware :synopsis: Django's built-in middleware classes. @@ -139,6 +139,20 @@ Enables language selection based on data from the request. It customizes content for each user. See the :ref:`internationalization documentation <topics-i18n>`. +Message middleware +------------------ + +.. module:: django.contrib.messages.middleware + :synopsis: Message middleware. + +.. class:: django.contrib.messages.middleware.MessageMiddleware + +.. versionadded:: 1.2 + ``MessageMiddleware`` was added. + +Enables cookie- and session-based message support. See the +:ref:`messages documentation <ref-contrib-messages>`. + Session middleware ------------------ diff --git a/docs/ref/models/fields.txt b/docs/ref/models/fields.txt index 0cb5be4b92..3c1106a217 100644 --- a/docs/ref/models/fields.txt +++ b/docs/ref/models/fields.txt @@ -299,6 +299,18 @@ according to available IDs. You usually won't need to use this directly; a primary key field will automatically be added to your model if you don't specify otherwise. See :ref:`automatic-primary-key-fields`. +``BigIntegerField`` +------------------- + +.. versionadded:: 1.2 + +.. class:: BigIntegerField([**options]) + +A 64 bit integer, much like an :class:`IntegerField` except that it is +guaranteed to fit numbers from -9223372036854775808 to 9223372036854775807. The +admin represents this as an ``<input type="text">`` (a single-line input). + + ``BooleanField`` ---------------- @@ -543,7 +555,7 @@ By default, :class:`FileField` instances are created as ``varchar(100)`` columns in your database. As with other fields, you can change the maximum length using the :attr:`~CharField.max_length` argument. -.. _`strftime formatting`: http://docs.python.org/lib/module-time.html#l2h-1941 +.. _`strftime formatting`: http://docs.python.org/library/time.html#time.strftime ``FilePathField`` ----------------- diff --git a/docs/ref/models/index.txt b/docs/ref/models/index.txt index 6918f335da..64b47b26cc 100644 --- a/docs/ref/models/index.txt +++ b/docs/ref/models/index.txt @@ -1,5 +1,6 @@ .. _ref-models-index: +====== Models ====== diff --git a/docs/ref/models/options.txt b/docs/ref/models/options.txt index d74f8350e8..f3e7363e36 100644 --- a/docs/ref/models/options.txt +++ b/docs/ref/models/options.txt @@ -4,8 +4,9 @@ Model ``Meta`` options ====================== -This document explains all the possible :ref:`metadata options <meta-options>` that you can give your model in its internal -``class Meta``. +This document explains all the possible :ref:`metadata options +<meta-options>` that you can give your model in its internal ``class +Meta``. Available ``Meta`` options ========================== @@ -242,4 +243,3 @@ The plural name for the object:: verbose_name_plural = "stories" If this isn't given, Django will use :attr:`~Options.verbose_name` + ``"s"``. - diff --git a/docs/ref/models/querysets.txt b/docs/ref/models/querysets.txt index e685472cca..2dbe8f03b0 100644 --- a/docs/ref/models/querysets.txt +++ b/docs/ref/models/querysets.txt @@ -94,7 +94,7 @@ the query construction and is not part of the public API. However, it is safe (and fully supported) to pickle and unpickle the attribute's contents as described here. -.. _pickle: http://docs.python.org/lib/module-pickle.html +.. _pickle: http://docs.python.org/library/pickle.html .. _queryset-api: @@ -874,6 +874,24 @@ logically:: # existing set of fields). Entry.objects.defer("body").only("headline", "body") +``using(alias)`` +~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 1.2 + +This method is for controlling which database the ``QuerySet`` will be +evaluated against if you are using more than one database. The only argument +this method takes is the alias of a database, as defined in +:setting:`DATABASES`. + +For example:: + + # queries the database with the 'default' alias. + >>> Entry.objects.all() + + # queries the database with the 'backup' alias + >>> Entry.objects.using('backup') + QuerySet methods that do not return QuerySets --------------------------------------------- @@ -1019,7 +1037,8 @@ Example:: ``count()`` performs a ``SELECT COUNT(*)`` behind the scenes, so you should always use ``count()`` rather than loading all of the record into Python -objects and calling ``len()`` on the result. +objects and calling ``len()`` on the result (unless you need to load the +objects into memory anyway, in which case ``len()`` will be faster). Depending on which database you're using (e.g. PostgreSQL vs. MySQL), ``count()`` may return a long integer instead of a normal Python integer. This @@ -1112,6 +1131,20 @@ control the name of the aggregation value that is returned:: For an in-depth discussion of aggregation, see :ref:`the topic guide on Aggregation <topics-db-aggregation>`. +``exists()`` +~~~~~~~~~~~~ + +.. versionadded:: 1.2 + +Returns ``True`` if the :class:`QuerySet` contains any results, and ``False`` +if not. This tries to perform the query in the simplest and fastest way +possible, but it *does* execute nearly the same query. This means that calling +:meth:`QuerySet.exists()` is faster than ``bool(some_query_set)``, but not by +a large degree. If ``some_query_set`` has not yet been evaluated, but you know +that it will be at some point, then using ``some_query_set.exists()`` will do +more overall work (an additional query) than simply using +``bool(some_query_set)``. + .. _field-lookups: ``exists()`` diff --git a/docs/ref/request-response.txt b/docs/ref/request-response.txt index 77d991bc1f..9dcf004149 100644 --- a/docs/ref/request-response.txt +++ b/docs/ref/request-response.txt @@ -298,9 +298,9 @@ a subclass of dictionary. Exceptions are outlined here: >>> q = q.copy() # to make it mutable >>> q.update({'a': '2'}) >>> q.getlist('a') - ['1', '2'] + [u'1', u'2'] >>> q['a'] # returns the last - ['2'] + [u'2'] .. method:: QueryDict.items() @@ -309,7 +309,7 @@ a subclass of dictionary. Exceptions are outlined here: >>> q = QueryDict('a=1&a=2&a=3') >>> q.items() - [('a', '3')] + [(u'a', u'3')] .. method:: QueryDict.iteritems() @@ -329,7 +329,7 @@ a subclass of dictionary. Exceptions are outlined here: >>> q = QueryDict('a=1&a=2&a=3') >>> q.values() - ['3'] + [u'3'] .. method:: QueryDict.itervalues() @@ -369,7 +369,7 @@ In addition, ``QueryDict`` has the following methods: >>> q = QueryDict('a=1&a=2&a=3') >>> q.lists() - [('a', ['1', '2', '3'])] + [(u'a', [u'1', u'2', u'3'])] .. method:: QueryDict.urlencode() @@ -598,4 +598,3 @@ types of HTTP responses. Like ``HttpResponse``, these subclasses live in .. class:: HttpResponseServerError Acts just like :class:`HttpResponse` but uses a 500 status code. - diff --git a/docs/ref/settings.txt b/docs/ref/settings.txt index 6e78030e8c..8cbc9ccc8f 100644 --- a/docs/ref/settings.txt +++ b/docs/ref/settings.txt @@ -1,5 +1,13 @@ .. _ref-settings: +======== +Settings +======== + +.. contents:: + :local: + :depth: 1 + Available settings ================== @@ -189,30 +197,67 @@ where ``reason`` is a short message (intended for developers or logging, not for end users) indicating the reason the request was rejected. See :ref:`ref-contrib-csrf`. -.. setting:: DATABASE_ENGINE -DATABASE_ENGINE ---------------- +.. setting:: DATABASES + +DATABASES +--------- + +.. versionadded: 1.2 + +Default: ``{}`` (Empty dictionary) + +A dictionary containing the settings for all databases to be used with +Django. It is a nested dictionary who's contents maps database aliases +to a dictionary containing the options for an individual database. + +The :setting:`DATABASES` setting must configure a ``default`` database; +any number of additional databases may also be specified. + +The simplest possible settings file is for a single-database setup using +SQLite. This can be configured using the following:: + + DATABASES = { + 'default': { + 'BACKEND': 'django.db.backends.sqlite3', + 'NAME': 'mydatabase' + } + } + +For other database backends, or more complex SQLite configurations, other options +will be required. The following inner options are available. + +.. setting:: ENGINE + +ENGINE +~~~~~~ Default: ``''`` (Empty string) -The database backend to use. The built-in database backends are -``'postgresql_psycopg2'``, ``'postgresql'``, ``'mysql'``, ``'sqlite3'``, and -``'oracle'``. +The database backend to use. The built-in database backends are: + + * ``'django.db.backends.postgresql_psycopg2'`` + * ``'django.db.backends.postgresql'`` + * ``'django.db.backends.mysql'`` + * ``'django.db.backends.sqlite3'`` + * ``'django.db.backends.oracle'`` You can use a database backend that doesn't ship with Django by setting -``DATABASE_ENGINE`` to a fully-qualified path (i.e. +``ENGINE`` to a fully-qualified path (i.e. ``mypackage.backends.whatever``). Writing a whole new database backend from scratch is left as an exercise to the reader; see the other backends for examples. -.. versionadded:: 1.0 - Support for external database backends is new in 1.0. +.. note:: + Prior to Django 1.2, you could use a short version of the backend name + to reference the built-in database backends (e.g., you could use + ``'sqlite3'`` to refer to the SQLite backend). This format has been + deprecated, and will be removed in Django 1.4. -.. setting:: DATABASE_HOST +.. setting:: HOST -DATABASE_HOST -------------- +HOST +~~~~ Default: ``''`` (Empty string) @@ -222,7 +267,7 @@ localhost. Not used with SQLite. If this value starts with a forward slash (``'/'``) and you're using MySQL, MySQL will connect via a Unix socket to the specified socket. For example:: - DATABASE_HOST = '/var/run/mysql' + "HOST": '/var/run/mysql' If you're using MySQL and this value *doesn't* start with a forward slash, then this value is assumed to be the host. @@ -232,10 +277,10 @@ for the connection, rather than a network connection to localhost. If you explicitly need to use a TCP/IP connection on the local machine with PostgreSQL, specify ``localhost`` here. -.. setting:: DATABASE_NAME +.. setting:: NAME -DATABASE_NAME -------------- +NAME +~~~~ Default: ``''`` (Empty string) @@ -243,44 +288,90 @@ The name of the database to use. For SQLite, it's the full path to the database file. When specifying the path, always use forward slashes, even on Windows (e.g. ``C:/homes/user/mysite/sqlite3.db``). -.. setting:: DATABASE_OPTIONS +.. setting:: OPTIONS -DATABASE_OPTIONS ----------------- +OPTIONS +~~~~~~~ Default: ``{}`` (Empty dictionary) Extra parameters to use when connecting to the database. Consult backend module's document for available keywords. -.. setting:: DATABASE_PASSWORD +.. setting:: PASSWORD -DATABASE_PASSWORD ------------------ +PASSWORD +~~~~~~~~ Default: ``''`` (Empty string) The password to use when connecting to the database. Not used with SQLite. -.. setting:: DATABASE_PORT +.. setting:: PORT -DATABASE_PORT -------------- +PORT +~~~~ Default: ``''`` (Empty string) The port to use when connecting to the database. An empty string means the default port. Not used with SQLite. -.. setting:: DATABASE_USER +.. setting:: USER -DATABASE_USER -------------- +USER +~~~~ Default: ``''`` (Empty string) The username to use when connecting to the database. Not used with SQLite. +.. setting:: TEST_CHARSET + +TEST_CHARSET +~~~~~~~~~~~~ + +Default: ``None`` + +The character set encoding used to create the test database. The value of this +string is passed directly through to the database, so its format is +backend-specific. + +Supported for the PostgreSQL_ (``postgresql``, ``postgresql_psycopg2``) and +MySQL_ (``mysql``) backends. + +.. _PostgreSQL: http://www.postgresql.org/docs/8.2/static/multibyte.html +.. _MySQL: http://dev.mysql.com/doc/refman/5.0/en/charset-database.html + +.. setting:: TEST_COLLATION + +TEST_COLLATION +~~~~~~~~~~~~~~ + +Default: ``None`` + +The collation order to use when creating the test database. This value is +passed directly to the backend, so its format is backend-specific. + +Only supported for the ``mysql`` backend (see the `MySQL manual`_ for details). + +.. _MySQL manual: MySQL_ + +.. setting:: TEST_NAME + +TEST_NAME +~~~~~~~~~ + +Default: ``None`` + +The name of database to use when running the test suite. + +If the default value (``None``) is used with the SQLite database engine, the +tests will use a memory resident database. For all other database engines the +test database will use the name ``'test_' + DATABASE_NAME``. + +See :ref:`topics-testing`. + .. setting:: DATE_FORMAT DATE_FORMAT @@ -288,12 +379,32 @@ DATE_FORMAT Default: ``'N j, Y'`` (e.g. ``Feb. 4, 2003``) -The default formatting to use for date fields on Django admin change-list -pages -- and, possibly, by other parts of the system. See -:ttag:`allowed date format strings <now>`. +The default formatting to use for date fields in any part of the system. +Note that if ``USE_L10N`` is set to ``True``, then locale format will +be applied. See :ttag:`allowed date format strings <now>`. + +See also ``DATETIME_FORMAT``, ``TIME_FORMAT`` and ``SHORT_DATE_FORMAT``. -See also ``DATETIME_FORMAT``, ``TIME_FORMAT``, ``YEAR_MONTH_FORMAT`` -and ``MONTH_DAY_FORMAT``. +.. setting:: DATE_INPUT_FORMATS + +DATE_INPUT_FORMATS +------------------ + +Default:: + + ('%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', '%b %d %Y', + '%b %d, %Y', '%d %b %Y', '%d %b, %Y', '%B %d %Y', + '%B %d, %Y', '%d %B %Y', '%d %B, %Y') + +A tuple of formats that will be accepted when inputting data on a date +field. Formats will be tried in order, using the first valid. +Note that these format strings are specified in Python's datetime_ module +syntax, that is different from the one used by Django for formatting dates +to be displayed. + +See also ``DATETIME_INPUT_FORMATS`` and ``TIME_INPUT_FORMATS``. + +.. _datetime: http://docs.python.org/library/datetime.html#strftime-behavior .. setting:: DATETIME_FORMAT @@ -302,12 +413,32 @@ DATETIME_FORMAT Default: ``'N j, Y, P'`` (e.g. ``Feb. 4, 2003, 4 p.m.``) -The default formatting to use for datetime fields on Django admin change-list -pages -- and, possibly, by other parts of the system. See -:ttag:`allowed date format strings <now>`. +The default formatting to use for datetime fields in any part of the system. +Note that if ``USE_L10N`` is set to ``True``, then locale format will +be applied. See :ttag:`allowed date format strings <now>`. + +See also ``DATE_FORMAT``, ``TIME_FORMAT`` and ``SHORT_DATETIME_FORMAT``. -See also ``DATE_FORMAT``, ``DATETIME_FORMAT``, ``TIME_FORMAT``, -``YEAR_MONTH_FORMAT`` and ``MONTH_DAY_FORMAT``. +.. setting:: DATETIME_INPUT_FORMATS + +DATETIME_INPUT_FORMATS +---------------------- + +Default:: + + ('%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d', + '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M', '%m/%d/%Y', + '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M', '%m/%d/%y') + +A tuple of formats that will be accepted when inputting data on a datetime +field. Formats will be tried in order, using the first valid. +Note that these format strings are specified in Python's datetime_ module +syntax, that is different from the one used by Django for formatting dates +to be displayed. + +See also ``DATE_INPUT_FORMATS`` and ``TIME_INPUT_FORMATS``. + +.. _datetime: http://docs.python.org/library/datetime.html#strftime-behavior .. setting:: DEBUG @@ -347,6 +478,14 @@ will be suppressed, and exceptions will propagate upwards. This can be useful for some test setups, and should never be used on a live site. +.. setting:: DECIMAL_SEPARATOR + +DECIMAL_SEPARATOR +----------------- + +Default: ``'.'`` (Dot) + +Default decimal separator used when formatting decimal numbers. .. setting:: DEFAULT_CHARSET @@ -594,7 +733,22 @@ system's standard umask. get totally incorrect behavior. -.. _documentation for os.chmod: http://docs.python.org/lib/os-file-dir.html +.. _documentation for os.chmod: http://docs.python.org/library/os.html#os.chmod + +.. setting:: FIRST_DAY_OF_WEEK + +FIRST_DAY_OF_WEEK +----------------- + +Default: ``0`` (Sunday) + +Number representing the first day of the week. This is especially useful +when displaying a calendar. This value is only used when not using +format internationalization, or when a format cannot be found for the +current locale. + +The value must be an integer from 0 to 6, where 0 means Sunday, 1 means +Monday and so on. .. setting:: FIXTURE_DIRS @@ -617,6 +771,34 @@ environment variable in any HTTP request. This setting can be used to override the server-provided value of ``SCRIPT_NAME``, which may be a rewritten version of the preferred value or not supplied at all. +.. setting:: FORMAT_MODULE_PATH + +FORMAT_MODULE_PATH +------------------ + +Default: ``None`` + +A full Python path to a Python package that contains format definitions for +project locales. If not ``None``, Django will check for a ``formats.py`` +file, under the directory named as the current locale, and will use the +formats defined on this file. + +For example, if ``FORMAT_MODULE_PATH`` is set to ``mysite.formats``, and +current language is ``en`` (English), Django will expect a directory tree +like:: + + mysite/ + formats/ + __init__.py + en/ + __init__.py + formats.py + +Available formats are ``DATE_FORMAT``, ``TIME_FORMAT``, ``DATETIME_FORMAT``, +``YEAR_MONTH_FORMAT``, ``MONTH_DAY_FORMAT``, ``SHORT_DATE_FORMAT``, +``SHORT_DATETIME_FORMAT``, ``FIRST_DAY_OF_WEEK``, ``DECIMAL_SEPARATOR``, +``THOUSAND_SEPARATOR`` and ``NUMBER_GROUPING``. + .. setting:: IGNORABLE_404_ENDS IGNORABLE_404_ENDS @@ -761,7 +943,7 @@ LOGIN_URL Default: ``'/accounts/login/'`` -The URL where requests are redirected for login, specially when using the +The URL where requests are redirected for login, especially when using the :func:`~django.contrib.auth.decorators.login_required` decorator. .. setting:: LOGOUT_URL @@ -812,6 +994,43 @@ Bad: ``"http://www.example.com/static"`` .. setting:: MIDDLEWARE_CLASSES +MESSAGE_LEVEL +------------- + +.. versionadded:: 1.2 + +Default: `messages.INFO` + +Sets the minimum message level that will be recorded by the messages +framework. See the :ref:`messages documentation <ref-contrib-messages>` for +more details. + +MESSAGE_STORAGE +--------------- + +.. versionadded:: 1.2 + +Default: ``'django.contrib.messages.storage.user_messages.LegacyFallbackStorage'`` + +Controls where Django stores message data. See the +:ref:`messages documentation <ref-contrib-messages>` for more details. + +MESSAGE_TAGS +------------ + +.. versionadded:: 1.2 + +Default:: + + {messages.DEBUG: 'debug', + messages.INFO: 'info', + messages.SUCCESS: 'success', + messages.WARNING: 'warning', + messages.ERROR: 'error',} + +Sets the mapping of message levels to message tags. See the +:ref:`messages documentation <ref-contrib-messages>` for more details. + MIDDLEWARE_CLASSES ------------------ @@ -820,10 +1039,16 @@ Default:: ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', - 'django.contrib.auth.middleware.AuthenticationMiddleware',) + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware',) A tuple of middleware classes to use. See :ref:`topics-http-middleware`. +.. versionchanged:: 1.2 + ``'django.contrib.messages.middleware.MessageMiddleware'`` was added to the + default. For more information, see the :ref:`messages documentation + <ref-contrib-messages>`. + .. setting:: MONTH_DAY_FORMAT MONTH_DAY_FORMAT @@ -843,6 +1068,21 @@ locales have different formats. For example, U.S. English would say See :ttag:`allowed date format strings <now>`. See also ``DATE_FORMAT``, ``DATETIME_FORMAT``, ``TIME_FORMAT`` and ``YEAR_MONTH_FORMAT``. +.. setting:: NUMBER_GROUPING + +NUMBER_GROUPING +---------------- + +Default: ``0`` + +Number of digits grouped together on the integer part of a number. Common use +is to display a thousand separator. If this setting is ``0``, then, no grouping +will be applied to the number. If this setting is greater than ``0`` then the +setting ``THOUSAND_SEPARATOR`` will be used as the separator between those +groups. + +See also ``THOUSAND_SEPARATOR`` + .. setting:: PREPEND_WWW PREPEND_WWW @@ -1002,6 +1242,18 @@ See the :ref:`topics-http-sessions`. .. setting:: SESSION_EXPIRE_AT_BROWSER_CLOSE +SESSION_DB_ALIAS +---------------- + +.. versionadded:: 1.2 + +Default: ``None`` + +If you're using database-backed session storage, this selects the database +alias that will be used to store session data. By default, Django will use +the ``default`` database, but you can store session data on any database +you choose. + SESSION_EXPIRE_AT_BROWSER_CLOSE ------------------------------- @@ -1034,6 +1286,32 @@ Default: ``False`` Whether to save the session data on every request. See :ref:`topics-http-sessions`. +.. setting:: SHORT_DATE_FORMAT + +SHORT_DATE_FORMAT +----------------- + +Default: ``m/d/Y`` (e.g. ``12/31/2003``) + +An available formatting that can be used for date fields on templates. +Note that if ``USE_L10N`` is set to ``True``, then locale format will +be applied. See :ttag:`allowed date format strings <now>`. + +See also ``DATE_FORMAT`` and ``SHORT_DATETIME_FORMAT``. + +.. setting:: SHORT_DATETIME_FORMAT + +SHORT_DATETIME_FORMAT +--------------------- + +Default: ``m/d/Y P`` (e.g. ``12/31/2003 4 p.m.``) + +An available formatting that can be used for datetime fields on templates. +Note that if ``USE_L10N`` is set to ``True``, then locale format will +be applied. See :ttag:`allowed date format strings <now>`. + +See also ``DATE_FORMAT`` and ``SHORT_DATETIME_FORMAT``. + .. setting:: SITE_ID SITE_ID @@ -1059,12 +1337,18 @@ Default:: ("django.core.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", - "django.core.context_processors.media") + "django.core.context_processors.media", + "django.contrib.messages.context_processors.messages") A tuple of callables that are used to populate the context in ``RequestContext``. These callables take a request object as their argument and return a dictionary of items to be merged into the context. +.. versionchanged:: 1.2 + ``"django.contrib.messages.context_processors.messages"`` was added to the + default. For more information, see the :ref:`messages documentation + <ref-contrib-messages>`. + .. setting:: TEMPLATE_DEBUG TEMPLATE_DEBUG @@ -1101,11 +1385,14 @@ TEMPLATE_LOADERS Default:: - ('django.template.loaders.filesystem.load_template_source', - 'django.template.loaders.app_directories.load_template_source') + ('django.template.loaders.filesystem.Loader', + 'django.template.loaders.app_directories.Loader') -A tuple of callables (as strings) that know how to import templates from -various sources. See :ref:`ref-templates-api`. +A tuple of template loader classes, specified as strings. Each ``Loader`` class +knows how to import templates from a particular sources. Optionally, a tuple can be +used instead of a string. The first item in the tuple should be the ``Loader``'s +module, subsequent items are passed to the ``Loader`` during initialization. See +:ref:`ref-templates-api`. .. setting:: TEMPLATE_STRING_IF_INVALID @@ -1117,81 +1404,59 @@ Default: ``''`` (Empty string) Output, as a string, that the template system should use for invalid (e.g. misspelled) variables. See :ref:`invalid-template-variables`.. -.. setting:: TEST_DATABASE_CHARSET - -TEST_DATABASE_CHARSET ---------------------- - -.. versionadded:: 1.0 - -Default: ``None`` - -The character set encoding used to create the test database. The value of this -string is passed directly through to the database, so its format is -backend-specific. - -Supported for the PostgreSQL_ (``postgresql``, ``postgresql_psycopg2``) and MySQL_ (``mysql``) backends. - -.. _PostgreSQL: http://www.postgresql.org/docs/8.2/static/multibyte.html -.. _MySQL: http://www.mysql.org/doc/refman/5.0/en/charset-database.html - -.. setting:: TEST_DATABASE_COLLATION - -TEST_DATABASE_COLLATION ------------------------- - -.. versionadded:: 1.0 +.. setting:: TEST_RUNNER -Default: ``None`` +TEST_RUNNER +----------- -The collation order to use when creating the test database. This value is -passed directly to the backend, so its format is backend-specific. +Default: ``'django.test.simple.run_tests'`` -Only supported for the ``mysql`` backend (see `section 10.3.2`_ of the MySQL -manual for details). +The name of the method to use for starting the test suite. See +:ref:`topics-testing`. -.. _section 10.3.2: http://www.mysql.org/doc/refman/5.0/en/charset-database.html +.. _Testing Django Applications: ../testing/ -.. setting:: TEST_DATABASE_NAME +.. setting:: THOUSAND_SEPARATOR -TEST_DATABASE_NAME +THOUSAND_SEPARATOR ------------------ -Default: ``None`` +Default ``,`` (Comma) -The name of database to use when running the test suite. +Default thousand separator used when formatting numbers. This setting is +used only when ``NUMBER_GROUPPING`` is set. -If the default value (``None``) is used with the SQLite database engine, the -tests will use a memory resident database. For all other database engines the -test database will use the name ``'test_' + settings.DATABASE_NAME``. +See also ``NUMBER_GROUPPING``, ``DECIMAL_SEPARATOR`` -See :ref:`topics-testing`. - -.. setting:: TEST_RUNNER +.. setting:: TIME_FORMAT -TEST_RUNNER +TIME_FORMAT ----------- -Default: ``'django.test.simple.run_tests'`` +Default: ``'P'`` (e.g. ``4 p.m.``) -The name of the method to use for starting the test suite. See -:ref:`topics-testing`. +The default formatting to use for time fields in any part of the system. +Note that if ``USE_L10N`` is set to ``True``, then locale format will +be applied. See :ttag:`allowed date format strings <now>`. -.. _Testing Django Applications: ../testing/ +See also ``DATE_FORMAT`` and ``DATETIME_FORMAT``. -.. setting:: TIME_FORMAT +.. setting:: TIME_INPUT_FORMATS -TIME_FORMAT ------------ +TIME_INPUT_FORMATS +------------------ -Default: ``'P'`` (e.g. ``4 p.m.``) +Default: ``('%H:%M:%S', '%H:%M')`` + +A tuple of formats that will be accepted when inputting data on a time +field. Formats will be tried in order, using the first valid. +Note that these format strings are specified in Python's datetime_ module +syntax, that is different from the one used by Django for formatting dates +to be displayed. -The default formatting to use for time fields on Django admin change-list -pages -- and, possibly, by other parts of the system. See -:ttag:`allowed date format strings <now>`. +See also ``DATE_INPUT_FORMATS`` and ``DATETIME_INPUT_FORMATS``. -See also ``DATE_FORMAT``, ``DATETIME_FORMAT``, ``TIME_FORMAT``, -``YEAR_MONTH_FORMAT`` and ``MONTH_DAY_FORMAT``. +.. _datetime: http://docs.python.org/library/datetime.html#strftime-behavior .. setting:: TIME_ZONE @@ -1246,6 +1511,19 @@ A boolean that specifies whether to output the "Etag" header. This saves bandwidth but slows down performance. This is only used if ``CommonMiddleware`` is installed (see :ref:`topics-http-middleware`). +.. setting:: USE_L10N + +USE_L10N +-------- + +Default ``False`` + +A boolean that specifies if data will be localized by default or not. If this +is set to ``True``, e.g. Django will display numbers and dates using the +format of the current locale. + +See also ``USE_I18N`` and ``LANGUAGE_CODE`` + .. setting:: USE_I18N USE_I18N @@ -1258,6 +1536,22 @@ enabled. This provides an easy way to turn it off, for performance. If this is set to ``False``, Django will make some optimizations so as not to load the internationalization machinery. +See also ``USE_L10N`` + +.. setting:: USE_THOUSAND_SEPARATOR + +USE_THOUSAND_SEPARATOR +---------------------- + +Default ``False`` + +A boolean that specifies wheter to display numbers using a thousand separator. +If this is set to ``True``, Django will use values from ``THOUSAND_SEPARATOR`` +and ``NUMBER_GROUPING`` from current locale, to format the number. +``USE_L10N`` must be set to ``True``, in order to format numbers. + +See also ``THOUSAND_SEPARATOR`` and ``NUMBER_GROUPING``. + .. setting:: YEAR_MONTH_FORMAT YEAR_MONTH_FORMAT @@ -1276,3 +1570,97 @@ Different locales have different formats. For example, U.S. English would say See :ttag:`allowed date format strings <now>`. See also ``DATE_FORMAT``, ``DATETIME_FORMAT``, ``TIME_FORMAT`` and ``MONTH_DAY_FORMAT``. + +Deprecated settings +=================== + +.. setting:: DATABASE_ENGINE + +DATABASE_ENGINE +--------------- + +.. deprecated:: 1.2 + This setting has been replaced by :setting:`ENGINE` in + :setting:`DATABASES`. + +.. setting:: DATABASE_HOST + +DATABASE_HOST +------------- + +.. deprecated:: 1.2 + This setting has been replaced by :setting:`HOST` in + :setting:`DATABASES`. + +.. setting:: DATABASE_NAME + +DATABASE_NAME +------------- + +.. deprecated:: 1.2 + This setting has been replaced by :setting:`NAME` in + :setting:`DATABASES`. + +.. setting:: DATABASE_OPTIONS + +DATABASE_OPTIONS +---------------- + +.. deprecated:: 1.2 + This setting has been replaced by :setting:`OPTIONS` in + :setting:`DATABASES`. + +.. setting:: DATABASE_PASSWORD + +DATABASE_PASSWORD +----------------- + +.. deprecated:: 1.2 + This setting has been replaced by :setting:`PASSWORD` in + :setting:`DATABASES`. + +.. setting:: DATABASE_PORT + +DATABASE_PORT +------------- + +.. deprecated:: 1.2 + This setting has been replaced by :setting:`PORT` in + :setting:`DATABASES`. + +.. setting:: DATABASE_USER + +DATABASE_USER +------------- + +.. deprecated:: 1.2 + This setting has been replaced by :setting:`USER` in + :setting:`DATABASES`. + +.. setting:: TEST_DATABASE_CHARSET + +TEST_DATABASE_CHARSET +--------------------- + +.. deprecated:: 1.2 + This setting has been replaced by :setting:`TEST_CHARSET` in + :setting:`DATABASES`. + +.. setting:: TEST_DATABASE_COLLATION + +TEST_DATABASE_COLLATION +----------------------- + +.. deprecated:: 1.2 + This setting has been replaced by :setting:`TEST_COLLATION` in + :setting:`DATABASES`. + +.. setting:: TEST_DATABASE_NAME + +TEST_DATABASE_NAME +------------------ + +.. deprecated:: 1.2 + This setting has been replaced by :setting:`TEST_NAME` in + :setting:`DATABASES`. + diff --git a/docs/ref/signals.txt b/docs/ref/signals.txt index cc203f1817..b54a895000 100644 --- a/docs/ref/signals.txt +++ b/docs/ref/signals.txt @@ -1,8 +1,8 @@ .. _ref-signals: -========================= -Built-in signal reference -========================= +======= +Signals +======= A list of all the signals that Django sends. diff --git a/docs/ref/templates/api.txt b/docs/ref/templates/api.txt index 1b6eeb7014..120cab384b 100644 --- a/docs/ref/templates/api.txt +++ b/docs/ref/templates/api.txt @@ -311,7 +311,8 @@ and return a dictionary of items to be merged into the context. By default, ("django.core.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", - "django.core.context_processors.media") + "django.core.context_processors.media", + "django.contrib.messages.context_processors.messages") .. versionadded:: 1.2 In addition to these, ``RequestContext`` always uses @@ -320,6 +321,10 @@ and return a dictionary of items to be merged into the context. By default, in case of accidental misconfiguration, it is deliberately hardcoded in and cannot be turned off by the :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting. +.. versionadded:: 1.2 + The ``'messages'`` context processor was added. For more information, see + the :ref:`messages documentation <ref-contrib-messages>`. + Each processor is applied in order. That means, if one processor adds a variable to the context and a second processor adds a variable with the same name, the second will override the first. The default processors are explained @@ -365,17 +370,18 @@ If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every logged-in user (or an ``AnonymousUser`` instance, if the client isn't logged in). - * ``messages`` -- A list of messages (as strings) for the currently - logged-in user. Behind the scenes, this calls - ``request.user.get_and_delete_messages()`` for every request. That method - collects the user's messages and deletes them from the database. - - Note that messages are set with ``user.message_set.create``. + * ``messages`` -- A list of messages (as strings) that have been set + via the :ref:`messages framework <ref-contrib-messages>`. * ``perms`` -- An instance of ``django.core.context_processors.PermWrapper``, representing the permissions that the currently logged-in user has. +.. versionchanged:: 1.2 + Prior to version 1.2, the ``messages`` variable was a lazy accessor for + ``user.get_and_delete_messages()``. It has been changed to include any + messages added via the :ref:`messages framework <ref-contrib-messages`. + django.core.context_processors.debug ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -427,6 +433,25 @@ If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every :class:`~django.http.HttpRequest`. Note that this processor is not enabled by default; you'll have to activate it. +django.contrib.messages.context_processors.messages +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every +``RequestContext`` will contain a single additional variable: + + * ``messages`` -- A list of messages (as strings) that have been set + via the user model (using ``user.message_set.create``) or through + the :ref:`messages framework <ref-contrib-messages>`. + +.. versionadded:: 1.2 + This template context variable was previously supplied by the ``'auth'`` + context processor. For backwards compatibility the ``'auth'`` context + processor will continue to supply the ``messages`` variable until Django + 1.4. If you use the ``messages`` variable, your project will work with + either (or both) context processors, but it is recommended to add + ``django.contrib.messages.context_processors.messages`` so your project + will be prepared for the future upgrade. + Writing your own context processors ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -477,12 +502,14 @@ The Python API Django has two ways to load templates from files: -``django.template.loader.get_template(template_name)`` +.. function:: django.template.loader.get_template(template_name) + ``get_template`` returns the compiled template (a ``Template`` object) for the template with the given name. If the template doesn't exist, it raises ``django.template.TemplateDoesNotExist``. -``django.template.loader.select_template(template_name_list)`` +.. function:: django.template.loader.select_template(template_name_list) + ``select_template`` is just like ``get_template``, except it takes a list of template names. Of the list, it returns the first template that exists. @@ -546,11 +573,11 @@ by editing your :setting:`TEMPLATE_LOADERS` setting. :setting:`TEMPLATE_LOADERS` should be a tuple of strings, where each string represents a template loader. Here are the template loaders that come with Django: -``django.template.loaders.filesystem.load_template_source`` +``django.template.loaders.filesystem.Loader`` Loads templates from the filesystem, according to :setting:`TEMPLATE_DIRS`. This loader is enabled by default. -``django.template.loaders.app_directories.load_template_source`` +``django.template.loaders.app_directories.Loader`` Loads templates from Django apps on the filesystem. For each app in :setting:`INSTALLED_APPS`, the loader looks for a ``templates`` subdirectory. If the directory exists, Django looks for templates in there. @@ -574,12 +601,43 @@ Here are the template loaders that come with Django: This loader is enabled by default. -``django.template.loaders.eggs.load_template_source`` +``django.template.loaders.eggs.Loader`` Just like ``app_directories`` above, but it loads templates from Python eggs rather than from the filesystem. This loader is disabled by default. +``django.template.loaders.cached.Loader`` + By default, the templating system will read and compile your templates every + time they need to be rendered. While the Django templating system is quite + fast, the overhead from reading and compiling templates can add up. + + The cached template loader is a class-based loader that you configure with + a list of other loaders that it should wrap. The wrapped loaders are used to + locate unknown templates when they are first encountered. The cached loader + then stores the compiled ``Template`` in memory. The cached ``Template`` + instance is returned for subsequent requests to load the same template. + + For example, to enable template caching with the ``filesystem`` and + ``app_directories`` template loaders you might use the following settings:: + + TEMPLATE_LOADERS = ( + ('django.template.loaders.cached.Loader', ( + 'django.template.loaders.filesystem.Loader', + 'django.template.loaders.app_directories.Loader', + )), + ) + + .. note:: + All of the built-in Django template tags are safe to use with the cached + loader, but if you're using custom template tags that come from third + party packages, or that you wrote yourself, you should ensure that the + ``Node`` implementation for each tag is thread-safe. For more + information, see + :ref:`template tag thread safety considerations<template_tag_thread_safety>`. + + This loader is disabled by default. + Django uses the template loaders in order according to the :setting:`TEMPLATE_LOADERS` setting. It uses each loader until a loader finds a match. @@ -642,3 +700,68 @@ settings you wish to specify. You might want to consider setting at least and :setting:`TEMPLATE_DEBUG`. All available settings are described in the :ref:`settings documentation <ref-settings>`, and any setting starting with ``TEMPLATE_`` is of obvious interest. + +.. _topic-template-alternate-language: + +Using an alternative template language +====================================== + +.. versionadded 1.2 + +The Django ``Template`` and ``Loader`` classes implement a simple API for +loading and rendering templates. By providing some simple wrapper classes that +implement this API we can use third party template systems like `Jinja2 +<http://jinja.pocoo.org/2/>`_ or `Cheetah <http://www.cheetahtemplate.org/>`_. This +allows us to use third-party template libraries without giving up useful Django +features like the Django ``Context`` object and handy shortcuts like +``render_to_response()``. + +The core component of the Django templating system is the ``Template`` class. +This class has a very simple interface: it has a constructor that takes a single +positional argument specifying the template string, and a ``render()`` method +that takes a ``django.template.context.Context`` object and returns a string +containing the rendered response. + +Suppose we're using a template language that defines a ``Template`` object with +a ``render()`` method that takes a dictionary rather than a ``Context`` object. +We can write a simple wrapper that implements the Django ``Template`` interface:: + + import some_template_language + class Template(some_template_language.Template): + def render(self, context): + # flatten the Django Context into a single dictionary. + context_dict = {} + for d in context.dicts: + context_dict.update(d) + return super(Template, self).render(context_dict) + +That's all that's required to make our fictional ``Template`` class compatible +with the Django loading and rendering system! + +The next step is to write a ``Loader`` class that returns instances of our custom +template class instead of the default ``django.template.Template``. Custom ``Loader`` +classes should inherit from ``django.template.loader.BaseLoader`` and override +the ``load_template_source()`` method, which takes a ``template_name`` argument, +loads the template from disk (or elsewhere), and returns a tuple: +``(template_string, template_origin)``. + +The ``load_template()`` method of the ``Loader`` class retrieves the template +string by calling ``load_template_source()``, instantiates a ``Template`` from +the template source, and returns a tuple: ``(template, template_origin)``. Since +this is the method that actually instantiates the ``Template``, we'll need to +override it to use our custom template class instead. We can inherit from the +builtin ``django.template.loaders.app_directories.Loader`` to take advantage of +the ``load_template_source()`` method implemented there:: + + from django.template.loaders import app_directories + class Loader(app_directories.Loader): + is_usable = True + + def load_template(self, template_name, template_dirs=None): + source, origin = self.load_template_source(template_name, template_dirs) + template = Template(source) + return template, origin + +Finally, we need to modify our project settings, telling Django to use our custom +loader. Now we can write all of our templates in our alternative template +language while continuing to use the rest of the Django templating system. diff --git a/docs/ref/templates/builtins.txt b/docs/ref/templates/builtins.txt index 20591311be..fb8b847608 100644 --- a/docs/ref/templates/builtins.txt +++ b/docs/ref/templates/builtins.txt @@ -323,6 +323,9 @@ displayed by the ``{{ athlete_list|length }}`` variable. As you can see, the ``if`` tag can take an optional ``{% else %}`` clause that will be displayed if the test fails. +Boolean operators +^^^^^^^^^^^^^^^^^ + ``if`` tags may use ``and``, ``or`` or ``not`` to test a number of variables or to negate a given variable:: @@ -348,24 +351,153 @@ to negate a given variable:: There are some athletes and absolutely no coaches. {% endif %} -``if`` tags don't allow ``and`` and ``or`` clauses within the same tag, because -the order of logic would be ambiguous. For example, this is invalid:: +.. versionchanged:: 1.2 + +Use of both ``and`` and ``or`` clauses within the same tag is allowed, with +``and`` having higher precedence than ``or`` e.g.:: {% if athlete_list and coach_list or cheerleader_list %} -If you need to combine ``and`` and ``or`` to do advanced logic, just use nested -``if`` tags. For example:: +will be interpreted like: - {% if athlete_list %} - {% if coach_list or cheerleader_list %} - We have athletes, and either coaches or cheerleaders! - {% endif %} +.. code-block:: python + + if (athlete_list and coach_list) or cheerleader_list + +Use of actual brackets in the ``if`` tag is invalid syntax. If you need them to +indicate precedence, you should use nested ``if`` tags. + +.. versionadded:: 1.2 + + +``if`` tags may also use the operators ``==``, ``!=``, ``<``, ``>``, +``<=``, ``>=`` and ``in`` which work as follows: + + +``==`` operator +^^^^^^^^^^^^^^^ + +Equality. Example:: + + {% if somevar == "x" %} + This appears if variable somevar equals the string "x" + {% endif %} + +``!=`` operator +^^^^^^^^^^^^^^^ + +Inequality. Example:: + + {% if somevar != "x" %} + This appears if variable somevar does not equal the string "x", + or if somevar is not found in the context + {% endif %} + +``<`` operator +^^^^^^^^^^^^^^ + +Less than. Example:: + + {% if somevar < 100 %} + This appears if variable somevar is less than 100. + {% endif %} + +``>`` operator +^^^^^^^^^^^^^^ + +Greater than. Example:: + + {% if somevar > 0 %} + This appears if variable somevar is greater than 0. + {% endif %} + +``<=`` operator +^^^^^^^^^^^^^^^ + +Less than or equal to. Example:: + + {% if somevar <= 100 %} + This appears if variable somevar is less than 100 or equal to 100. + {% endif %} + +``>=`` operator +^^^^^^^^^^^^^^^ + +Greater than or equal to. Example:: + + {% if somevar >= 1 %} + This appears if variable somevar is greater than 1 or equal to 1. {% endif %} -Multiple uses of the same logical operator are fine, as long as you use the -same operator. For example, this is valid:: +``in`` operator +^^^^^^^^^^^^^^^ + +Contained within. This operator is supported by many Python containers to test +whether the given value is in the container. The following are some examples of +how ``x in y`` will be interpreted:: + + {% if "bc" in "abcdef" %} + This appears since "bc" is a substring of "abcdef" + {% endif %} + + {% if "hello" in greetings %} + If greetings is a list or set, one element of which is the string + "hello", this will appear. + {% endif %} + + {% if user in users %} + If users is a QuerySet, this will appear if user is an + instance that belongs to the QuerySet. + {% endif %} + + +The comparison operators cannot be 'chained' like in Python or in mathematical +notation. For example, instead of using:: + + {% if a > b > c %} (WRONG) + +you should use:: + + {% if a > b and b > c %} + + +Filters +^^^^^^^ + +You can also use filters in the ``if`` expression. For example:: + + {% if messages|length >= 100 %} + You have lots of messages today! + {% endif %} + +Complex expressions +^^^^^^^^^^^^^^^^^^^ + +All of the above can be combined to form complex expressions. For such +expressions, it can be important to know how the operators are grouped when the +expression is evaluated - that is, the precedence rules. The precedence of the +operators, from lowest to highest, is as follows: + + * ``or`` + * ``and`` + * ``not`` + * ``in`` + * ``==``, ``!=``, ``<``, ``>``,``<=``, ``>=`` + +(This follows Python exactly). So, for example, the following complex if tag: + + {% if a == b or c == d and e %} + +...will be interpreted as: + +.. code-block:: python + + (a == b) or ((c == d) and e) + +If you need different precedence, you will need to use nested if tags. Sometimes +that is better for clarity anyway, for the sake of those who do not know the +precedence rules. - {% if athlete_list or coach_list or parent_list or teacher_list %} .. templatetag:: ifchanged @@ -437,6 +569,9 @@ You cannot check for equality with Python objects such as ``True`` or ``False``. If you need to test if something is true or false, use the ``if`` tag instead. +.. versionadded:: 1.2 + An alternative to the ``ifequal`` tag is to use the :ttag:`if` tag and the ``==`` operator. + .. templatetag:: ifnotequal ifnotequal @@ -444,6 +579,9 @@ ifnotequal Just like ``ifequal``, except it tests that the two arguments are not equal. +.. versionadded:: 1.2 + An alternative to the ``ifnotequal`` tag is to use the :ttag:`if` tag and the ``!=`` operator. + .. templatetag:: include include @@ -919,7 +1057,12 @@ If ``value`` is ``"String with spaces"``, the output will be ``"Stringwithspaces date ~~~~ -Formats a date according to the given format (same as the `now`_ tag). +Formats a date according to the given format. + +Given format can be one of the predefined ones ``DATE_FORMAT``, +``DATETIME_FORMAT``, ``SHORT_DATE_FORMAT`` or ``SHORT_DATETIME_FORMAT``, +or a custom format, same as the `now`_ tag. Note that predefined formats may +vary depending on the current locale. For example:: @@ -934,7 +1077,7 @@ When used without a format string:: {{ value|date }} ...the formatting string defined in the :setting:`DATE_FORMAT` setting will be -used. +used, without applying any localization. .. templatefilter:: default @@ -1482,7 +1625,11 @@ output will be ``"Joel is a slug"``. time ~~~~ -Formats a time according to the given format (same as the `now`_ tag). +Formats a time according to the given format. + +Given format can be the predefined one ``TIME_FORMAT``, or a custom format, +same as the `now`_ tag. Note that the predefined format is locale depending. + The time filter will only accept parameters in the format string that relate to the time of day, not the date (for obvious reasons). If you need to format a date, use the `date`_ filter. @@ -1499,7 +1646,7 @@ When used without a format string:: {{ value|time }} ...the formatting string defined in the :setting:`TIME_FORMAT` setting will be -used. +used, without aplying any localization. .. templatefilter:: timesince diff --git a/docs/ref/templates/index.txt b/docs/ref/templates/index.txt index d7bf99aa8c..6655b3da18 100644 --- a/docs/ref/templates/index.txt +++ b/docs/ref/templates/index.txt @@ -1,7 +1,8 @@ .. _ref-templates-index: -Template reference -================== +========= +Templates +========= Django's template engine provides a powerful mini-language for defining the user-facing layer of your application, encouraging a clean separation of @@ -17,4 +18,4 @@ an understanding of HTML; no knowledge of Python is required. .. seealso:: For information on writing your own custom tags and filters, see - :ref:`howto-custom-template-tags`.
\ No newline at end of file + :ref:`howto-custom-template-tags`. diff --git a/docs/ref/unicode.txt b/docs/ref/unicode.txt index c5851a2c6c..a6149119bf 100644 --- a/docs/ref/unicode.txt +++ b/docs/ref/unicode.txt @@ -1,8 +1,8 @@ .. _ref-unicode: -====================== -Unicode data in Django -====================== +============ +Unicode data +============ .. versionadded:: 1.0 @@ -21,8 +21,8 @@ data. Normally, this means giving it an encoding of UTF-8 or UTF-16. If you use a more restrictive encoding -- for example, latin1 (iso8859-1) -- you won't be able to store certain characters in the database, and information will be lost. - * MySQL users, refer to the `MySQL manual`_ (section 10.3.2 for MySQL 5.1) for - details on how to set or alter the database character set encoding. + * MySQL users, refer to the `MySQL manual`_ (section 9.1.3.2 for MySQL 5.1) + for details on how to set or alter the database character set encoding. * PostgreSQL users, refer to the `PostgreSQL manual`_ (section 21.2.2 in PostgreSQL 8) for details on creating databases with the correct encoding. @@ -30,7 +30,7 @@ able to store certain characters in the database, and information will be lost. * SQLite users, there is nothing you need to do. SQLite always uses UTF-8 for internal encoding. -.. _MySQL manual: http://www.mysql.org/doc/refman/5.1/en/charset-database.html +.. _MySQL manual: http://dev.mysql.com/doc/refman/5.1/en/charset-database.html .. _PostgreSQL manual: http://www.postgresql.org/docs/8.2/static/multibyte.html#AEN24104 All of Django's database backends automatically convert Unicode strings into |
