From bdcc95e5cce2754d78055f86d561ba2be92ba854 Mon Sep 17 00:00:00 2001 From: Jeremy Dunck Date: Mon, 18 Jun 2007 16:48:27 +0000 Subject: gis: Merged revisions 4786-5490 via svnmerge from http://code.djangoproject.com/svn/django/trunk git-svn-id: http://code.djangoproject.com/svn/django/branches/gis@5492 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/add_ons.txt | 35 +- docs/api_stability.txt | 6 +- docs/authentication.txt | 42 ++- docs/cache.txt | 17 +- docs/contributing.txt | 92 ++++- docs/databases.txt | 9 +- docs/databrowse.txt | 60 ++++ docs/db-api.txt | 88 +++-- docs/distributions.txt | 10 +- docs/django-admin.txt | 86 +++-- docs/documentation.txt | 42 +-- docs/email.txt | 87 ++++- docs/faq.txt | 15 +- docs/fastcgi.txt | 40 ++- docs/flatpages.txt | 4 +- docs/forms.txt | 35 +- docs/generic_views.txt | 9 +- docs/i18n.txt | 10 +- docs/install.txt | 65 ++-- docs/legacy_databases.txt | 10 +- docs/man/django-admin.1 | 162 +++++++++ docs/model-api.txt | 198 +++++++---- docs/modpython.txt | 73 +++- docs/newforms.txt | 848 ++++++++++++++++++++++++++++++++++++++++++-- docs/overview.txt | 2 +- docs/redirects.txt | 4 +- docs/release_notes_0.96.txt | 4 +- docs/request_response.txt | 9 +- docs/serialization.txt | 27 +- docs/sessions.txt | 4 +- docs/settings.txt | 156 +++++--- docs/sitemaps.txt | 2 - docs/sites.txt | 4 +- docs/syndication_feeds.txt | 32 +- docs/templates.txt | 88 ++++- docs/templates_python.txt | 106 ++++-- docs/testing.txt | 277 +++++++++++---- docs/tutorial01.txt | 26 +- docs/tutorial02.txt | 10 +- docs/tutorial03.txt | 9 +- docs/tutorial04.txt | 32 +- docs/url_dispatch.txt | 113 +++++- docs/webdesign.txt | 53 +++ 43 files changed, 2467 insertions(+), 534 deletions(-) create mode 100644 docs/databrowse.txt create mode 100644 docs/man/django-admin.1 create mode 100644 docs/webdesign.txt (limited to 'docs') diff --git a/docs/add_ons.txt b/docs/add_ons.txt index 9809cf46f8..ffc4f7420f 100644 --- a/docs/add_ons.txt +++ b/docs/add_ons.txt @@ -6,8 +6,16 @@ Django aims to follow Python's `"batteries included" philosophy`_. It ships with a variety of extra, optional tools that solve common Web-development problems. -This code lives in ``django/contrib`` in the Django distribution. Here's a -rundown of the packages in ``contrib``: +This code lives in ``django/contrib`` in the Django distribution. This document +gives a rundown of the packages in ``contrib``, along with any dependencies +those packages have. + +.. admonition:: Note + + For most of these add-ons -- specifically, the add-ons that include either + models or template tags -- you'll need to add the package name (e.g., + ``'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 @@ -17,7 +25,9 @@ admin The automatic Django administrative interface. For more information, see `Tutorial 2`_. -.. _Tutorial 2: ../tutorial2/ +.. _Tutorial 2: ../tutorial02/ + +Requires the auth_ and contenttypes_ contrib packages to be installed. auth ==== @@ -137,6 +147,8 @@ See the `flatpages documentation`_. .. _flatpages documentation: ../flatpages/ +Requires the sites_ contrib package to be installed as well. + localflavor =========== @@ -147,13 +159,20 @@ contains a ``USZipCodeField`` that you can use to validate U.S. zip codes. markup ====== -A collection of template filters that implement these common markup languages: +A collection of template filters that implement common markup languages: + + * ``textile`` -- implements `Textile`_ + * ``markdown`` -- implements `Markdown`_ + * ``restructuredtext`` -- implements `ReST (ReStructured Text)`_ - * `Textile`_ - * `Markdown`_ - * `ReST (ReStructured Text)`_ +In each case, the filter expects formatted markup as a string and returns a +string representing the marked-up text. For example, the ``textile`` filter +converts text that is marked-up in Textile format to HTML. -For documentation, read the source code in django/contrib/markup/templatetags/markup.py. +To activate these filters, add ``'django.contrib.markup'`` to your +``INSTALLED_APPS`` setting. Once you've done that, use ``{% load markup %}`` in +a template, and you'll have access to these filters. For more documentation, +read the source code in django/contrib/markup/templatetags/markup.py. .. _Textile: http://en.wikipedia.org/wiki/Textile_%28markup_language%29 .. _Markdown: http://en.wikipedia.org/wiki/Markdown diff --git a/docs/api_stability.txt b/docs/api_stability.txt index 508336e0ef..cfaffeac6b 100644 --- a/docs/api_stability.txt +++ b/docs/api_stability.txt @@ -100,14 +100,14 @@ change: .. _caching: ../cache/ .. _custom template tags and libraries: ../templates_python/ -.. _database lookup: ../db_api/ -.. _django-admin utility: ../django_admin/ +.. _database lookup: ../db-api/ +.. _django-admin utility: ../django-admin/ .. _fastcgi integration: ../fastcgi/ .. _flatpages: ../flatpages/ .. _generic views: ../generic_views/ .. _internationalization: ../i18n/ .. _legacy database integration: ../legacy_databases/ -.. _model definition: ../model_api/ +.. _model definition: ../model-api/ .. _mod_python integration: ../modpython/ .. _redirects: ../redirects/ .. _request/response objects: ../request_response/ diff --git a/docs/authentication.txt b/docs/authentication.txt index aff336f67a..972ca42073 100644 --- a/docs/authentication.txt +++ b/docs/authentication.txt @@ -144,7 +144,7 @@ custom methods: Raises ``django.contrib.auth.models.SiteProfileNotAvailable`` if the current site doesn't allow profiles. -.. _Django model: ../model_api/ +.. _Django model: ../model-api/ .. _DEFAULT_FROM_EMAIL: ../settings/#default-from-email Manager functions @@ -161,8 +161,8 @@ The ``User`` model has a custom manager that has the following helper functions: * ``make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')`` Returns a random password with the given length and given string of allowed characters. (Note that the default value of ``allowed_chars`` - doesn't contain ``"I"`` or letters that look like it, to avoid user - confusion. + doesn't contain letters that can cause user confusion, including + ``1``, ``I`` and ``0``). Basic usage ----------- @@ -204,9 +204,12 @@ The ``password`` attribute of a ``User`` object is a string in this format:: That's hashtype, salt and hash, separated by the dollar-sign character. -Hashtype is either ``sha1`` (default) or ``md5`` -- the algorithm used to -perform a one-way hash of the password. Salt is a random string used to salt -the raw password to create the hash. +Hashtype is either ``sha1`` (default), ``md5`` or ``crypt`` -- the algorithm +used to perform a one-way hash of the password. Salt is a random string used +to salt the raw password to create the hash. Note that the ``crypt`` method is +only supported on platforms that have the standard Python ``crypt`` module +available, and ``crypt`` support is only available in the Django development +version. For example:: @@ -387,14 +390,15 @@ introduced in Python 2.4:: ``login_required`` does the following: - * If the user isn't logged in, redirect to ``/accounts/login/``, passing - the current absolute URL in the query string as ``next``. For example: + * If the user isn't logged in, redirect to ``settings.LOGIN_URL`` + (``/accounts/login/`` by default), passing the current absolute URL + in the query string as ``next``. For example: ``/accounts/login/?next=/polls/3/``. * If the user is logged in, execute the view normally. The view code is free to assume the user is logged in. -Note that you'll need to map the appropriate Django view to ``/accounts/login/``. -To do this, add the following line to your URLconf:: +Note that you'll need to map the appropriate Django view to ``settings.LOGIN_URL``. +For example, using the defaults, add the following line to your URLconf:: (r'^accounts/login/$', 'django.contrib.auth.views.login'), @@ -405,9 +409,9 @@ Here's what ``django.contrib.auth.views.login`` does: * If called via ``POST``, it tries to log the user in. If login is successful, the view redirects to the URL specified in ``next``. If - ``next`` isn't provided, it redirects to ``/accounts/profile/`` (which is - currently hard-coded). If login isn't successful, it redisplays the login - form. + ``next`` isn't provided, it redirects to ``settings.LOGIN_REDIRECT_URL`` + (which defaults to ``/accounts/profile/``). If login isn't successful, + it redisplays the login form. It's your responsibility to provide the login form in a template called ``registration/login.html`` by default. This template gets passed three @@ -487,7 +491,7 @@ Logs a user out, then redirects to the login page. **Optional arguments:** * ``login_url``: The URL of the login page to redirect to. This - will default to ``/accounts/login/`` if not supplied. + will default to ``settings.LOGIN_URL`` if not supplied. ``django.contrib.auth.views.password_change`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -569,7 +573,7 @@ successful login. **Optional arguments:** * ``login_url``: The URL of the login page to redirect to. This - will default to ``/accounts/login/`` if not supplied. + will default to ``settings.LOGIN_URL`` if not supplied. Built-in manipulators --------------------- @@ -636,7 +640,7 @@ Note that ``user_passes_test`` does not automatically check that the ``User`` is not anonymous. ``user_passes_test()`` takes an optional ``login_url`` argument, which lets you -specify the URL for your login page (``/accounts/login/`` by default). +specify the URL for your login page (``settings.LOGIN_URL`` by default). Example in Python 2.3 syntax:: @@ -680,7 +684,7 @@ parameter. Example:: my_view = permission_required('polls.can_vote', login_url='/loginpage/')(my_view) As in the ``login_required`` decorator, ``login_url`` defaults to -``'/accounts/login/'``. +``settings.LOGIN_URL``. Limiting access to generic views -------------------------------- @@ -726,7 +730,7 @@ Django developers are currently discussing. Default permissions ------------------- -Three basic permissions -- add, create and delete -- are automatically created +Three basic permissions -- add, change and delete -- are automatically created for each Django model that has a ``class Admin`` set. Behind the scenes, these permissions are added to the ``auth_permission`` database table when you run ``manage.py syncdb``. @@ -757,7 +761,7 @@ This example model creates three custom permissions:: The only thing this does is create those extra permissions when you run ``syncdb``. -.. _model Meta attribute: ../model_api/#meta-options +.. _model Meta attribute: ../model-api/#meta-options API reference ------------- diff --git a/docs/cache.txt b/docs/cache.txt index 054d99819d..e245e100e7 100644 --- a/docs/cache.txt +++ b/docs/cache.txt @@ -66,10 +66,19 @@ deleting arbitrary data in the cache. All data is stored directly in memory, so there's no overhead of database or filesystem usage. After installing Memcached itself, you'll need to install the Memcached Python -bindings. They're in a single Python module, memcache.py, available at -ftp://ftp.tummy.com/pub/python-memcached/ . If that URL is no longer valid, -just go to the Memcached Web site (http://www.danga.com/memcached/) and get the -Python bindings from the "Client APIs" section. +bindings. Two versions of this are available. Choose and install *one* of the +following modules: + + * The fastest available option is a module called ``cmemcache``, available + at http://gijsbert.org/cmemcache/ . (This module is only compatible with + the Django development version. Django 0.96 is only compatible with the + second option, below.) + + * If you can't install ``cmemcache``, you can install ``python-memcached``, + available at ftp://ftp.tummy.com/pub/python-memcached/ . If that URL is + no longer valid, just go to the Memcached Web site + (http://www.danga.com/memcached/) and get the Python bindings from the + "Client APIs" section. To use Memcached with Django, set ``CACHE_BACKEND`` to ``memcached://ip:port/``, where ``ip`` is the IP address of the Memcached diff --git a/docs/contributing.txt b/docs/contributing.txt index 1d2b635b76..31409f27bd 100644 --- a/docs/contributing.txt +++ b/docs/contributing.txt @@ -279,6 +279,15 @@ Please follow these coding standards when writing code for inclusion in Django: * Mark all strings for internationalization; see the `i18n documentation`_ for details. + * Please don't put your name in the code you contribute. Our policy is to + keep contributors' names in the ``AUTHORS`` file distributed with Django + -- not scattered throughout the codebase itself. Feel free to include a + change to the ``AUTHORS`` file in your patch if you make more than a + single trivial change. + +Template style +-------------- + * In Django template code, put one (and only one) space between the curly brackets and the tag contents. @@ -290,6 +299,9 @@ Please follow these coding standards when writing code for inclusion in Django: {{foo}} +View style +---------- + * In Django views, the first parameter in a view function should be called ``request``. @@ -303,11 +315,72 @@ Please follow these coding standards when writing code for inclusion in Django: def my_view(req, foo): # ... - * Please don't put your name in the code you contribute. Our policy is to - keep contributors' names in the ``AUTHORS`` file distributed with Django - -- not scattered throughout the codebase itself. Feel free to include a - change to the ``AUTHORS`` file in your patch if you make more than a - single trivial change. +Model style +----------- + + * Field names should be all lowercase, using underscores instead of + camelCase. + + Do this:: + + class Person(models.Model): + first_name = models.CharField(maxlength=20) + last_name = models.CharField(maxlength=40) + + Don't do this:: + + class Person(models.Model): + FirstName = models.CharField(maxlength=20) + Last_Name = models.CharField(maxlength=40) + + * The ``class Meta`` should appear *after* the fields are defined, with + a single blank line separating the fields and the class definition. + + Do this:: + + class Person(models.Model): + first_name = models.CharField(maxlength=20) + last_name = models.CharField(maxlength=40) + + class Meta: + verbose_name_plural = 'people' + + Don't do this:: + + class Person(models.Model): + first_name = models.CharField(maxlength=20) + last_name = models.CharField(maxlength=40) + class Meta: + verbose_name_plural = 'people' + + Don't do this, either:: + + class Person(models.Model): + class Meta: + verbose_name_plural = 'people' + + first_name = models.CharField(maxlength=20) + last_name = models.CharField(maxlength=40) + + * The order of model inner classes and standard methods should be as + follows (noting that these are not all required): + + * All database fields + * ``class Meta`` + * ``class Admin`` + * ``def __str__()`` + * ``def save()`` + * ``def get_absolute_url()`` + * Any custom methods + + * If ``choices`` is defined for a given model field, define the choices as + a tuple of tuples, with an all-uppercase name, either near the top of the + model module or just above the model class. Example:: + + GENDER_CHOICES = ( + ('M', 'Male'), + ('F', 'Female'), + ) Committing code =============== @@ -396,10 +469,11 @@ To run the tests, ``cd`` to the ``tests/`` directory and type:: ./runtests.py --settings=path.to.django.settings Yes, the unit tests need a settings module, but only for database connection -info -- the ``DATABASE_ENGINE``, ``DATABASE_USER`` and ``DATABASE_PASSWORD``. -You will also need a ``ROOT_URLCONF`` setting (its value is ignored; it just -needs to be present) and a ``SITE_ID`` setting (any integer value will do) in -order for all the tests to pass. +info -- the ``DATABASE_NAME`` (required, but will be ignored), +``DATABASE_ENGINE``, ``DATABASE_USER`` and ``DATABASE_PASSWORD`` settings. You +will also need a ``ROOT_URLCONF`` setting (its value is ignored; it just needs +to be present) and a ``SITE_ID`` setting (any integer value will do) in order +for all the tests to pass. The unit tests will not touch your existing databases; they create a new database, called ``django_test_db``, which is deleted when the tests are diff --git a/docs/databases.txt b/docs/databases.txt index 3545b58d47..b73f39843c 100644 --- a/docs/databases.txt +++ b/docs/databases.txt @@ -69,9 +69,12 @@ For now, InnoDB is probably your best choice. MySQLdb ------- -`MySQLdb`_ is the Python interface to MySQL. 1.2.1 is the first version that -has support for MySQL 4.1 and newer. If you are trying to use an older version -of MySQL, then 1.2.0 *might* work for you. +`MySQLdb`_ is the Python interface to MySQL. Version 1.2.1p2 or later is +required for full MySQL support in Django. Earlier versions will not work with +the ``mysql`` backend. + +If you are trying to use an older version of MySQL and the ``mysql_old`` +backend, then 1.2.0 *might* work for you. .. _MySQLdb: http://sourceforge.net/projects/mysql-python diff --git a/docs/databrowse.txt b/docs/databrowse.txt new file mode 100644 index 0000000000..9c03e7e4ea --- /dev/null +++ b/docs/databrowse.txt @@ -0,0 +1,60 @@ +========== +Databrowse +========== + +Databrowse is a Django application that lets you browse your data. + +As the Django admin dynamically creates an admin interface by introspecting +your models, Databrowse dynamically creates a rich, browsable Web site by +introspecting your models. + +.. admonition:: Note + + Databrowse is **very** new and is currently under active development. It + may change substantially before the next Django release. + + With that said, it's easy to use, and it doesn't require writing any + code. So you can play around with it today, with very little investment in + time or coding. + +How to use Databrowse +===================== + + 1. Point Django at the default Databrowse templates. There are two ways to + do this: + + * Add ``'django.contrib.databrowse'`` to your ``INSTALLED_APPS`` + setting. This will work if your ``TEMPLATE_LOADERS`` setting includes + the ``app_directories`` template loader (which is the case by + default). See the `template loader docs`_ for more. + + * Otherwise, determine the full filesystem path to the + ``django/contrib/databrowse/templates`` directory, and add that + directory to your ``TEMPLATE_DIRS`` setting. + + 2. Register a number of models with the Databrowse site:: + + from django.contrib import databrowse + + databrowse.site.register(SomeModel) + databrowse.site.register(SomeOtherModel) + + Note that you should register the model *classes*, not instances. + + It doesn't matter where you put this, as long as it gets executed at + some point. A good place for it is in your URLconf file (``urls.py``). + + 3. Change your URLconf to import the ``databrowse`` module:: + + from django.contrib import databrowse + + ...and add the following line to your URLconf:: + + (r'^databrowse/(.*)', databrowse.site.root), + + The prefix doesn't matter -- you can use ``databrowse/`` or ``db/`` or + whatever you'd like. + + 4. Run the Django server and visit ``/databrowse/`` in your browser. + +.. _template loader docs: ../templates_python/#loader-types diff --git a/docs/db-api.txt b/docs/db-api.txt index 64db3def96..e7b8183f6c 100644 --- a/docs/db-api.txt +++ b/docs/db-api.txt @@ -6,7 +6,7 @@ Once you've created your `data models`_, Django automatically gives you a database-abstraction API that lets you create, retrieve, update and delete objects. This document explains that API. -.. _`data models`: ../model_api/ +.. _`data models`: ../model-api/ Throughout this reference, we'll refer to the following models, which comprise a weblog application:: @@ -85,7 +85,7 @@ There's no way to tell what the value of an ID will be before you call unless you explicitly specify ``primary_key=True`` on a field. See the `AutoField documentation`_.) -.. _AutoField documentation: ../model_api/#autofield +.. _AutoField documentation: ../model-api/#autofield Explicitly specifying auto-primary-key values ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -112,7 +112,7 @@ the previous record in the database:: b4 = Blog(id=3, name='Not Cheddar', tagline='Anything but cheese.') b4.save() # Overrides the previous blog with ID=3! -See _`How Django knows to UPDATE vs. INSERT`, below, for the reason this +See `How Django knows to UPDATE vs. INSERT`_, below, for the reason this happens. Explicitly specifying auto-primary-key values is mostly useful for bulk-saving @@ -134,6 +134,15 @@ the database until you explicitly call ``save()``. The ``save()`` method has no return value. +Updating ``ForeignKey`` fields works exactly the same way; simply assign an +object of the right type to the field in question:: + + joe = Author.objects.create(name="Joe") + entry.author = joe + entry.save() + +Django will complain if you try to assign an object of the wrong type. + How Django knows to UPDATE vs. INSERT ------------------------------------- @@ -143,8 +152,8 @@ or ``UPDATE`` SQL statements. Specifically, when you call ``save()``, Django follows this algorithm: * If the object's primary key attribute is set to a value that evaluates to - ``True`` (i.e., a value other than ``None`` or the empty string), Django - executes a ``SELECT`` query to determine whether a record with the given + ``True`` (i.e., a value other than ``None`` or the empty string), Django + executes a ``SELECT`` query to determine whether a record with the given primary key already exists. * If the record with the given primary key does already exist, Django executes an ``UPDATE`` query. @@ -379,7 +388,7 @@ The lookup parameters (``**kwargs``) should be in the format described in `Field lookups`_ below. Multiple parameters are joined via ``AND`` in the underlying SQL statement, and the whole thing is enclosed in a ``NOT()``. -This example excludes all entries whose ``pub_date`` is the current date/time +This example excludes all entries whose ``pub_date`` is later than 2005-1-3 AND whose ``headline`` is "Hello":: Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3), headline='Hello') @@ -389,8 +398,8 @@ In SQL terms, that evaluates to:: SELECT ... WHERE NOT (pub_date > '2005-1-3' AND headline = 'Hello') -This example excludes all entries whose ``pub_date`` is the current date/time -OR whose ``headline`` is "Hello":: +This example excludes all entries whose ``pub_date`` is later than 2005-1-3 +AND whose headline is NOT "Hello":: Entry.objects.exclude(pub_date__gt=datetime.date(2005, 1, 3)).exclude(headline='Hello') @@ -525,19 +534,19 @@ Examples:: [datetime.datetime(2005, 3, 20), datetime.datetime(2005, 2, 20)] >>> Entry.objects.filter(headline__contains='Lennon').dates('pub_date', 'day') [datetime.datetime(2005, 3, 20)] - + ``none()`` ~~~~~~~~~~ **New in Django development version** -Returns an ``EmptyQuerySet`` -- a ``QuerySet`` that always evaluates to +Returns an ``EmptyQuerySet`` -- a ``QuerySet`` that always evaluates to an empty list. This can be used in cases where you know that you should return an empty result set and your caller is expecting a ``QuerySet`` object (instead of returning an empty list, for example.) Examples:: - + >>> Entry.objects.none() [] @@ -589,7 +598,7 @@ related ``Person`` *and* the related ``City``:: p = b.author # Doesn't hit the database. c = p.hometown # Doesn't hit the database. - sv = Book.objects.get(id=4) # No select_related() in this example. + b = Book.objects.get(id=4) # No select_related() in this example. p = b.author # Hits the database. c = p.hometown # Hits the database. @@ -610,7 +619,7 @@ follow:: c = p.hometown # Requires a database call. The ``depth`` argument is new in the Django development version. - + ``extra(select=None, where=None, params=None, tables=None)`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -714,7 +723,7 @@ QuerySet methods that do not return QuerySets The following ``QuerySet`` methods evaluate the ``QuerySet`` and return something *other than* a ``QuerySet``. -These methods do not use a cache (see _`Caching and QuerySets` below). Rather, +These methods do not use a cache (see `Caching and QuerySets`_ below). Rather, they query the database each time they're called. ``get(**kwargs)`` @@ -906,8 +915,8 @@ The database API supports the following lookup types: exact ~~~~~ -Exact match. If the value provided for comparison is ``None``, it will -be interpreted as an SQL ``NULL`` (See isnull_ for more details). +Exact match. If the value provided for comparison is ``None``, it will +be interpreted as an SQL ``NULL`` (See isnull_ for more details). Examples:: @@ -1136,7 +1145,7 @@ such as January 3, July 3, etc. isnull ~~~~~~ -Takes either ``True`` or ``False``, which correspond to SQL queries of +Takes either ``True`` or ``False``, which correspond to SQL queries of ``IS NULL`` and ``IS NOT NULL``, respectively. Example:: @@ -1149,10 +1158,10 @@ SQL equivalent:: .. admonition:: ``__isnull=True`` vs ``__exact=None`` - There is an important difference between ``__isnull=True`` and + There is an important difference between ``__isnull=True`` and ``__exact=None``. ``__exact=None`` will *always* return an empty result - set, because SQL requires that no value is equal to ``NULL``. - ``__isnull`` determines if the field is currently holding the value + set, because SQL requires that no value is equal to ``NULL``. + ``__isnull`` determines if the field is currently holding the value of ``NULL`` without performing a comparison. search @@ -1181,7 +1190,7 @@ The pk lookup shortcut ---------------------- For convenience, Django provides a ``pk`` lookup type, which stands for -"primary_key". +"primary_key". In the example ``Blog`` model, the primary key is the ``id`` field, so these three statements are equivalent:: @@ -1190,14 +1199,14 @@ three statements are equivalent:: Blog.objects.get(id=14) # __exact is implied Blog.objects.get(pk=14) # pk implies id__exact -The use of ``pk`` isn't limited to ``__exact`` queries -- any query term +The use of ``pk`` isn't limited to ``__exact`` queries -- any query term can be combined with ``pk`` to perform a query on the primary key of a model:: # Get blogs entries with id 1, 4 and 7 Blog.objects.filter(pk__in=[1,4,7]) # Get all blog entries with id > 14 - Blog.objects.filter(pk__gt=14) - + Blog.objects.filter(pk__gt=14) + ``pk`` lookups also work across joins. For example, these three statements are equivalent:: @@ -1229,8 +1238,8 @@ whose ``headline`` contains ``'Lennon'``:: Blog.objects.filter(entry__headline__contains='Lennon') -Escaping parenthesis and underscores in LIKE statements -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Escaping percent signs and underscores in LIKE statements +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The field lookups that equate to ``LIKE`` SQL statements (``iexact``, ``contains``, ``icontains``, ``startswith``, ``istartswith``, ``endswith`` @@ -1748,25 +1757,26 @@ Shortcuts As you develop views, you will discover a number of common idioms in the way you use the database API. Django encodes some of these idioms as -shortcuts that can be used to simplify the process of writing views. +shortcuts that can be used to simplify the process of writing views. These +functions are in the ``django.shortcuts`` module. get_object_or_404() ------------------- One common idiom to use ``get()`` and raise ``Http404`` if the -object doesn't exist. This idiom is captured by ``get_object_or_404()``. -This function takes a Django model as its first argument and an -arbitrary number of keyword arguments, which it passes to the manager's +object doesn't exist. This idiom is captured by ``get_object_or_404()``. +This function takes a Django model as its first argument and an +arbitrary number of keyword arguments, which it passes to the manager's ``get()`` function. It raises ``Http404`` if the object doesn't -exist. For example:: - +exist. For example:: + # Get the Entry with a primary key of 3 e = get_object_or_404(Entry, pk=3) -When you provide a model to this shortcut function, the default manager -is used to execute the underlying ``get()`` query. If you don't want to -use the default manager, or you want to search a list of related objects, -you can provide ``get_object_or_404()`` with a manager object, instead. +When you provide a model to this shortcut function, the default manager +is used to execute the underlying ``get()`` query. If you don't want to +use the default manager, or if you want to search a list of related objects, +you can provide ``get_object_or_404()`` with a manager object instead. For example:: # Get the author of blog instance `e` with a name of 'Fred' @@ -1779,8 +1789,8 @@ For example:: get_list_or_404() ----------------- -``get_list_or_404`` behaves the same was as ``get_object_or_404()`` --- except the it uses using ``filter()`` instead of ``get()``. It raises +``get_list_or_404`` behaves the same way as ``get_object_or_404()`` +-- except that it uses ``filter()`` instead of ``get()``. It raises ``Http404`` if the list is empty. Falling back to raw SQL @@ -1801,4 +1811,4 @@ interface to your database. You can access your database via other tools, programming languages or database frameworks; there's nothing Django-specific about your database. -.. _Executing custom SQL: ../model_api/#executing-custom-sql +.. _Executing custom SQL: ../model-api/#executing-custom-sql diff --git a/docs/distributions.txt b/docs/distributions.txt index 63206c535e..4ec265f93c 100644 --- a/docs/distributions.txt +++ b/docs/distributions.txt @@ -47,16 +47,18 @@ Fedora ------ A Django package is available for `Fedora Linux`_, in the "Fedora Extras" -repository. The `current Fedora package`_ is based on Django 0.95.1, and can be -installed by typing ``yum install Django``. +repository. The `current Fedora package`_ is based on Django 0.96, and can be +installed by typing ``yum install Django``. The previous link is for the i386 +binary. Users of other architectures should be able to use that as a starting +point to find their preferred version. .. _Fedora Linux: http://fedora.redhat.com/ -.. _current Fedora package: http://fedoraproject.org/extras/6/i386/repodata/repoview/Django-0-0.95.1-1.fc6.html +.. _current Fedora package: http://download.fedora.redhat.com/pub/fedora/linux/extras/6/i386/repoview/Django.html Gentoo ------ -A Django build is available for `Gentoo Linux`_, and is based on Django 0.95.1. +A Django build is available for `Gentoo Linux`_, and is based on Django 0.96. The `current Gentoo build`_ can be installed by typing ``emerge django``. .. _Gentoo Linux: http://www.gentoo.org/ diff --git a/docs/django-admin.txt b/docs/django-admin.txt index 28e28089cc..d20db7edc9 100644 --- a/docs/django-admin.txt +++ b/docs/django-admin.txt @@ -29,6 +29,9 @@ Generally, when working on a single Django project, it's easier to use ``--settings`` command line option, if you need to switch between multiple Django settings files. +The command-line examples throughout this document use ``django-admin.py`` to +be consistent, but any example can use ``manage.py`` just as well. + Usage ===== @@ -58,7 +61,7 @@ Prints the admin-index template snippet for the given appnames. Use admin-index template snippets if you want to customize the look and feel of your admin's index page. See `Tutorial 2`_ for more information. -.. _Tutorial 2: ../tutorial2/ +.. _Tutorial 2: ../tutorial02/ createcachetable [tablename] ---------------------------- @@ -100,23 +103,24 @@ if you're ever curious to see the full list of defaults. dumpdata [appname appname ...] ------------------------------ -Output to standard output all data in the database associated with the named +Output to standard output all data in the database associated with the named application(s). By default, the database will be dumped in JSON format. If you want the output -to be in another format, use the ``--format`` option (e.g., ``format=xml``). -You may specify any Django serialization backend (including any user specified -serialization backends named in the ``SERIALIZATION_MODULES`` setting). +to be in another format, use the ``--format`` option (e.g., ``format=xml``). +You may specify any Django serialization backend (including any user specified +serialization backends named in the ``SERIALIZATION_MODULES`` setting). The +``--indent`` option can be used to pretty-print the output. If no application name is provided, all installed applications will be dumped. -The output of ``dumpdata`` can be used as input for ``loaddata``. +The output of ``dumpdata`` can be used as input for ``loaddata``. flush ----- -Return the database to the state it was in immediately after syncdb was -executed. This means that all data will be removed from the database, any +Return the database to the state it was in immediately after syncdb was +executed. This means that all data will be removed from the database, any post-synchronization handlers will be re-executed, and the ``initial_data`` fixture will be re-installed. @@ -178,37 +182,37 @@ Django will search in three locations for fixtures: 3. In the literal path named by the fixture Django will load any and all fixtures it finds in these locations that match -the provided fixture names. +the provided fixture names. -If the named fixture has a file extension, only fixtures of that type +If the named fixture has a file extension, only fixtures of that type will be loaded. For example:: django-admin.py loaddata mydata.json - -would only load JSON fixtures called ``mydata``. The fixture extension -must correspond to the registered name of a serializer (e.g., ``json`` or + +would only load JSON fixtures called ``mydata``. The fixture extension +must correspond to the registered name of a serializer (e.g., ``json`` or ``xml``). -If you omit the extension, Django will search all available fixture types +If you omit the extension, Django will search all available fixture types for a matching fixture. For example:: django-admin.py loaddata mydata - + would look for any fixture of any fixture type called ``mydata``. If a fixture directory contained ``mydata.json``, that fixture would be loaded -as a JSON fixture. However, if two fixtures with the same name but different -fixture type are discovered (for example, if ``mydata.json`` and -``mydata.xml`` were found in the same fixture directory), fixture -installation will be aborted, and any data installed in the call to +as a JSON fixture. However, if two fixtures with the same name but different +fixture type are discovered (for example, if ``mydata.json`` and +``mydata.xml`` were found in the same fixture directory), fixture +installation will be aborted, and any data installed in the call to ``loaddata`` will be removed from the database. -The fixtures that are named can include directory components. These +The fixtures that are named can include directory components. These directories will be included in the search path. For example:: django-admin.py loaddata foo/bar/mydata.json - -would search ``/fixtures/foo/bar/mydata.json`` for each installed -application, ``/foo/bar/mydata.json`` for each directory in + +would search ``/fixtures/foo/bar/mydata.json`` for each installed +application, ``/foo/bar/mydata.json`` for each directory in ``FIXTURE_DIRS``, and the literal path ``foo/bar/mydata.json``. Note that the order in which fixture files are processed is undefined. However, @@ -217,16 +221,18 @@ one fixture can reference data in another fixture. If the database backend supports row-level constraints, these constraints will be checked at the end of the transaction. +The ``dumpdata`` command can be used to generate input for ``loaddata``. + .. admonition:: MySQL and Fixtures - Unfortunately, MySQL isn't capable of completely supporting all the + Unfortunately, MySQL isn't capable of completely supporting all the features of Django fixtures. If you use MyISAM tables, MySQL doesn't - support transactions or constraints, so you won't get a rollback if - multiple transaction files are found, or validation of fixture data. - If you use InnoDB tables, you won't be able to have any forward - references in your data files - MySQL doesn't provide a mechanism to - defer checking of row constraints until a transaction is committed. - + support transactions or constraints, so you won't get a rollback if + multiple transaction files are found, or validation of fixture data. + If you use InnoDB tables, you won't be able to have any forward + references in your data files - MySQL doesn't provide a mechanism to + defer checking of row constraints until a transaction is committed. + reset [appname appname ...] --------------------------- Executes the equivalent of ``sqlreset`` for the given appnames. @@ -289,7 +295,7 @@ Serving static files with the development server ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ By default, the development server doesn't serve any static files for your site -(such as CSS files, images, things under ``MEDIA_ROOT_URL`` and so forth). If +(such as CSS files, images, things under ``MEDIA_URL`` and so forth). If you want to configure Django to serve static media, read the `serving static files`_ documentation. @@ -326,7 +332,7 @@ sqlall [appname appname ...] Prints the CREATE TABLE and initial-data SQL statements for the given appnames. -Refer to the description of ``sqlinitialdata`` for an explanation of how to +Refer to the description of ``sqlcustom`` for an explanation of how to specify initial data. sqlclear [appname appname ...] @@ -342,7 +348,7 @@ Prints the custom SQL statements for the given appnames. For each model in each specified app, this command looks for the file ``/sql/.sql``, where ```` is the given appname and ```` is the model's name in lowercase. For example, if you have an -app ``news`` that includes a ``Story`` model, ``sqlinitialdata`` will attempt +app ``news`` that includes a ``Story`` model, ``sqlcustom`` will attempt to read a file ``news/sql/story.sql`` and append it to the output of this command. @@ -366,7 +372,7 @@ Prints the DROP TABLE SQL, then the CREATE TABLE SQL, for the given appnames. sqlsequencereset [appname appname ...] ---------------------------------------------- -Prints the SQL statements for resetting PostgreSQL sequences for the given +Prints the SQL statements for resetting sequences for the given appnames. See http://simon.incutio.com/archive/2004/04/21/postgres for more information. @@ -397,9 +403,10 @@ this command to install the default apps. If you're installing the ``django.contrib.auth`` application, ``syncdb`` will give you the option of creating a superuser immediately. -``syncdb`` will also search for and install any fixture named ``initial_data``. -See the documentation for ``loaddata`` for details on the specification of -fixture data files. +``syncdb`` will also search for and install any fixture named ``initial_data`` +with an appropriate extension (e.g. ``json`` or ``xml``). See the +documentation for ``loaddata`` for details on the specification of fixture +data files. test ---- @@ -471,7 +478,7 @@ Example usage:: django-admin.py dumpdata --indent=4 -Specifies the number of spaces that will be used for indentation when +Specifies the number of spaces that will be used for indentation when pretty-printing output. By default, output will *not* be pretty-printed. Pretty-printing will only be enabled if the indent option is provided. @@ -512,7 +519,8 @@ and `2` is verbose output. ------------ Example usage:: - django-admin.py manage.py --adminmedia=/tmp/new-admin-style/ + + django-admin.py --adminmedia=/tmp/new-admin-style/ Tells Django where to find the various CSS and JavaScript files for the admin interface when running the development server. Normally these files are served diff --git a/docs/documentation.txt b/docs/documentation.txt index bacfb176b1..decb066fa1 100644 --- a/docs/documentation.txt +++ b/docs/documentation.txt @@ -42,25 +42,25 @@ On the Web The most recent version of the Django documentation lives at http://www.djangoproject.com/documentation/ . These HTML pages are generated -automatically from the text files in source control every 15 minutes. That -means they reflect the "latest and greatest" in Django -- they include the very -latest corrections and additions, and they discuss the latest Django features, +automatically from the text files in source control. That means they reflect +the "latest and greatest" in Django -- they include the very latest +corrections and additions, and they discuss the latest Django features, which may only be available to users of the Django development version. (See "Differences between versions" below.) -A key advantage of the Web-based documentation is the comment section at the -bottom of each document. This is an area for anybody to submit changes, -corrections and suggestions about the given document. The Django developers -frequently monitor the comments there and use them to improve the documentation -for everybody. +We encourage you to help improve the docs by submitting changes, corrections +and suggestions in the `ticket system`_. The Django developers actively monitor +the ticket system and use your feedback to improve the documentation for +everybody. -We encourage you to help improve the docs: it's easy! Note, however, that -comments should explicitly relate to the documentation, rather than asking -broad tech-support questions. If you need help with your particular Django -setup, try the `django-users mailing list`_ instead of posting a comment to the -documentation. +Note, however, that tickets should explicitly relate to the documentation, +rather than asking broad tech-support questions. If you need help with your +particular Django setup, try the `django-users mailing list`_ or the +`#django IRC channel`_ instead. +.. _ticket system: http://code.djangoproject.com/simpleticket?component=Documentation .. _django-users mailing list: http://groups.google.com/group/django-users +.. _#django IRC channel: irc://irc.freenode.net/django In plain text ------------- @@ -94,12 +94,10 @@ Formatting The text documentation is written in ReST (ReStructured Text) format. That means it's easy to read but is also formatted in a way that makes it easy to -convert into other formats, such as HTML. If you're interested, the script that -converts the ReST text docs into djangoproject.com's HTML lives at -`djangoproject.com/django_website/apps/docs/parts/build_documentation.py`_ in -the Django Subversion repository. +convert into other formats, such as HTML. If you have the `reStructuredText`_ +library installed, you can use ``rst2html`` to generate your own HTML files. -.. _djangoproject.com/django_website/apps/docs/parts/build_documentation.py: http://code.djangoproject.com/browser/djangoproject.com/django_website/apps/docs/parts/build_documentation.py +.. _reStructuredText: http://docutils.sourceforge.net/rst.html Differences between versions ============================ @@ -134,14 +132,6 @@ We follow this policy: frozen document that says "These docs are frozen for Django version XXX" and links to the current version of that document. - * Once a document is frozen for a Django release, we remove comments from - that page, in favor of having comments on the latest version of that - document. This is for the sake of maintainability and usability, so that - users have one, and only one, place to leave comments on a particular - document. We realize that some people may be stuck on a previous version - of Django, but we believe the usability problems with multiple versions - of a document the outweigh the benefits. - * The `main documentation Web page`_ includes links to documentation for all previous versions. diff --git a/docs/email.txt b/docs/email.txt index 1f4ce4ef42..66948e5294 100644 --- a/docs/email.txt +++ b/docs/email.txt @@ -19,13 +19,23 @@ In two lines:: send_mail('Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False) - + +Mail is sent using the SMTP host and port specified in the `EMAIL_HOST`_ and +`EMAIL_PORT`_ settings. The `EMAIL_HOST_USER`_ and `EMAIL_HOST_PASSWORD`_ +settings, if set, are used to authenticate to the SMTP server, and the +`EMAIL_USE_TLS`_ setting controls whether a secure connection is used. + .. note:: - The character set of email sent with ``django.core.mail`` will be set to + The character set of e-mail sent with ``django.core.mail`` will be set to the value of your `DEFAULT_CHARSET setting`_. - -.. _DEFAULT_CHARSET setting: ../settings/#DEFAULT_CHARSET + +.. _DEFAULT_CHARSET setting: ../settings/#default-charset +.. _EMAIL_HOST: ../settings/#email-host +.. _EMAIL_PORT: ../settings/#email-port +.. _EMAIL_HOST_USER: ../settings/#email-host-user +.. _EMAIL_HOST_PASSWORD: ../settings/#email-host-password +.. _EMAIL_USE_TLS: ../settings/#email-use-tls send_mail() =========== @@ -174,3 +184,72 @@ from the request's POST data, sends that to admin@example.com and redirects to return HttpResponse('Make sure all fields are entered and valid.') .. _Header injection: http://securephp.damonkohler.com/index.php/Email_Injection + +The EmailMessage and SMTPConnection classes +=========================================== + +**New in Django development version** + +Django's ``send_mail()`` and ``send_mass_mail()`` functions are actually thin +wrappers that make use of the ``EmailMessage`` and ``SMTPConnection`` classes +in ``django.core.mail``. If you ever need to customize the way Django sends +e-mail, you can subclass these two classes to suit your needs. + +.. note:: + Not all features of the ``EmailMessage`` class are available through the + ``send_mail()`` and related wrapper functions. If you wish to use advanced + features, such as BCC'ed recipients or multi-part e-mail, you'll need to + create ``EmailMessage`` instances directly. + +In general, ``EmailMessage`` is responsible for creating the e-mail message +itself. ``SMTPConnection`` is responsible for the network connection side of +the operation. This means you can reuse the same connection (an +``SMTPConnection`` instance) for multiple messages. + +The ``EmailMessage`` class is initialized as follows:: + + email = EmailMessage(subject, body, from_email, to, bcc, connection) + +All of these parameters are optional. If ``from_email`` is omitted, the value +from ``settings.DEFAULT_FROM_EMAIL`` is used. Both the ``to`` and ``bcc`` +parameters are lists of addresses, as strings. + +For example:: + + email = EmailMessage('Hello', 'Body goes here', 'from@example.com', + ['to1@example.com', 'to2@example.com'], + ['bcc@example.com']) + +The class has the following methods: + + * ``send()`` sends the message, using either the connection that is + specified in the ``connection`` attribute, or creating a new connection + if none already exists. + + * ``message()`` constructs a ``django.core.mail.SafeMIMEText`` object (a + sub-class of Python's ``email.MIMEText.MIMEText`` class) holding the + message to be sent. If you ever need to extend the `EmailMessage` class, + you'll probably want to override this method to put the content you wish + into the MIME object. + + * ``recipients()`` returns a list of all the recipients of the message, + whether they're recorded in the ``to`` or ``bcc`` attributes. This is + another method you might need to override when sub-classing, because the + SMTP server needs to be told the full list of recipients when the message + is sent. If you add another way to specify recipients in your class, they + need to be returned from this method as well. + +The ``SMTPConnection`` class is initialized with the host, port, username and +password for the SMTP server. If you don't specify one or more of those +options, they are read from your settings file. + +If you're sending lots of messages at once, the ``send_messages()`` method of +the ``SMTPConnection`` class is useful. It takes a list of ``EmailMessage`` +instances (or subclasses) and sends them over a single connection. For example, +if you have a function called ``get_notification_email()`` that returns a +list of ``EmailMessage`` objects representing some periodic e-mail you wish to +send out, you could send this with:: + + connection = SMTPConnection() # Use default settings for connection + messages = get_notification_email() + connection.send_messages(messages) diff --git a/docs/faq.txt b/docs/faq.txt index 33e8ef01b4..bdd8c5360e 100644 --- a/docs/faq.txt +++ b/docs/faq.txt @@ -278,7 +278,7 @@ How do I get started? .. _`Download the code`: http://www.djangoproject.com/download/ .. _`installation guide`: ../install/ -.. _tutorial: ../tutorial1/ +.. _tutorial: ../tutorial01/ .. _documentation: ../ .. _ask questions: http://www.djangoproject.com/community/ @@ -328,8 +328,9 @@ Do I have to use mod_python? Although we recommend mod_python for production use, you don't have to use it, thanks to the fact that Django uses an arrangement called WSGI_. Django can -talk to any WSGI-enabled server. The most common non-mod_python deployment -setup is FastCGI. See `How to use Django with FastCGI`_ for full information. +talk to any WSGI-enabled server. Other non-mod_python deployment setups are +FastCGI, SCGI or AJP. See `How to use Django with FastCGI, SCGI or AJP`_ for +full information. Also, see the `server arrangements wiki page`_ for other deployment strategies. @@ -337,7 +338,7 @@ If you just want to play around and develop things on your local computer, use the development Web server that comes with Django. Things should Just Work. .. _WSGI: http://www.python.org/peps/pep-0333.html -.. _How to use Django with FastCGI: ../fastcgi/ +.. _How to use Django with FastCGI, SCGI or AJP: ../fastcgi/ .. _server arrangements wiki page: http://code.djangoproject.com/wiki/ServerArrangements How do I install mod_python on Windows? @@ -381,9 +382,9 @@ Why do I get an error about importing DJANGO_SETTINGS_MODULE? Make sure that: * The environment variable DJANGO_SETTINGS_MODULE is set to a fully-qualified - Python module (i.e. "mysite.settings.main"). + Python module (i.e. "mysite.settings"). - * Said module is on ``sys.path`` (``import mysite.settings.main`` should work). + * Said module is on ``sys.path`` (``import mysite.settings`` should work). * The module doesn't contain syntax errors (of course). @@ -511,7 +512,7 @@ type, create an initial data file and put something like this in it:: As explained in the `SQL initial data file`_ documentation, this SQL file can contain arbitrary SQL, so you can make any sorts of changes you need to make. -.. _SQL initial data file: ../model_api/#providing-initial-sql-data +.. _SQL initial data file: ../model-api/#providing-initial-sql-data Why is Django leaking memory? ----------------------------- diff --git a/docs/fastcgi.txt b/docs/fastcgi.txt index 5ecaac8666..81888bba76 100644 --- a/docs/fastcgi.txt +++ b/docs/fastcgi.txt @@ -1,11 +1,17 @@ -============================== -How to use Django with FastCGI -============================== +=========================================== +How to use Django with FastCGI, SCGI or AJP +=========================================== Although the `current preferred setup`_ for running Django is Apache_ with -`mod_python`_, many people use shared hosting, on which FastCGI is the only -viable option. In some setups, FastCGI also allows better security -- and, -possibly, better performance -- than mod_python. +`mod_python`_, many people use shared hosting, on which protocols such as +FastCGI, SCGI or AJP are the only viable options. In some setups, these protocols +also allow better security -- and, possibly, better performance -- than mod_python. + +.. admonition:: Note + + This document primarily focuses on FastCGI. Other protocols, such as SCGI + and AJP, are also supported, through the ``flup`` Python package. See the + "Protocols" section below for specifics about SCGI and AJP. Essentially, FastCGI is an efficient way of letting an external application serve pages to a Web server. The Web server delegates the incoming Web requests @@ -74,10 +80,26 @@ your ``manage.py`` is), and then run ``manage.py`` with the ``runfcgi`` option:: If you specify ``help`` as the only option after ``runfcgi``, it'll display a list of all the available options. -You'll need to specify either a ``socket`` or both ``host`` and ``port``. Then, -when you set up your Web server, you'll just need to point it at the host/port +You'll need to specify either a ``socket``, ``protocol`` or both ``host`` and ``port``. +Then, when you set up your Web server, you'll just need to point it at the host/port or socket you specified when starting the FastCGI server. +Protocols +--------- + +Django supports all the protocols that flup_ does, namely fastcgi_, `SCGI`_ and +`AJP1.3`_ (the Apache JServ Protocol, version 1.3). Select your preferred +protocol by using the ``protocol=`` option with +``./manage.py runfcgi`` -- where ```` may be one of: ``fcgi`` +(the default), ``scgi`` or ``ajp``. For example:: + + ./manage.py runfcgi --protocol=scgi + +.. _flup: http://www.saddi.com/software/flup/ +.. _fastcgi: http://www.fastcgi.com/ +.. _SCGI: http://python.ca/scgi/protocol.txt +.. _AJP1.3: http://tomcat.apache.org/connectors-doc/ajp/ajpv13a.html + Examples -------- @@ -181,7 +203,7 @@ This is probably the most common case, if you're using Django's admin site:: DocumentRoot /home/user/public_html Alias /media /home/user/python/django/contrib/admin/media RewriteEngine On - RewriteRule ^/(media.*)$ /$1 [QSA,L] + RewriteRule ^/(media.*)$ /$1 [QSA,L,PT] RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^/(.*)$ /mysite.fcgi/$1 [QSA,L] diff --git a/docs/flatpages.txt b/docs/flatpages.txt index cb910e812d..1422f16b6b 100644 --- a/docs/flatpages.txt +++ b/docs/flatpages.txt @@ -84,9 +84,9 @@ Flatpages are represented by a standard `Django model`_, which lives in `django/contrib/flatpages/models.py`_. You can access flatpage objects via the `Django database API`_. -.. _Django model: ../model_api/ +.. _Django model: ../model-api/ .. _django/contrib/flatpages/models.py: http://code.djangoproject.com/browser/django/trunk/django/contrib/flatpages/models.py -.. _Django database API: ../db_api/ +.. _Django database API: ../db-api/ Flatpage templates ================== diff --git a/docs/forms.txt b/docs/forms.txt index f76f6d27ef..f6cb55a3f6 100644 --- a/docs/forms.txt +++ b/docs/forms.txt @@ -517,10 +517,10 @@ to put punctuation at the end of your validation messages. When are validators called? --------------------------- -After a form has been submitted, Django first checks to see that all the -required fields are present and non-empty. For each field that passes that -test *and if the form submission contained data* for that field, all the -validators for that field are called in turn. The emphasized portion in the +After a form has been submitted, Django validates each field in turn. First, +if the field is required, Django checks that it is present and non-empty. Then, +if that test passes *and the form submission contained data* for that field, all +the validators for that field are called in turn. The emphasized portion in the last sentence is important: if a form field is not submitted (because it contains no data -- which is normal HTML behavior), the validators are not run against the field. @@ -567,6 +567,7 @@ check for the given property: * isValidANSIDate * isValidANSITime * isValidEmail + * isValidFloat * isValidImage * isValidImageURL * isValidPhone @@ -615,15 +616,19 @@ fails. If no message is passed in, a default message is used. ``other_value``, then the validators in ``validator_list`` are all run against the current field. +``RequiredIfOtherFieldGiven`` + Takes a field name of the current field is only required if the other + field has a value. + +``RequiredIfOtherFieldsGiven`` + Similar to ``RequiredIfOtherFieldGiven``, except that it takes a list of + field names and if any one of the supplied fields has a value provided, + the current field being validated is required. + ``RequiredIfOtherFieldNotGiven`` Takes the name of the other field and this field is only required if the other field has no value. -``RequiredIfOtherFieldsNotGiven`` - Similar to ``RequiredIfOtherFieldNotGiven``, except that it takes a list - of field names and if any one of the supplied fields does not have a value - provided, the field being validated is required. - ``RequiredIfOtherFieldEquals`` and ``RequiredIfOtherFieldDoesNotEqual`` Each of these validator classes takes a field name and a value (in that order). If the given field does (or does not have, in the latter case) the @@ -650,8 +655,8 @@ fails. If no message is passed in, a default message is used. ``NumberIsInRange`` Takes two boundary numbers, ``lower`` and ``upper``, and checks that the field is greater than ``lower`` (if given) and less than ``upper`` (if - given). - + given). + Both checks are inclusive. That is, ``NumberIsInRange(10, 20)`` will allow values of both 10 and 20. This validator only checks numeric values (e.g., float and integer values). @@ -660,10 +665,10 @@ fails. If no message is passed in, a default message is used. Takes an integer argument and when called as a validator, checks that the field being validated is a power of the integer. -``IsValidFloat`` +``IsValidDecimal`` Takes a maximum number of digits and number of decimal places (in that - order) and validates whether the field is a float with less than the - maximum number of digits and decimal place. + order) and validates whether the field is a decimal with no more than the + maximum number of digits and decimal places. ``MatchesRegularExpression`` Takes a regular expression (a string) as a parameter and validates the @@ -691,5 +696,5 @@ fails. If no message is passed in, a default message is used. document for more details). .. _`generic views`: ../generic_views/ -.. _`models API`: ../model_api/ +.. _`models API`: ../model-api/ .. _settings: ../settings/ diff --git a/docs/generic_views.txt b/docs/generic_views.txt index 7659a428c5..359a82506a 100644 --- a/docs/generic_views.txt +++ b/docs/generic_views.txt @@ -44,7 +44,7 @@ simple weblog app that drives the blog on djangoproject.com:: (r'^(?P\d{4})/(?P[a-z]{3})/(?P\w{1,2})/$', 'archive_day', info_dict), (r'^(?P\d{4})/(?P[a-z]{3})/$', 'archive_month', info_dict), (r'^(?P\d{4})/$', 'archive_year', info_dict), - (r'^/?$', 'archive_index', info_dict), + (r'^$', 'archive_index', info_dict), ) As you can see, this URLconf defines a few options in ``info_dict``. @@ -71,7 +71,7 @@ are first evaluated, so if you want to pass in a QuerySet via ``extra_context`` that is always fresh you need to wrap it in a function or lambda that returns the QuerySet. -.. _database API docs: ../db_api/ +.. _database API docs: ../db-api/ "Simple" generic views ====================== @@ -99,6 +99,9 @@ which is a dictionary of the parameters captured in the URL. dictionary is callable, the generic view will call it just before rendering the template. + * ``mimetype``: The MIME type to use for the resulting document. Defaults + to the value of the ``DEFAULT_CONTENT_TYPE`` setting. + **Example:** Given the following URL patterns:: @@ -222,7 +225,7 @@ In addition to ``extra_context``, the template's context will be: by ``date_field``. For example, if ``num_latest`` is ``10``, then ``latest`` will be a list of the latest 10 objects in ``queryset``. -.. _RequestContext docs: ../templates_python/#subclassing-context-djangocontext +.. _RequestContext docs: ../templates_python/#subclassing-context-requestcontext ``django.views.generic.date_based.archive_year`` ------------------------------------------------ diff --git a/docs/i18n.txt b/docs/i18n.txt index 4a05e53ddf..27abadacc9 100644 --- a/docs/i18n.txt +++ b/docs/i18n.txt @@ -175,7 +175,7 @@ class, though:: verbose_name = _('my thing') verbose_name_plural = _('mythings') -.. _Django models: ../model_api/ +.. _Django models: ../model-api/ Pluralization ~~~~~~~~~~~~~ @@ -236,7 +236,7 @@ To pluralize, specify both the singular and plural forms with the ``{% plural %}`` tag, which appears within ``{% blocktrans %}`` and ``{% endblocktrans %}``. Example:: - {% blocktrans count list|count as counter %} + {% blocktrans count list|length as counter %} There is only one {{ name }} object. {% plural %} There are {{ counter }} {{ name }} objects. @@ -310,7 +310,7 @@ To create or update a message file, run this command:: ...where ``de`` is the language code for the message file you want to create. The language code, in this case, is in locale format. For example, it's -``pt_BR`` for Brazilian and ``de_AT`` for Austrian German. +``pt_BR`` for Brazilian Portugese and ``de_AT`` for Austrian German. The script should be run from one of three places: @@ -463,8 +463,8 @@ following this algorithm: Notes: * In each of these places, the language preference is expected to be in the - standard language format, as a string. For example, Brazilian is - ``pt-br``. + standard language format, as a string. For example, Brazilian Portugese + is ``pt-br``. * If a base language is available but the sublanguage specified is not, Django uses the base language. For example, if a user specifies ``de-at`` (Austrian German) but Django only has ``de`` available, Django uses diff --git a/docs/install.txt b/docs/install.txt index 3eede02af0..4f5a4bbe31 100644 --- a/docs/install.txt +++ b/docs/install.txt @@ -11,8 +11,8 @@ Being a Python Web framework, Django requires Python. It works with any Python version 2.3 and higher. -Get Python at www.python.org. If you're running Linux or Mac OS X, you probably -already have it installed. +Get Python at http://www.python.org. If you're running Linux or Mac OS X, you +probably already have it installed. Install Apache and mod_python ============================= @@ -45,19 +45,20 @@ Get your database running ========================= If you plan to use Django's database API functionality, you'll need to -make sure a database server is running. Django works with PostgreSQL_ -(recommended), MySQL_ and SQLite_. +make sure a database server is running. Django works with PostgreSQL_, +MySQL_ and SQLite_. Additionally, you'll need to make sure your Python database bindings are installed. -* If you're using PostgreSQL, you'll need the psycopg_ package (version 2 is - recommended with ``postgresql_psycopg2`` backend, version 1.1 works also with the - ``postgresql``` backend). - +* If you're using PostgreSQL, you'll need the psycopg_ package. Django supports + both version 1 and 2. (When you configure Django's database layer, specify + either ``postgresql`` [for version 1] or ``postgresql_psycopg2`` [for version 2].) + If you're on Windows, check out the unofficial `compiled Windows version`_. - + * If you're using MySQL, you'll need MySQLdb_, version 1.2.1p2 or higher. + You will also want to read the database-specific notes for the `MySQL backend`_. * If you're using SQLite, you'll need pysqlite_. Use version 2.0.3 or higher. @@ -69,6 +70,36 @@ installed. .. _MySQLdb: http://sourceforge.net/projects/mysql-python .. _SQLite: http://www.sqlite.org/ .. _pysqlite: http://initd.org/tracker/pysqlite +.. _MySQL backend: ../databases/ + +Remove any old versions of Django +================================= + +If you are upgrading your installation of Django from a previous version, +you will need to uninstall the old Django version before installing the +new version. + +If you installed Django using ``setup.py install``, uninstalling +is as simple as deleting the ``django`` directory from your Python +``site-packages``. + +If you installed Django from a Python Egg, remove the Django ``.egg`` file, +and remove the reference to the egg in the file named ``easy-install.pth``. +This file should also be located in your ``site-packages`` directory. + +.. admonition:: Where are my ``site-packages`` stored? + + The location of the ``site-packages`` directory depends on the operating + system, and the location in which Python was installed. However, the + following locations are common: + + * If you're using Linux: ``/usr/lib/python2.X/site-packages`` + + * If you're using Windows: ``C:\Python2.X\lib\site-packages`` + + * If you're using MacOSX: ``/Library/Python2.X/site-packages`` or + ``/Library/Frameworks/Python.framework/Versions/2.X/lib/python2.X/site-packages/`` + (in later releases). Install the Django code ======================= @@ -86,25 +117,17 @@ Installing the official version Distribution-provided packages will typically allow for automatic installation of dependancies and easy upgrade paths. - 2. Download Django-0.95.tar.gz from our `download page`_. - - 3. ``tar xzvf Django-0.95.tar.gz`` + 2. Download the latest release from our `download page`_. - 4. ``cd Django-0.95`` + 3. Untar the downloaded file (e.g. ``tar xzvf Django-NNN.tar.gz``). - 5. ``sudo python setup.py install`` + 4. Change into the downloaded directory (e.g. ``cd Django-NNN``). -Note that the last command will automatically download and install setuptools_ -if you don't already have it installed. This requires a working Internet -connection and may cause problems on Python 2.5. If you run into problems, -try using our development version by following the instructions below. The -development version no longer uses setuptools nor requires an Internet -connection. + 5. Run ``sudo python setup.py install``. The command will install Django in your Python installation's ``site-packages`` directory. -.. _setuptools: http://peak.telecommunity.com/DevCenter/setuptools .. _distribution specific notes: ../distributions/ Installing the development version diff --git a/docs/legacy_databases.txt b/docs/legacy_databases.txt index 8230c11f61..ca3927e52f 100644 --- a/docs/legacy_databases.txt +++ b/docs/legacy_databases.txt @@ -9,7 +9,7 @@ utilities to automate as much of this process as possible. This document assumes you know the Django basics, as covered in the `official tutorial`_. -.. _official tutorial: ../tutorial1/ +.. _official tutorial: ../tutorial01/ Give Django your database parameters ==================================== @@ -39,11 +39,11 @@ Auto-generate the models Django comes with a utility that can create models by introspecting an existing database. You can view the output by running this command:: - django-admin.py inspectdb --settings=path.to.settings + python manage.py inspectdb Save this as a file by using standard Unix output redirection:: - django-admin.py inspectdb --settings=path.to.settings > models.py + python manage.py inspectdb > models.py This feature is meant as a shortcut, not as definitive model generation. See the `django-admin.py documentation`_ for more information. @@ -52,7 +52,7 @@ Once you've cleaned up your models, name the file ``models.py`` and put it in the Python package that holds your app. Then add the app to your ``INSTALLED_APPS`` setting. -.. _django-admin.py documentation: ../django_admin/ +.. _django-admin.py documentation: ../django-admin/ Install the core Django tables ============================== @@ -60,7 +60,7 @@ Install the core Django tables Next, run the ``manage.py syncdb`` command to install any extra needed database records such as admin permissions and content types:: - django-admin.py init --settings=path.to.settings + python manage.py syncdb See whether it worked ===================== diff --git a/docs/man/django-admin.1 b/docs/man/django-admin.1 new file mode 100644 index 0000000000..fec5053ccb --- /dev/null +++ b/docs/man/django-admin.1 @@ -0,0 +1,162 @@ +.TH "django-admin.py" "1" "June 2007" "Django Project" "" +.SH "NAME" +django\-admin.py \- Utility script for the Django web framework +.SH "SYNOPSIS" +.B django\-admin.py +.I +.B [options] +.sp +.SH "DESCRIPTION" +This utility script provides commands for creation and maintenance of Django +projects and apps. +.sp +With the exception of +.BI startproject, +all commands listed below can also be performed with the +.BI manage.py +script found at the top level of each Django project directory. +.sp +.SH "ACTIONS" +.TP +.BI "adminindex [" "appname ..." "]" +Prints the admin\-index template snippet for the given app name(s). +.TP +.BI "createcachetable [" "tablename" "]" +Creates the table needed to use the SQL cache backend +.TP +.B dbshell +Runs the command\-line client for the current +.BI DATABASE_ENGINE. +.TP +.B diffsettings +Displays differences between the current +.B settings.py +and Django's default settings. Settings that don't appear in the defaults are +followed by "###". +.TP +.B inspectdb +Introspects the database tables in the database specified in settings.py and outputs a Django +model module. +.TP +.BI "install [" "appname ..." "]" +Executes +.B sqlall +for the given app(s) in the current database. +.TP +.BI "reset [" "appname ..." "]" +Executes +.B sqlreset +for the given app(s) in the current database. +.TP +.BI "runfcgi [" "KEY=val" "] [" "KEY=val" "] " "..." +Runs this project as a FastCGI application. Requires flup. Use +.B runfcgi help +for help on the KEY=val pairs. +.TP +.BI "runserver [" "\-\-noreload" "] [" "\-\-adminmedia=ADMIN_MEDIA_PATH" "] [" "port|ipaddr:port" "]" +Starts a lightweight Web server for development. +.TP +.BI "shell [" "\-\-plain" "]" +Runs a Python interactive interpreter. Tries to use IPython, if it's available. +The +.BI \-\-plain +option forces the use of the standard Python interpreter even when IPython is +installed. +.TP +.BI "sql [" "appname ..." "]" +Prints the CREATE TABLE SQL statements for the given app name(s). +.TP +.BI "sqlall [" "appname ..." "]" +Prints the CREATE TABLE, initial\-data and CREATE INDEX SQL statements for the +given model module name(s). +.TP +.BI "sqlclear [" "appname ..." "]" +Prints the DROP TABLE SQL statements for the given app name(s). +.TP +.BI "sqlindexes [" "appname ..." "]" +Prints the CREATE INDEX SQL statements for the given model module name(s). +.TP +.BI "sqlinitialdata [" "appname ..." "]" +Prints the initial INSERT SQL statements for the given app name(s). +.TP +.BI "sqlreset [" "appname ..." "]" +Prints the DROP TABLE SQL, then the CREATE TABLE SQL, for the given app +name(s). +.TP +.BI "sqlsequencereset [" "appname ..." "]" +Prints the SQL statements for resetting PostgreSQL sequences for the +given app name(s). +.TP +.BI "startapp [" "appname" "]" +Creates a Django app directory structure for the given app name in +the current directory. +.TP +.BI "startproject [" "projectname" "]" +Creates a Django project directory structure for the given project name +in the current directory. +.TP +.BI syncdb +Creates the database tables for all apps in INSTALLED_APPS whose tables +haven't already been created. +.TP +.BI "test [" "\-\-verbosity" "] [" "appname ..." "]" +Runs the test suite for the specified applications, or the entire project if +no apps are specified +.TP +.BI validate +Validates all installed models. +.SH "OPTIONS" +.TP +.I \-\-version +Show program's version number and exit. +.TP +.I \-h, \-\-help +Show this help message and exit. +.TP +.I \-\-settings=SETTINGS +Python path to settings module, e.g. "myproject.settings.main". If +this isn't provided, the DJANGO_SETTINGS_MODULE environment variable +will be used. +.TP +.I \-\-pythonpath=PYTHONPATH +Lets you manually add a directory the Python path, +e.g. "/home/djangoprojects/myproject". +.TP +.I \-\-plain +Use plain Python, not IPython, for the "shell" command. +.TP +.I \-\-noinput +Do not prompt the user for input. +.TP +.I \-\-noreload +Disable the development server's auto\-reloader. +.TP +.I \-\-verbosity=VERBOSITY +Verbosity level: 0=minimal output, 1=normal output, 2=all output. +.TP +.I \-\-adminmedia=ADMIN_MEDIA_PATH +Specifies the directory from which to serve admin media when using the development server. + +.SH "ENVIRONMENT" +.TP +.I DJANGO_SETTINGS_MODULE +In the absence of the +.BI \-\-settings +option, this environment variable defines the settings module to be read. +It should be in Python-import form, e.g. "myproject.settings". + +.SH "SEE ALSO" +Full descriptions of all these options, with examples, as well as documentation +for the rest of the Django framework, can be found on the Django site: +.sp +.I http://www.djangoproject.com/documentation/ +.sp +or in the distributed documentation. +.SH "AUTHORS/CREDITS" +Originally developed at World Online in Lawrence, Kansas, USA. Refer to the +AUTHORS file in the Django distribution for contributors. +.sp +.SH "LICENSE" +New BSD license. For the full license text refer to the LICENSE file in the +Django distribution. + diff --git a/docs/model-api.txt b/docs/model-api.txt index 155ef63271..09440f2b56 100644 --- a/docs/model-api.txt +++ b/docs/model-api.txt @@ -21,7 +21,7 @@ A companion to this document is the `official repository of model examples`_. (In the Django source distribution, these examples are in the ``tests/modeltests`` directory.) -.. _Database API reference: http://www.djangoproject.com/documentation/db_api/ +.. _Database API reference: ../db-api/ .. _official repository of model examples: http://www.djangoproject.com/documentation/models/ Quick example @@ -57,7 +57,7 @@ Some technical notes: syntax, but it's worth noting Django uses SQL tailored to the database backend specified in your `settings file`_. -.. _settings file: http://www.djangoproject.com/documentation/settings/ +.. _settings file: ../settings/ Fields ====== @@ -184,6 +184,35 @@ A date and time field. Takes the same extra options as ``DateField``. The admin represents this as two ```` fields, with JavaScript shortcuts. +``DecimalField`` +~~~~~~~~~~~~~~~~ + +**New in Django development version** + +A fixed-precision decimal number, represented in Python by a ``Decimal`` instance. +Has two **required** arguments: + + ====================== =================================================== + Argument Description + ====================== =================================================== + ``max_digits`` The maximum number of digits allowed in the number. + + ``decimal_places`` The number of decimal places to store with the + number. + ====================== =================================================== + +For example, to store numbers up to 999 with a resolution of 2 decimal places, +you'd use:: + + models.DecimalField(..., max_digits=5, decimal_places=2) + +And to store numbers up to approximately one billion with a resolution of 10 +decimal places:: + + models.DecimalField(..., max_digits=19, decimal_places=10) + +The admin represents this as an ```` (a single-line input). + ``EmailField`` ~~~~~~~~~~~~~~ @@ -194,14 +223,23 @@ This doesn't accept ``maxlength``; its ``maxlength`` is automatically set to ``FileField`` ~~~~~~~~~~~~~ -A file-upload field. +A file-upload field. Has one **required** argument: + + ====================== =================================================== + Argument Description + ====================== =================================================== + ``upload_to`` A local filesystem path that will be appended to + your ``MEDIA_ROOT`` setting to determine the + output of the ``get__url()`` helper + function. + ====================== =================================================== -Has an extra required argument, ``upload_to``, a local filesystem path to -which files should be upload. This path may contain `strftime formatting`_, -which will be replaced by the date/time of the file upload (so that -uploaded files don't fill up the given directory). +This path may contain `strftime formatting`_, which will be replaced by the +date/time of the file upload (so that uploaded files don't fill up the given +directory). -The admin represents this as an ```` (a file-upload widget). +The admin represents this field as an ```` (a file-upload +widget). Using a ``FileField`` or an ``ImageField`` (see below) in a model takes a few steps: @@ -231,6 +269,13 @@ For example, say your ``MEDIA_ROOT`` is set to ``'/home/media'``, and upload a file on Jan. 15, 2007, it will be saved in the directory ``/home/media/photos/2007/01/15``. +If you want to retrieve the upload file's on-disk filename, or a URL that +refers to that file, or the file's size, you can use the +``get_FOO_filename()``, ``get_FOO_url()`` and ``get_FOO_size()`` methods. +They are all documented here__. + +__ ../db-api/#get-foo-filename + Note that whenever you deal with uploaded files, you should pay close attention to where you're uploading them and what type of files they are, to avoid security holes. *Validate all uploaded files* so that you're sure the files are @@ -246,7 +291,7 @@ visiting its URL on your site. Don't allow that. A field whose choices are limited to the filenames in a certain directory on the filesystem. Has three special arguments, of which the first is -required: +**required**: ====================== =================================================== Argument Description @@ -281,28 +326,16 @@ because the ``match`` applies to the base filename (``foo.gif`` and ``FloatField`` ~~~~~~~~~~~~~~ -A floating-point number. Has two **required** arguments: +**Changed in Django development version** - ====================== =================================================== - Argument Description - ====================== =================================================== - ``max_digits`` The maximum number of digits allowed in the number. - - ``decimal_places`` The number of decimal places to store with the - number. - ====================== =================================================== - -For example, to store numbers up to 999 with a resolution of 2 decimal places, -you'd use:: - - models.FloatField(..., max_digits=5, decimal_places=2) +A floating-point number represented in Python by a ``float`` instance. -And to store numbers up to approximately one billion with a resolution of 10 -decimal places:: +The admin represents this as an ```` (a single-line input). - models.FloatField(..., max_digits=19, decimal_places=10) +**NOTE:** The semantics of ``FloatField`` have changed in the Django +development version. See the `Django 0.96 documentation`_ for the old behavior. -The admin represents this as an ```` (a single-line input). +.. _Django 0.96 documentation: http://www.djangoproject.com/documentation/0.96/model-api/#floatfield ``ImageField`` ~~~~~~~~~~~~~~ @@ -312,9 +345,14 @@ image. Has two extra optional arguments, ``height_field`` and ``width_field``, which, if set, will be auto-populated with the height and width of the image each time a model instance is saved. +In addition to the special ``get_FOO_*`` methods that are available for +``FileField``, an ``ImageField`` also has ``get_FOO_height()`` and +``get_FOO_width()`` methods. These are documented elsewhere_. + Requires the `Python Imaging Library`_. .. _Python Imaging Library: http://www.pythonware.com/products/pil/ +.. _elsewhere: ../db-api/#get-foo-height-and-get-foo-width ``IntegerField`` ~~~~~~~~~~~~~~~~ @@ -409,6 +447,11 @@ and doesn't give a 404 response). The admin represents this as an ```` (a single-line input). +``URLField`` takes an optional argument, ``maxlength``, the maximum length (in +characters) of the field. The maxlength is enforced at the database level and +in Django's validation. If you don't specify ``maxlength``, a default of 200 +is used. + ``USStateField`` ~~~~~~~~~~~~~~~~ @@ -437,8 +480,10 @@ If ``True``, Django will store empty values as ``NULL`` in the database. Default is ``False``. Note that empty string values will always get stored as empty strings, not -as ``NULL`` -- so use ``null=True`` for non-string fields such as integers, -booleans and dates. +as ``NULL``. Only use ``null=True`` for non-string fields such as integers, +booleans and dates. For both types of fields, you will also need to set +``blank=True`` if you wish to permit empty values in forms, as the ``null`` +parameter only affects database storage (see blank_, below). Avoid using ``null`` on string-based fields such as ``CharField`` and ``TextField`` unless you have an excellent reason. If a string-based field @@ -450,7 +495,7 @@ string, not ``NULL``. ``blank`` ~~~~~~~~~ -If ``True``, the field is allowed to be blank. +If ``True``, the field is allowed to be blank. Default is ``False``. Note that this is different than ``null``. ``null`` is purely database-related, whereas ``blank`` is validation-related. If a field has @@ -501,7 +546,7 @@ For each model field that has ``choices`` set, Django will add a method to retrieve the human-readable name for the field's current value. See `get_FOO_display`_ in the database API documentation. -.. _get_FOO_display: ../db_api/#get-foo-display +.. _get_FOO_display: ../db-api/#get-foo-display Finally, note that choices can be any iterable object -- not necessarily a list or tuple. This lets you construct choices dynamically. But if you find @@ -626,7 +671,7 @@ that takes the parameters ``field_data, all_data`` and raises Django comes with quite a few validators. They're in ``django.core.validators``. -.. _validator docs: http://www.djangoproject.com/documentation/forms/#validators +.. _validator docs: ../forms/#validators Verbose field names ------------------- @@ -734,10 +779,10 @@ relationship should work. All are optional: ``limit_choices_to`` A dictionary of lookup arguments and values (see the `Database API reference`_) that limit the available admin choices for this object. Use this - with ``models.LazyDate`` to limit choices of objects - by date. For example:: + with functions from the Python ``datetime`` module + to limit choices of objects by date. For example:: - limit_choices_to = {'pub_date__lte': models.LazyDate()} + limit_choices_to = {'pub_date__lte': datetime.now} only allows the choice of related objects with a ``pub_date`` before the current date/time to be @@ -792,8 +837,8 @@ relationship should work. All are optional: the related object. ======================= ============================================================ -.. _`Database API reference`: http://www.djangoproject.com/documentation/db_api/ -.. _related objects documentation: http://www.djangoproject.com/documentation/db_api/#related-objects +.. _`Database API reference`: ../db-api/ +.. _related objects documentation: ../db-api/#related-objects Many-to-many relationships ~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -963,7 +1008,7 @@ Example:: See the `docs for latest()`_ for more. -.. _docs for latest(): http://www.djangoproject.com/documentation/db_api/#latest-field-name-none +.. _docs for latest(): ../db-api/#latest-field-name-none ``order_with_respect_to`` ------------------------- @@ -1307,13 +1352,13 @@ A few special cases to note about ``list_display``: * Usually, elements of ``list_display`` that aren't actual database fields can't be used in sorting (because Django does all the sorting at the database level). - + However, if an element of ``list_display`` represents a certain database field, you can indicate this fact by setting the ``admin_order_field`` attribute of the item. - + For example:: - + class Person(models.Model): first_name = models.CharField(maxlength=50) color_code = models.CharField(maxlength=6) @@ -1325,7 +1370,7 @@ A few special cases to note about ``list_display``: return '%s' % (self.color_code, self.first_name) colored_first_name.allow_tags = True colored_first_name.admin_order_field = 'first_name' - + The above will tell Django to order by the ``first_name`` field when trying to sort by ``colored_first_name`` in the admin. @@ -1397,7 +1442,7 @@ if one of the ``list_display`` fields is a ``ForeignKey``. For more on ``select_related()``, see `the select_related() docs`_. -.. _the select_related() docs: http://www.djangoproject.com/documentation/db_api/#select-related +.. _the select_related() docs: ../db-api/#select-related ``ordering`` ------------ @@ -1502,7 +1547,7 @@ The way ``Manager`` classes work is documented in the `Retrieving objects`_ section of the database API docs, but this section specifically touches on model options that customize ``Manager`` behavior. -.. _Retrieving objects: http://www.djangoproject.com/documentation/db_api/#retrieving-objects +.. _Retrieving objects: ../db-api/#retrieving-objects Manager names ------------- @@ -1750,6 +1795,15 @@ But this template code is good:: {{ object.name }} +.. note:: + The string you return from ``get_absolute_url()`` must contain only ASCII + characters (required by the URI spec, `RFC 2396`_) that have been + URL-encoded, if necessary. Code and templates using ``get_absolute_url()`` + should be able to use the result directly without needing to do any + further processing. + +.. _RFC 2396: http://www.ietf.org/rfc/rfc2396.txt + The ``permalink`` decorator ~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -1758,16 +1812,38 @@ slightly violates the DRY principle: the URL for this object is defined both in the URLConf file and in the model. You can further decouple your models from the URLconf using the ``permalink`` -decorator. This decorator is passed the view function and any parameters you -would use for accessing this instance directly. Django then works out the -correct full URL path using the URLconf. For example:: +decorator. This decorator is passed the view function, a list of positional +parameters and (optionally) a dictionary of named parameters. Django then +works out the correct full URL path using the URLconf, substituting the +parameters you have given into the URL. For example, if your URLconf +contained a line such as:: + + (r'^/people/(\d+)/$', 'people.views.details'), + +...your model could have a ``get_absolute_url`` method that looked like this:: from django.db.models import permalink def get_absolute_url(self): - return ('people.views.details', str(self.id)) + return ('people.views.details', [str(self.id)]) get_absolute_url = permalink(get_absolute_url) +Similarly, if you had a URLconf entry that looked like:: + + (r'/archive/(?P\d{4})/(?P\d{1,2})/(?P\d{1,2})/$', archive_view) + +...you could reference this using ``permalink()`` as follows:: + + def get_absolute_url(self): + return ('archive_view', (), { + 'year': self.created.year, + 'month': self.created.month, + 'day': self.created.day}) + get_absolute_url = permalink(get_absolute_url) + +Notice that we specify an empty sequence for the second argument in this case, +because we only want to pass keyword arguments, not named arguments. + In this way, you're tying the model's absolute URL to the view that is used to display it, without repeating the URL information anywhere. You can still use the ``get_absolute_url`` method in templates, as before. @@ -1789,21 +1865,23 @@ rows. Example:: row = cursor.fetchone() return row -``connection`` and ``cursor`` simply use the standard `Python DB-API`_. If -you're not familiar with the Python DB-API, note that the SQL statement in -``cursor.execute()`` uses placeholders, ``"%s"``, rather than adding parameters -directly within the SQL. If you use this technique, the underlying database -library will automatically add quotes and escaping to your parameter(s) as -necessary. (Also note that Django expects the ``"%s"`` placeholder, *not* the -``"?"`` placeholder, which is used by the SQLite Python bindings. This is for -the sake of consistency and sanity.) +``connection`` and ``cursor`` mostly implement the standard `Python DB-API`_ +(except when it comes to `transaction handling`_). If you're not familiar with +the Python DB-API, note that the SQL statement in ``cursor.execute()`` uses +placeholders, ``"%s"``, rather than adding parameters directly within the SQL. +If you use this technique, the underlying database library will automatically +add quotes and escaping to your parameter(s) as necessary. (Also note that +Django expects the ``"%s"`` placeholder, *not* the ``"?"`` placeholder, which is +used by the SQLite Python bindings. This is for the sake of consistency and +sanity.) A final note: If all you want to do is a custom ``WHERE`` clause, you can just just the ``where``, ``tables`` and ``params`` arguments to the standard lookup API. See `Other lookup options`_. .. _Python DB-API: http://www.python.org/peps/pep-0249.html -.. _Other lookup options: http://www.djangoproject.com/documentation/db_api/#extra-params-select-where-tables +.. _Other lookup options: ../db-api/#extra-params-select-where-tables +.. _transaction handling: ../transactions/ Overriding default model methods -------------------------------- @@ -1836,7 +1914,7 @@ You can also prevent saving:: else: super(Blog, self).save() # Call the "real" save() method. -.. _database API docs: http://www.djangoproject.com/documentation/db_api/ +.. _database API docs: ../db-api/ Models across files =================== @@ -1893,7 +1971,7 @@ Each SQL file, if given, is expected to contain valid SQL. The SQL files are piped directly into the database after all of the models' table-creation statements have been executed. -The SQL files are read by the ``sqlinitialdata``, ``sqlreset``, ``sqlall`` and +The SQL files are read by the ``sqlcustom``, ``sqlreset``, ``sqlall`` and ``reset`` commands in ``manage.py``. Refer to the `manage.py documentation`_ for more information. @@ -1902,7 +1980,7 @@ order in which they're executed. The only thing you can assume is that, by the time your custom data files are executed, all the database tables already will have been created. -.. _`manage.py documentation`: http://www.djangoproject.com/documentation/django_admin/#sqlinitialdata-appname-appname +.. _`manage.py documentation`: ../django-admin/#sqlcustom-appname-appname Database-backend-specific SQL data ---------------------------------- diff --git a/docs/modpython.txt b/docs/modpython.txt index 2c999753c7..388a6168f3 100644 --- a/docs/modpython.txt +++ b/docs/modpython.txt @@ -13,14 +13,15 @@ other server arrangements. Django requires Apache 2.x and mod_python 3.x, and you should use Apache's `prefork MPM`_, as opposed to the `worker MPM`_. -You may also be interested in `How to use Django with FastCGI`_. +You may also be interested in `How to use Django with FastCGI, SCGI or AJP`_ +(which also covers SCGI and AJP). .. _Apache: http://httpd.apache.org/ .. _mod_python: http://www.modpython.org/ .. _mod_perl: http://perl.apache.org/ .. _prefork MPM: http://httpd.apache.org/docs/2.2/mod/prefork.html .. _worker MPM: http://httpd.apache.org/docs/2.2/mod/worker.html -.. _How to use Django with FastCGI: ../fastcgi/ +.. _How to use Django with FastCGI, SCGI or AJP: ../fastcgi/ Basic configuration =================== @@ -37,7 +38,8 @@ Then edit your ``httpd.conf`` file and add the following:: PythonDebug On -...and replace ``mysite.settings`` with the Python path to your settings file. +...and replace ``mysite.settings`` with the Python import path to your Django +project's settings file. This tells Apache: "Use mod_python for any URL at or under '/mysite/', using the Django mod_python handler." It passes the value of ``DJANGO_SETTINGS_MODULE`` @@ -49,9 +51,29 @@ whereas ```` points at places in the URL structure of a Web site. ```` would be meaningless here. Also, if you've manually altered your ``PYTHONPATH`` to put your Django project -on it, you'll need to tell mod_python:: +on it, you'll need to tell mod_python: - PythonPath "['/path/to/project'] + sys.path" +.. parsed-literal:: + + + SetHandler python-program + PythonHandler django.core.handlers.modpython + SetEnv DJANGO_SETTINGS_MODULE mysite.settings + PythonDebug On + **PythonPath "['/path/to/project'] + sys.path"** + + +.. caution:: + + If you're using Windows, remember that the path will contain backslashes. + This string is passed through Python's string parser twice, so you need to + escape each backslash **twice**:: + + PythonPath "['c:\\\\path\\\\to\\\\project'] + sys.path" + + Or, use raw strings:: + + PythonPath "[r'c:\\path\\to\\project'] + sys.path" You can also add directives such as ``PythonAutoReload Off`` for performance. See the `mod_python documentation`_ for a full list of options. @@ -146,7 +168,7 @@ If, however, you have no option but to serve media files on the same Apache ``VirtualHost`` as Django, here's how you can turn off mod_python for a particular part of the site:: - + SetHandler None @@ -163,7 +185,7 @@ the ``media`` subdirectory and any URL that ends with ``.jpg``, ``.gif`` or SetEnv DJANGO_SETTINGS_MODULE mysite.settings - + SetHandler None @@ -197,6 +219,41 @@ Here are two recommended approaches: 2. Or, copy the admin media files so that they live within your Apache document root. +Using eggs with mod_python +========================== + +If you installed Django from a Python egg_ or are using eggs in your Django +project, some extra configuration is required. Create an extra file in your +project (or somewhere else) that contains something like the following:: + + import os + os.environ['PYTHON_EGG_CACHE'] = '/some/directory' + +Here, ``/some/directory`` is a directory that the Apache webserver process can +write to. It will be used as the location for any unpacking of code the eggs +need to do. + +Then you have to tell mod_python to import this file before doing anything +else. This is done using the PythonImport_ directive to mod_python. You need +to ensure that you have specified the ``PythonInterpreter`` directive to +mod_python as described above__ (you need to do this even if you aren't +serving multiple installations in this case). Then add the ``PythonImport`` +line inside the ``Location`` or ``VirtualHost`` section. For example:: + + PythonInterpreter my_django + PythonImport /path/to/my/project/file.py my_django + +Note that you can use an absolute path here (or a normal dotted import path), +as described in the `mod_python manual`_. We use an absolute path in the +above example because if any Python path modifications are required to access +your project, they will not have been done at the time the ``PythonImport`` +line is processed. + +.. _Egg: http://peak.telecommunity.com/DevCenter/PythonEggs +.. _PythonImport: http://www.modpython.org/live/current/doc-html/dir-other-pimp.html +.. _mod_python manual: PythonImport_ +__ `Multiple Django installations on the same Apache`_ + Error handling ============== @@ -242,3 +299,5 @@ as necessary. .. _Expat Causing Apache Crash: http://www.dscpl.com.au/articles/modpython-006.html .. _mod_python FAQ entry: http://modpython.org/FAQ/faqw.py?req=show&file=faq02.013.htp .. _Getting mod_python Working: http://www.dscpl.com.au/articles/modpython-001.html + + diff --git a/docs/newforms.txt b/docs/newforms.txt index d7ef4d2599..1511791a7d 100644 --- a/docs/newforms.txt +++ b/docs/newforms.txt @@ -9,28 +9,30 @@ framework. This document explains how to use this new library. Migration plan ============== -``django.newforms`` currently is only available in Django beginning -with the 0.96 release. the Django development version -- i.e., it's -not available in the Django 0.95 release. For the next Django release, -our plan is to do the following: +``django.newforms`` is new in Django's 0.96 release, but, as it won't be new +forever, we plan to rename it to ``django.forms`` in the future. The current +``django.forms`` package will be available as ``django.oldforms`` until Django +1.0, when we plan to remove it for good. - * As of revision [4208], we've copied the current ``django.forms`` to - ``django.oldforms``. This allows you to upgrade your code *now* rather - than waiting for the backwards-incompatible change and rushing to fix - your code after the fact. Just change your import statements like this:: +That has direct repercussions on the forward compatibility of your code. Please +read the following migration plan and code accordingly: + + * The old forms framework (the current ``django.forms``) has been copied to + ``django.oldforms``. Thus, you can start upgrading your code *now*, + rather than waiting for the future backwards-incompatible change, by + changing your import statements like this:: from django import forms # old from django import oldforms as forms # new - * At an undecided future date, we will move the current ``django.newforms`` - to ``django.forms``. This will be a backwards-incompatible change, and - anybody who is still using the old version of ``django.forms`` at that - time will need to change their import statements, as described in the - previous bullet. + * In the next Django release (0.97), we will move the current + ``django.newforms`` to ``django.forms``. This will be a + backwards-incompatible change, and anybody who is still using the old + version of ``django.forms`` at that time will need to change their import + statements, as described in the previous bullet. * We will remove ``django.oldforms`` in the release *after* the next Django - release -- the release that comes after the release in which we're - creating the new ``django.forms``. + release -- either 0.98 or 1.0, whichever comes first. With this in mind, we recommend you use the following import statement when using ``django.newforms``:: @@ -184,7 +186,7 @@ e-mail address:: >>> f.is_valid() False -Access the ``Form`` attribute ``errors`` to get a dictionary of error messages:: +Access the ``errors`` attribute to get a dictionary of error messages:: >>> f.errors {'sender': [u'Enter a valid e-mail address.'], 'subject': [u'This field is required.']} @@ -197,6 +199,10 @@ You can access ``errors`` without having to call ``is_valid()`` first. The form's data will be validated the first time either you call ``is_valid()`` or access ``errors``. +The validation routines will only get called once, regardless of how many times +you access ``errors`` or call ``is_valid()``. This means that if validation has +side effects, those side effects will only be triggered once. + Behavior of unbound forms ~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -224,7 +230,7 @@ object. Regardless of whether you pass it a string in the format 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 ``clean_data`` attribute of the ``Form`` +you can access the clean data via the ``cleaned_data`` attribute of the ``Form`` object:: >>> data = {'subject': 'hello', @@ -234,7 +240,7 @@ object:: >>> f = ContactForm(data) >>> f.is_valid() True - >>> f.clean_data + >>> f.cleaned_data {'cc_myself': True, 'message': u'Hi there', 'sender': u'foo@example.com', 'subject': u'hello'} Note that any text-based field -- such as ``CharField`` or ``EmailField`` -- @@ -242,7 +248,7 @@ always cleans the input into a Unicode string. We'll cover the encoding implications later in this document. If your data does *not* validate, your ``Form`` instance will not have a -``clean_data`` attribute:: +``cleaned_data`` attribute:: >>> data = {'subject': '', ... 'message': 'Hi there', @@ -251,15 +257,15 @@ If your data does *not* validate, your ``Form`` instance will not have a >>> f = ContactForm(data) >>> f.is_valid() False - >>> f.clean_data + >>> f.cleaned_data Traceback (most recent call last): ... - AttributeError: 'ContactForm' object has no attribute 'clean_data' + AttributeError: 'ContactForm' object has no attribute 'cleaned_data' -``clean_data`` will always *only* contain a key for fields defined in the +``cleaned_data`` will always *only* contain a key for fields defined in the ``Form``, even if you pass extra data when you define the ``Form``. In this example, we pass a bunch of extra fields to the ``ContactForm`` constructor, -but ``clean_data`` contains only the form's fields:: +but ``cleaned_data`` contains only the form's fields:: >>> data = {'subject': 'hello', ... 'message': 'Hi there', @@ -271,20 +277,48 @@ but ``clean_data`` contains only the form's fields:: >>> f = ContactForm(data) >>> f.is_valid() True - >>> f.clean_data # Doesn't contain extra_field_1, etc. + >>> f.cleaned_data # Doesn't contain extra_field_1, etc. {'cc_myself': True, 'message': u'Hi there', 'sender': u'foo@example.com', 'subject': u'hello'} +``cleaned_data`` will include a key and value for *all* fields defined in the +``Form``, even if the data didn't include a value for fields that are not +required. In this example, the data dictionary doesn't include a value for the +``nick_name`` field, but ``cleaned_data`` includes it, with an empty value:: + + >>> class OptionalPersonForm(Form): + ... first_name = CharField() + ... last_name = CharField() + ... nick_name = CharField(required=False) + >>> data = {'first_name': u'John', 'last_name': u'Lennon'} + >>> f = OptionalPersonForm(data) + >>> f.is_valid() + True + >>> f.cleaned_data + {'nick_name': u'', 'first_name': u'John', 'last_name': u'Lennon'} + +In this above example, the ``cleaned_data`` value for ``nick_name`` is set to an +empty string, because ``nick_name`` is ``CharField``, and ``CharField``\s treat +empty values as an empty string. Each field type knows what its "blank" value +is -- e.g., for ``DateField``, it's ``None`` instead of the empty string. For +full details on each field's behavior in this case, see the "Empty value" note +for each field in the "Built-in ``Field`` classes" section below. + +You can write code to perform validation for particular form fields (based on +their name) or for the form as a whole (considering combinations of various +fields). More information about this is in the `Custom form and field +validation`_ section, below. + Behavior of unbound forms ~~~~~~~~~~~~~~~~~~~~~~~~~ -It's meaningless to request "clean" data in a form with no data, but, for the +It's meaningless to request "cleaned" data in a form with no data, but, for the record, here's what happens with unbound forms:: >>> f = ContactForm() - >>> f.clean_data + >>> f.cleaned_data Traceback (most recent call last): ... - AttributeError: 'ContactForm' object has no attribute 'clean_data' + AttributeError: 'ContactForm' object has no attribute 'cleaned_data' Outputting forms as HTML ------------------------ @@ -454,7 +488,7 @@ field:: If ``auto_id`` is set to a string containing the format character ``'%s'``, then the form output will include ``