From ae22b6d403dcf25098c77f0dfcf59ae58b186461 Mon Sep 17 00:00:00 2001 From: Christopher Long Date: Sun, 17 Jun 2007 22:18:54 +0000 Subject: per-object-permissions: Merged to trunk [5486] NOTE: Not fully tested, will be working on this over the next few weeks. git-svn-id: http://code.djangoproject.com/svn/django/branches/per-object-permissions@5488 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- docs/add_ons.txt | 68 +- docs/apache_auth.txt | 4 +- docs/api_stability.txt | 46 +- docs/authentication.txt | 217 ++++++- docs/cache.txt | 19 +- docs/contributing.txt | 227 ++++++- docs/databases.txt | 165 +++++ docs/databrowse.txt | 60 ++ docs/db-api.txt | 135 +++- docs/design_philosophies.txt | 2 +- docs/distributions.txt | 78 +++ docs/django-admin.txt | 192 +++++- docs/documentation.txt | 42 +- docs/email.txt | 101 ++- docs/faq.txt | 33 +- docs/fastcgi.txt | 55 +- docs/flatpages.txt | 14 +- docs/forms.txt | 74 ++- docs/generic_views.txt | 70 ++- docs/i18n.txt | 39 +- docs/install.txt | 82 ++- docs/legacy_databases.txt | 26 +- docs/man/django-admin.1 | 162 +++++ docs/middleware.txt | 17 +- docs/model-api.txt | 282 +++++++-- docs/modpython.txt | 73 ++- docs/newforms.txt | 1415 ++++++++++++++++++++++++++++++++++++++++-- docs/outputting_csv.txt | 6 +- docs/outputting_pdf.txt | 4 +- docs/overview.txt | 4 +- docs/redirects.txt | 12 +- docs/release_notes_0.96.txt | 264 ++++++++ docs/request_response.txt | 125 +++- docs/serialization.txt | 30 +- docs/sessions.txt | 27 +- docs/settings.txt | 283 ++++++--- docs/sitemaps.txt | 22 +- docs/sites.txt | 12 +- docs/static_files.txt | 6 +- docs/syndication_feeds.txt | 79 ++- docs/templates.txt | 161 ++++- docs/templates_python.txt | 198 +++++- docs/testing.txt | 438 ++++++++++--- docs/tutorial01.txt | 44 +- docs/tutorial02.txt | 16 +- docs/tutorial03.txt | 20 +- docs/tutorial04.txt | 49 +- docs/url_dispatch.txt | 134 +++- docs/webdesign.txt | 53 ++ 49 files changed, 4899 insertions(+), 786 deletions(-) create mode 100644 docs/databases.txt create mode 100644 docs/databrowse.txt create mode 100644 docs/distributions.txt create mode 100644 docs/man/django-admin.1 create mode 100644 docs/release_notes_0.96.txt create mode 100644 docs/webdesign.txt (limited to 'docs') diff --git a/docs/add_ons.txt b/docs/add_ons.txt index 58c01c4fc0..ffc4f7420f 100644 --- a/docs/add_ons.txt +++ b/docs/add_ons.txt @@ -1,13 +1,21 @@ -===================== -The "contrib" add-ons -===================== +============================ +The "django.contrib" add-ons +============================ 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: http://www.djangoproject.com/documentation/tutorial2/ +.. _Tutorial 2: ../tutorial02/ + +Requires the auth_ and contenttypes_ contrib packages to be installed. auth ==== @@ -26,7 +36,7 @@ Django's authentication framework. See the `authentication documentation`_. -.. _authentication documentation: http://www.djangoproject.com/documentation/authentication/ +.. _authentication documentation: ../authentication/ comments ======== @@ -46,13 +56,11 @@ A middleware for preventing Cross Site Request Forgeries See the `csrf documentation`_. -.. _csrf documentation: http://www.djangoproject.com/documentation/csrf/ +.. _csrf documentation: ../csrf/ formtools ========= -**New in Django development version** - A set of high-level abstractions for Django forms (django.newforms). django.contrib.formtools.preview @@ -137,18 +145,38 @@ A framework for managing simple "flat" HTML content in a database. See the `flatpages documentation`_. -.. _flatpages documentation: http://www.djangoproject.com/documentation/flatpages/ +.. _flatpages documentation: ../flatpages/ + +Requires the sites_ contrib package to be installed as well. + +localflavor +=========== + +A collection of various Django snippets that are useful only for a particular +country or culture. For example, ``django.contrib.localflavor.usa.forms`` +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)`_ + +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. - * Textile - * Markdown - * ReST (ReStructured Text) +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. -For 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 +.. _ReST (ReStructured Text): http://en.wikipedia.org/wiki/ReStructuredText redirects ========= @@ -157,7 +185,7 @@ A framework for managing redirects. See the `redirects documentation`_. -.. _redirects documentation: http://www.djangoproject.com/documentation/redirects/ +.. _redirects documentation: ../redirects/ sites ===== @@ -168,7 +196,7 @@ one or more sites. See the `sites documentation`_. -.. _sites documentation: http://www.djangoproject.com/documentation/sites/ +.. _sites documentation: ../sites/ sitemaps ======== @@ -177,7 +205,7 @@ A framework for generating Google sitemap XML files. See the `sitemaps documentation`_. -.. _sitemaps documentation: http://www.djangoproject.com/documentation/sitemaps/ +.. _sitemaps documentation: ../sitemaps/ syndication =========== @@ -186,7 +214,7 @@ A framework for generating syndication feeds, in RSS and Atom, quite easily. See the `syndication documentation`_. -.. _syndication documentation: http://www.djangoproject.com/documentation/syndication/ +.. _syndication documentation: ../syndication/ Other add-ons ============= diff --git a/docs/apache_auth.txt b/docs/apache_auth.txt index b85057924b..583cb96b39 100644 --- a/docs/apache_auth.txt +++ b/docs/apache_auth.txt @@ -65,7 +65,7 @@ are equivalent:: SetEnv DJANGO_SETTINGS_MODULE mysite.settings PythonOption DJANGO_SETTINGS_MODULE mysite.settings -.. _authentication system: http://www.djangoproject.com/documentation/authentication/ +.. _authentication system: ../authentication/ .. _Subversion: http://subversion.tigris.org/ .. _mod_dav: http://httpd.apache.org/docs/2.0/mod/mod_dav.html -.. _custom permissions: http://www.djangoproject.com/documentation/authentication/#custom-permissions +.. _custom permissions: ../authentication/#custom-permissions diff --git a/docs/api_stability.txt b/docs/api_stability.txt index 18885fbe63..cfaffeac6b 100644 --- a/docs/api_stability.txt +++ b/docs/api_stability.txt @@ -98,26 +98,26 @@ change: rewrite before Django 1.0. Even if the change isn't quite that drastic, there will at least be moderate changes. -.. _caching: http://www.djangoproject.com/documentation/cache/ -.. _custom template tags and libraries: http://www.djangoproject.com/documentation/templates_python/ -.. _database lookup: http://www.djangoproject.com/documentation/db_api/ -.. _django-admin utility: http://www.djangoproject.com/documentation/django_admin/ -.. _fastcgi integration: http://www.djangoproject.com/documentation/fastcgi/ -.. _flatpages: http://www.djangoproject.com/documentation/flatpages/ -.. _generic views: http://www.djangoproject.com/documentation/generic_views/ -.. _internationalization: http://www.djangoproject.com/documentation/i18n/ -.. _legacy database integration: http://www.djangoproject.com/documentation/legacy_databases/ -.. _model definition: http://www.djangoproject.com/documentation/model_api/ -.. _mod_python integration: http://www.djangoproject.com/documentation/modpython/ -.. _redirects: http://www.djangoproject.com/documentation/redirects/ -.. _request/response objects: http://www.djangoproject.com/documentation/request_response/ -.. _sending email: http://www.djangoproject.com/documentation/email/ -.. _sessions: http://www.djangoproject.com/documentation/sessions/ -.. _settings: http://www.djangoproject.com/documentation/settings/ -.. _syndication: http://www.djangoproject.com/documentation/syndication/ -.. _template language: http://www.djangoproject.com/documentation/templates/ -.. _transactions: http://www.djangoproject.com/documentation/transactions/ -.. _url dispatch: http://www.djangoproject.com/documentation/url_dispatch/ -.. _forms and validation: http://www.djangoproject.com/documentation/forms/ -.. _serialization: http://www.djangoproject.com/documentation/serialization/ -.. _authentication: http://www.djangoproject.com/documentation/authentication/ +.. _caching: ../cache/ +.. _custom template tags and libraries: ../templates_python/ +.. _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/ +.. _mod_python integration: ../modpython/ +.. _redirects: ../redirects/ +.. _request/response objects: ../request_response/ +.. _sending email: ../email/ +.. _sessions: ../sessions/ +.. _settings: ../settings/ +.. _syndication: ../syndication/ +.. _template language: ../templates/ +.. _transactions: ../transactions/ +.. _url dispatch: ../url_dispatch/ +.. _forms and validation: ../forms/ +.. _serialization: ../serialization/ +.. _authentication: ../authentication/ diff --git a/docs/authentication.txt b/docs/authentication.txt index 08565e13e1..12b61db538 100644 --- a/docs/authentication.txt +++ b/docs/authentication.txt @@ -86,10 +86,10 @@ objects in the same way as any other `Django model`_:: myuser.groups.add(group, group,...) myuser.groups.remove(group, group,...) myuser.groups.clear() - myuser.permissions = [permission_list] - myuser.permissions.add(permission, permission, ...) - myuser.permissions.remove(permission, permission, ...] - myuser.permissions.clear() + myuser.user_permissions = [permission_list] + myuser.user_permissions.add(permission, permission, ...) + myuser.user_permissions.remove(permission, permission, ...] + myuser.user_permissions.clear() In addition to those automatic API methods, ``User`` objects have the following custom methods: @@ -144,8 +144,8 @@ custom methods: Raises ``django.contrib.auth.models.SiteProfileNotAvailable`` if the current site doesn't allow profiles. -.. _Django model: http://www.djangoproject.com/documentation/model_api/ -.. _DEFAULT_FROM_EMAIL: http://www.djangoproject.com/documentation/settings/#default-from-email +.. _Django model: ../model-api/ +.. _DEFAULT_FROM_EMAIL: ../settings/#default-from-email Manager functions ~~~~~~~~~~~~~~~~~ @@ -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:: @@ -271,8 +274,8 @@ previous section). You can tell them apart with ``is_authenticated()``, like so: else: # Do something for anonymous users. -.. _request objects: http://www.djangoproject.com/documentation/request_response/#httprequest-objects -.. _session documentation: http://www.djangoproject.com/documentation/sessions/ +.. _request objects: ../request_response/#httprequest-objects +.. _session documentation: ../sessions/ How to log a user in -------------------- @@ -317,6 +320,16 @@ This example shows how you might use both ``authenticate()`` and ``login()``:: else: # Return an 'invalid login' error message. +Manually checking a user's password +----------------------------------- + +If you'd like to manually authenticate a user by comparing a +plain-text password to the hashed password in the database, use the +convenience function `django.contrib.auth.models.check_password`. It +takes two arguments: the plain-text password to check, and the full +value of a user's ``password`` field in the database to check against, +and returns ``True`` if they match, ``False`` otherwise. + How to log a user out --------------------- @@ -377,27 +390,28 @@ 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'), -Here's what ``django.contrib.auth.views.login`` does:: +Here's what ``django.contrib.auth.views.login`` does: * If called via ``GET``, it displays a login form that POSTs to the same URL. More on this in a bit. * 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 @@ -441,8 +455,149 @@ block:: {% endblock %} -.. _forms documentation: http://www.djangoproject.com/documentation/forms/ -.. _site framework docs: http://www.djangoproject.com/documentation/sites/ +.. _forms documentation: ../forms/ +.. _site framework docs: ../sites/ + +Other built-in views +-------------------- + +In addition to the `login` view, the authentication system includes a +few other useful built-in views: + +``django.contrib.auth.views.logout`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**Description:** + +Logs a user out. + +**Optional arguments:** + + * ``template_name``: The full name of a template to display after + logging the user out. This will default to + ``registration/logged_out.html`` if no argument is supplied. + +**Template context:** + + * ``title``: The string "Logged out", localized. + +``django.contrib.auth.views.logout_then_login`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**Description:** + +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 ``settings.LOGIN_URL`` if not supplied. + +``django.contrib.auth.views.password_change`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**Description:** + +Allows a user to change their password. + +**Optional arguments:** + + * ``template_name``: The full name of a template to use for + displaying the password change form. This will default to + ``registration/password_change_form.html`` if not supplied. + +**Template context:** + + * ``form``: The password change form. + +``django.contrib.auth.views.password_change_done`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**Description:** + +The page shown after a user has changed their password. + +**Optional arguments:** + + * ``template_name``: The full name of a template to use. This will + default to ``registration/password_change_done.html`` if not + supplied. + +``django.contrib.auth.views.password_reset`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**Description:** + +Allows a user to reset their password, and sends them the new password +in an email. + +**Optional arguments:** + + * ``template_name``: The full name of a template to use for + displaying the password reset form. This will default to + ``registration/password_reset_form.html`` if not supplied. + + * ``email_template_name``: The full name of a template to use for + generating the email with the new password. This will default to + ``registration/password_reset_email.html`` if not supplied. + +**Template context:** + + * ``form``: The form for resetting the user's password. + +``django.contrib.auth.views.password_reset_done`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**Description:** + +The page shown after a user has reset their password. + +**Optional arguments:** + + * ``template_name``: The full name of a template to use. This will + default to ``registration/password_reset_done.html`` if not + supplied. + +``django.contrib.auth.views.redirect_to_login`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +**Description:** + +Redirects to the login page, and then back to another URL after a +successful login. + +**Required arguments:** + + * ``next``: The URL to redirect to after a successful login. + +**Optional arguments:** + + * ``login_url``: The URL of the login page to redirect to. This + will default to ``settings.LOGIN_URL`` if not supplied. + +Built-in manipulators +--------------------- + +If you don't want to use the built-in views, but want the convenience +of not having to write manipulators for this functionality, the +authentication system provides several built-in manipulators: + + * ``django.contrib.auth.forms.AdminPasswordChangeForm``: A + manipulator used in the admin interface to change a user's + password. + + * ``django.contrib.auth.forms.AuthenticationForm``: A manipulator + for logging a user in. + + * ``django.contrib.auth.forms.PasswordChangeForm``: A manipulator + for allowing a user to change their password. + + * ``django.contrib.auth.forms.PasswordResetForm``: A manipulator + for resetting a user's password and emailing the new password to + them. + + * ``django.contrib.auth.forms.UserCreationForm``: A manipulator + for creating a new user. Limiting access to logged-in users that pass a test --------------------------------------------------- @@ -485,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:: @@ -529,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 -------------------------------- @@ -544,7 +699,7 @@ For example:: def limited_object_detail(*args, **kwargs): return object_detail(*args, **kwargs) -.. _generic view: http://www.djangoproject.com/documentation/generic_views/ +.. _generic view: ../generic_views/ Permissions =========== @@ -575,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``. @@ -606,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: http://www.djangoproject.com/documentation/model_api/#meta-options +.. _model Meta attribute: ../model-api/#meta-options API reference ------------- @@ -645,7 +800,7 @@ The currently logged-in user and his/her permissions are made available in the setting contains ``"django.core.context_processors.auth"``, which is default. For more, see the `RequestContext docs`_. - .. _RequestContext docs: http://www.djangoproject.com/documentation/templates_python/#subclassing-context-requestcontext + .. _RequestContext docs: ../templates_python/#subclassing-context-requestcontext Users ----- @@ -691,7 +846,7 @@ Thus, you can check permissions in template ``{% if %}`` statements::

You don't have permission to do anything in the foo app.

{% endif %} -.. _template context: http://www.djangoproject.com/documentation/templates_python/ +.. _template context: ../templates_python/ Groups ====== @@ -756,7 +911,7 @@ scenes, so any messages will be deleted even if you don't display them. Finally, note that this messages framework only works with users in the user database. To send messages to anonymous users, use the `session framework`_. -.. _session framework: http://www.djangoproject.com/documentation/sessions/ +.. _session framework: ../sessions/ Other authentication sources ============================ @@ -813,13 +968,13 @@ The ``authenticate`` method takes credentials as keyword arguments. Most of the time, it'll just look like this:: class MyBackend: - def authenticate(username=None, password=None): + def authenticate(self, username=None, password=None): # Check the username/password and return a User. But it could also authenticate a token, like so:: class MyBackend: - def authenticate(token=None): + def authenticate(self, token=None): # Check the token and return a User. Either way, ``authenticate`` should check the credentials it gets, and it diff --git a/docs/cache.txt b/docs/cache.txt index 1795345ed9..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 @@ -250,7 +259,7 @@ Additionally, ``CacheMiddleware`` automatically sets a few headers in each See the `middleware documentation`_ for more on middleware. -.. _`middleware documentation`: http://www.djangoproject.com/documentation/middleware/ +.. _`middleware documentation`: ../middleware/ The per-view cache ================== diff --git a/docs/contributing.txt b/docs/contributing.txt index de9236f6c1..31409f27bd 100644 --- a/docs/contributing.txt +++ b/docs/contributing.txt @@ -122,9 +122,9 @@ Patch style * Name the patch file with a ``.diff`` extension; this will let the ticket tracker apply correct syntax highlighting, which is quite helpful. - * Put the prefix "[patch] " before the title of your ticket. This will make - it obvious that the ticket includes a patch, and it will add the ticket - to the `list of tickets with patches`_. + * Check the "Has patch" box on the ticket details. This will make it + obvious that the ticket includes a patch, and it will add the ticket to + the `list of tickets with patches`_. * The code required to fix a problem or add a feature is an essential part of a patch, but it is not the only part. A good patch should also include @@ -151,24 +151,97 @@ Unfortunately, not all bug reports in the `ticket tracker`_ provide all the `required details`_. A number of tickets have patches, but those patches don't meet all the requirements of a `good patch`_. -One way to help out is to *triage* bugs that have been reported by other users. -Pick an open ticket that is missing some details, and try to replicate the -problem. Fill in the missing pieces of the report. If the ticket doesn't have -a patch, create one. +One way to help out is to *triage* bugs that have been reported by other +users. A couple of dedicated volunteers work on this regularly, but more help +is always appreciated. -Once you've completed all the missing details on the ticket and you have a -patch with all the required features, e-mail `django-developers`_. Indicate -that you have triaged a ticket, and recommend a course of action for dealing -with that ticket. +Most of the workflow is based around the concept of a ticket's "triage stage". +This stage describes where in its lifetime a given ticket is at any time. +Along with a handful of flags, this field easily tells us what and who each +ticket is waiting on. -At first, this may require you to be persistent. If you find that your triaged -ticket still isn't getting attention, occasional polite requests for eyeballs -to look at your ticket may be necessary. However, as you earn a reputation for -quality triage work, you should find that it is easier to get the developers' -attention. +Since a picture is worth a thousand words, let's start there: + +.. image:: http://media.djangoproject.com/img/doc/djangotickets.png + :height: 451 + :width: 590 + :alt: Django's ticket workflow + +We've got two roles here: + + * Core developers: people with commit access who make the decisions and + write the bulk of the code. + + * Ticket triagers: community members who keep track of tickets, making + sure the tickets are always categorized correctly. + +Second, note the four triage stages: + + 1. A ticket starts as "Unreviewed", meaning that a triager has yet to + examine the ticket and move it along. + + 2. "Design decision needed" means "this concept requires a design + decision," which should be discussed either in the ticket comments or on + django-developers. + + 3. Once a ticket is ruled to be approved for fixing, it's moved into the + "Accepted" stage. This stage is where all the real work gets done. + + 4. If a ticket has an associated patch (see below), a triager will review the + patch. If the patch is complete, it'll be marked as "ready for checkin" so + that a core developer knows to review and check in the patches. + +The second part of this workflow involves a set of flags the describe what the +ticket has or needs in order to be "ready for checkin": + + "Has patch" + This means the ticket has an associated patch_. These will be + reviewed to see if the patch is "good". + + "Needs documentation" + This flag is used for tickets with patches that need associated + documentation. Complete documentation of features is a prerequisite + before we can check a fix into the codebase. + + "Needs tests" + This flags the patch as needing associated unit tests. Again, this is a + required part of a valid patch. + + "Patch needs improvement" + This flag means that although the ticket *has* a patch, it's not quite + ready for checkin. This could mean the patch no longer applies + cleanly, or that the code doesn't live up to our standards. + +A ticket can be resolved in a number of ways: + + "fixed" + Used by one of the core developers once a patch has been rolled into + Django and the issue is fixed. + + "invalid" + Used if the ticket is found to be incorrect or a user error. + + "wontfix" + Used when a core developer decides that this request is not + appropriate for consideration in Django. This is usually chosen after + discussion in the ``django-developers`` mailing list, and you should + feel free to join in when it's something you care about. + + "duplicate" + Used when another ticket covers the same issue. By closing duplicate + tickets, we keep all the discussion in one place, which helps everyone. + + "worksforme" + Used when the triage team is unable to replicate the original bug. + +If you believe that the ticket was closed in error -- because you're +still having the issue, or it's popped up somewhere else, or the triagers have +-- made a mistake, please reopen the ticket and tell us why. Please do not +reopen tickets that have been marked as "wontfix" by core developers. .. _required details: `Reporting bugs`_ .. _good patch: `Patch style`_ +.. _patch: `Submitting patches`_ Submitting and maintaining translations ======================================= @@ -186,7 +259,7 @@ translated, here's what to do: `i18n documentation`_. .. _Django i18n mailing list: http://groups.google.com/group/django-i18n/ -.. _i18n documentation: http://www.djangoproject.com/documentation/i18n/ +.. _i18n documentation: ../i18n/ Coding style ============ @@ -206,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. @@ -217,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``. @@ -230,9 +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. While we appreciate all - contributions to Django, our policy is not to publish individual - developer names in code -- for instance, at the top of Python modules. +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 =============== @@ -311,7 +459,7 @@ The Django tests all use the testing infrastructure that ships with Django for testing applications. See `Testing Django applications`_ for an explanation of how to write new tests. -.. _Testing Django applications: http://www.djangoproject.com/documentation/testing/ +.. _Testing Django applications: ../testing/ Running the unit tests ---------------------- @@ -321,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 @@ -438,6 +587,29 @@ Alternatively, you can use a symlink called ``django`` that points to the location of the branch's ``django`` package. If you want to switch back, just change the symlink to point to the old code. +A third option is to use a `path file`_ (``.pth``) which should +work on all systems (including Windows, which doesn't have symlinks +available). First, make sure there are no files, directories or symlinks named +``django`` in your ``site-packages`` directory. Then create a text file named +``django.pth`` and save it to your ``site-packages`` directory. That file +should contain a path to your copy of Django on a single line and optional +comments. Here is an example that points to multiple branches. Just uncomment +the line for the branch you want to use ('Trunk' in this example) and make +sure all other lines are commented:: + + # Trunk is a svn checkout of: + # http://code.djangoproject.com/svn/django/trunk/ + # + /path/to/trunk + + # is a svn checkout of: + # http://code.djangoproject.com/svn/django/branches// + # + #/path/to/ + + # On windows a path may look like this: + # C:/path/to/ + If you're using Django 0.95 or earlier and installed it using ``python setup.py install``, you'll have a directory called something like ``Django-0.95-py2.4.egg`` instead of ``django``. In this case, edit the file @@ -445,6 +617,8 @@ If you're using Django 0.95 or earlier and installed it using file. Then copy the branch's version of the ``django`` directory into ``site-packages``. +.. _path file: http://docs.python.org/lib/module-site.html + Official releases ================= @@ -548,8 +722,7 @@ requests for commit access are potential flame-war starters, and will be ignored .. _search the tracker: http://code.djangoproject.com/search .. _django-users: http://groups.google.com/group/django-users .. _`#django`: irc://irc.freenode.net/django -.. _list of tickets with patches: http://code.djangoproject.com/report/12 +.. _list of tickets with patches: http://code.djangoproject.com/query?status=new&status=assigned&status=reopened&has_patch=1&order=priority .. _PEP 8: http://www.python.org/peps/pep-0008.html -.. _i18n documentation: http://www.djangoproject.com/documentation/i18n/ .. _i18n branch: http://code.djangoproject.com/browser/django/branches/i18n .. _`tags/releases`: http://code.djangoproject.com/browser/django/tags/releases diff --git a/docs/databases.txt b/docs/databases.txt new file mode 100644 index 0000000000..b73f39843c --- /dev/null +++ b/docs/databases.txt @@ -0,0 +1,165 @@ +=============================== +Notes about supported databases +=============================== + +Django attempts to support as many features as possible on all database +backends. However, not all database backends are alike, and we've had to make +design decisions on which features to support and which assumptions we can make +safely. + +This file describes some of the features that might be relevant to Django +usage. Of course, it is not intended as a replacement for server-specific +documentation or reference manuals. + +MySQL notes +=========== + +Django expects the database to support transactions, referential integrity, +and Unicode support (UTF-8 encoding). Fortunately, MySQL_ has all these +features as available as far back as 3.23. While it may be possible to use +3.23 or 4.0, you'll probably have less trouble if you use 4.1 or 5.0. + +MySQL 4.1 +--------- + +`MySQL 4.1`_ has greatly improved support for character sets. It is possible to +set different default character sets on the database, table, and column. +Previous versions have only a server-wide character set setting. It's also the +first version where the character set can be changed on the fly. 4.1 also has +support for views, but Django currently doesn't use views. + +MySQL 5.0 +--------- + +`MySQL 5.0`_ adds the ``information_schema`` database, which contains detailed +data on all database schema. Django's ``inspectdb`` feature uses this +``information_schema`` if it's available. 5.0 also has support for stored +procedures, but Django currently doesn't use stored procedures. + +.. _MySQL: http://www.mysql.com/ +.. _MySQL 4.1: http://dev.mysql.com/doc/refman/4.1/en/index.html +.. _MySQL 5.0: http://dev.mysql.com/doc/refman/5.0/en/index.html + +Storage engines +--------------- + +MySQL has several `storage engines`_ (previously called table types). You can +change the default storage engine in the server configuration. + +The default engine is MyISAM_. The main drawback of MyISAM is that it doesn't +currently support transactions or foreign keys. On the plus side, it's +currently the only engine that supports full-text indexing and searching. + +The InnoDB_ engine is fully transactional and supports foreign key references. + +The BDB_ engine, like InnoDB, is also fully transactional and supports foreign +key references. However, its use seems to be deprecated. + +`Other storage engines`_, including SolidDB_ and Falcon_, are on the horizon. +For now, InnoDB is probably your best choice. + +.. _storage engines: http://dev.mysql.com/doc/refman/5.0/en/storage-engines.html +.. _MyISAM: http://dev.mysql.com/doc/refman/5.0/en/myisam-storage-engine.html +.. _BDB: http://dev.mysql.com/doc/refman/5.0/en/bdb-storage-engine.html +.. _InnoDB: http://dev.mysql.com/doc/refman/5.0/en/innodb.html +.. _Other storage engines: http://dev.mysql.com/doc/refman/5.1/en/storage-engines-other.html +.. _SolidDB: http://forge.mysql.com/projects/view.php?id=139 +.. _Falcon: http://dev.mysql.com/doc/falcon/en/index.html + +MySQLdb +------- + +`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 + +Creating your database +---------------------- + +You can `create your database`_ using the command-line tools and this SQL:: + + CREATE DATABASE CHARACTER SET utf8; + +This ensures all tables and columns will use UTF-8 by default. + +.. _create your database: http://dev.mysql.com/doc/refman/5.0/en/create-database.html + +Connecting to the database +-------------------------- + +Refer to the `settings documentation`_. + +Connection settings are used in this order: + + 1. ``DATABASE_OPTIONS`` + 2. ``DATABASE_NAME``, ``DATABASE_USER``, ``DATABASE_PASSWORD``, ``DATABASE_HOST``, + ``DATABASE_PORT`` + 3. MySQL option files. + +In other words, if you set the name of the database in ``DATABASE_OPTIONS``, +this will take precedence over ``DATABASE_NAME``, which would override +anything in a `MySQL option file`_. + +Here's a sample configuration which uses a MySQL option file:: + + # settings.py + DATABASE_ENGINE = "mysql" + DATABASE_OPTIONS = { + 'read_default_file': '/path/to/my.cnf', + } + + # my.cnf + [client] + database = DATABASE_NAME + user = DATABASE_USER + passwd = DATABASE_PASSWORD + default-character-set = utf8 + +Several other MySQLdb connection options may be useful, such as ``ssl``, +``use_unicode``, ``init_command``, and ``sql_mode``. Consult the +`MySQLdb documentation`_ for more details. + +.. _settings documentation: http://www.djangoproject.com/documentation/settings/#database-engine +.. _MySQL option file: http://dev.mysql.com/doc/refman/5.0/en/option-files.html +.. _MySQLdb documentation: http://mysql-python.sourceforge.net/ + +Creating your tables +-------------------- + +When Django generates the schema, it doesn't specify a storage engine, so +tables will be created with whatever default storage engine your database +server is configured for. The easiest solution is to set your database server's +default storage engine to the desired engine. + +If you're using a hosting service and can't change your server's default +storage engine, you have a couple of options. + + * After the tables are created, execute an ``ALTER TABLE`` statement to + convert a table to a new storage engine (such as InnoDB):: + + ALTER TABLE ENGINE=INNODB; + + This can be tedious if you have a lot of tables. + + * Another option is to use the ``init_command`` option for MySQLdb prior to + creating your tables:: + + DATABASE_OPTIONS = { + # ... + "init_command": "SET storage_engine=INNODB", + # ... + } + + This sets the default storage engine upon connecting to the database. + After your tables have been created, you should remove this option. + + * Another method for changing the storage engine is described in + AlterModelOnSyncDB_. + +.. _AlterModelOnSyncDB: http://code.djangoproject.com/wiki/AlterModelOnSyncDB + 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 13a32bd0b8..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`: http://www.djangoproject.com/documentation/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: http://www.djangoproject.com/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') @@ -526,6 +535,21 @@ Examples:: >>> 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 +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() + [] + ``select_related()`` ~~~~~~~~~~~~~~~~~~~~ @@ -574,13 +598,28 @@ 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. Note that ``select_related()`` does not follow foreign keys that have ``null=True``. +Usually, using ``select_related()`` can vastly improve performance because your +app can avoid many database calls. However, in situations with deeply nested +sets of relationships ``select_related()`` can sometimes end up following "too +many" relations, and can generate queries so large that they end up being slow. + +In these situations, you can use the ``depth`` argument to ``select_related()`` +to control how many "levels" of relations ``select_related()`` will actually +follow:: + + b = Book.objects.select_related(depth=1).get(id=4) + p = b.author # Doesn't hit the database. + 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)`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -684,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)`` @@ -876,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:: @@ -1106,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:: @@ -1119,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 @@ -1151,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:: @@ -1160,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:: @@ -1199,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`` @@ -1606,6 +1645,15 @@ For example, this deletes all ``Entry`` objects with a ``pub_date`` year of Entry.objects.filter(pub_date__year=2005).delete() +When Django deletes an object, it emulates the behavior of the SQL +constraint ``ON DELETE CASCADE`` -- in other words, any objects which +had foreign keys pointing at the object to be deleted will be deleted +along with it. For example:: + + b = Blog.objects.get(pk=1) + # This will delete the Blog and all of its Entry objects. + b.delete() + Note that ``delete()`` is the only ``QuerySet`` method that is not exposed on a ``Manager`` itself. This is a safety mechanism to prevent you from accidentally requesting ``Entry.objects.delete()``, and deleting *all* the entries. If you @@ -1704,6 +1752,47 @@ For every ``ImageField``, the object will have ``get_FOO_height()`` and ``get_FOO_width()`` methods, where ``FOO`` is the name of the field. This returns the height (or width) of the image, as an integer, in pixels. +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. 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 +``get()`` function. It raises ``Http404`` if the object doesn't +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 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' + a = get_object_or_404(e.authors, name='Fred') + + # Use a custom manager 'recent_entries' in the search for an + # entry with a primary key of 3 + e = get_object_or_404(Entry.recent_entries, pk=3) + +get_list_or_404() +----------------- + +``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 ======================= @@ -1722,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: http://www.djangoproject.com/documentation/model_api/#executing-custom-sql +.. _Executing custom SQL: ../model-api/#executing-custom-sql diff --git a/docs/design_philosophies.txt b/docs/design_philosophies.txt index 7fdc7ea01b..72aa8ade95 100644 --- a/docs/design_philosophies.txt +++ b/docs/design_philosophies.txt @@ -186,7 +186,7 @@ code. This is the philosophy behind `template inheritance`_. -.. _template inheritance: http://www.djangoproject.com/documentation/templates/#template-inheritance +.. _template inheritance: ../templates/#template-inheritance Be decoupled from HTML ---------------------- diff --git a/docs/distributions.txt b/docs/distributions.txt new file mode 100644 index 0000000000..4ec265f93c --- /dev/null +++ b/docs/distributions.txt @@ -0,0 +1,78 @@ +=================================== +Third-party distributions of Django +=================================== + +Several third-party distributors are now providing versions of Django integrated +with their package-management systems. These can make installation and upgrading +much easier for users of Django since the integration includes the ability to +automatically install dependancies (like database adapters) that Django +requires. + +Typically, these packages are based on the latest stable release of Django, so +if you want to use the development version of Django you'll need to follow the +instructions for `installing the development version`_ from our Subversion +repository. + +.. _installing the development version: ../install/#installing-the-development-version + +Linux distributions +=================== + +Debian +------ + +A `packaged version of Django`_ is available for `Debian GNU/Linux`_, and can be +installed from either the "testing" or the "unstable" repositories by typing +``apt-get install python-django``. + +When you install this package, ``apt`` will recommend installing a database +adapter; you should select and install the adapter for whichever database you +plan to use with Django. + +.. _Debian GNU/Linux: http://www.debian.org/ +.. _packaged version of Django: http://packages.debian.org/testing/python/python-django + +Ubuntu +------ + +The Debian ``python-django`` package is also available for `Ubuntu Linux`_, in +the "universe" repository for Ubuntu 7.04 ("Feisty Fawn"). The `current Ubuntu +package`_ is also based on Django 0.95.1 and can be installed in the same +fashion as for Debian. + +.. _Ubuntu Linux: http://www.ubuntu.com/ +.. _current Ubuntu package: http://packages.ubuntu.com/feisty/python/python-django + +Fedora +------ + +A Django package is available for `Fedora Linux`_, in the "Fedora Extras" +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://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.96. +The `current Gentoo build`_ can be installed by typing ``emerge django``. + +.. _Gentoo Linux: http://www.gentoo.org/ +.. _current Gentoo build: http://packages.gentoo.org/packages/?category=dev-python;name=django + +For distributors +================ + +If you'd like to package Django for distribution, we'd be happy to help out! +Please join the `django-developers mailing list`_ and introduce yourself. + +We also encourage all distributors to subscribe to the `django-announce mailing +list`_, which is a (very) low-traffic list for announcing new releases of Django +and important bugfixes. + +.. _django-developers mailing list: http://groups.google.com/group/django-developers/ +.. _django-announce mailing list: http://groups.google.com/group/django-announce/ diff --git a/docs/django-admin.txt b/docs/django-admin.txt index 7f9682b443..d20db7edc9 100644 --- a/docs/django-admin.txt +++ b/docs/django-admin.txt @@ -17,13 +17,21 @@ two things for you before delegating to ``django-admin.py``: The ``django-admin.py`` script should be on your system path if you installed Django via its ``setup.py`` utility. If it's not on your path, you can find it in ``site-packages/django/bin`` within your Python installation. Consider -symlinking to it from some place on your path, such as ``/usr/local/bin``. +symlinking it from some place on your path, such as ``/usr/local/bin``. + +For Windows users, who do not have symlinking functionality available, you +can copy ``django-admin.py`` to a location on your existing path or edit the +``PATH`` settings (under ``Settings - Control Panel - System - Advanced - Environment...``) +to point to its installed location. Generally, when working on a single Django project, it's easier to use ``manage.py``. Use ``django-admin.py`` with ``DJANGO_SETTINGS_MODULE``, or the ``--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 ===== @@ -53,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: http://www.djangoproject.com/documentation/tutorial2/ +.. _Tutorial 2: ../tutorial02/ createcachetable [tablename] ---------------------------- @@ -61,7 +69,7 @@ createcachetable [tablename] Creates a cache table named ``tablename`` for use with the database cache backend. See the `cache documentation`_ for more information. -.. _cache documentation: http://www.djangoproject.com/documentation/cache/ +.. _cache documentation: ../cache/ dbshell ------- @@ -92,6 +100,30 @@ example, the default settings don't define ``ROOT_URLCONF``, so Note that Django's default settings live in ``django/conf/global_settings.py``, 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 +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). 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``. + +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 +post-synchronization handlers will be re-executed, and the ``initial_data`` +fixture will be re-installed. + inspectdb --------- @@ -133,10 +165,87 @@ needed. ``inspectdb`` works with PostgreSQL, MySQL and SQLite. Foreign-key detection only works in PostgreSQL and with certain types of MySQL tables. -install [appname appname ...] ------------------------------ +loaddata [fixture fixture ...] +------------------------------ + +Searches for and loads the contents of the named fixture into the database. + +A *Fixture* is a collection of files that contain the serialized contents of +the database. Each fixture has a unique name; however, the files that +comprise the fixture can be distributed over multiple directories, in +multiple applications. + +Django will search in three locations for fixtures: + + 1. In the ``fixtures`` directory of every installed application + 2. In any directory named in the ``FIXTURE_DIRS`` setting + 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. + +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 +``xml``). + +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 +``loaddata`` will be removed from the database. + +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 +``FIXTURE_DIRS``, and the literal path ``foo/bar/mydata.json``. + +Note that the order in which fixture files are processed is undefined. However, +all fixture data is installed as a single transaction, so data in +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 + 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. + +reset [appname appname ...] +--------------------------- +Executes the equivalent of ``sqlreset`` for the given appnames. + +runfcgi [options] +----------------- +Starts a set of FastCGI processes suitable for use with any web server +which supports the FastCGI protocol. See the `FastCGI deployment +documentation`_ for details. Requires the Python FastCGI module from +`flup`_. -Executes the equivalent of ``sqlall`` for the given appnames. +.. _FastCGI deployment documentation: ../fastcgi/ +.. _flup: http://www.saddi.com/software/flup/ runserver [optional port number, or ipaddr:port] ------------------------------------------------ @@ -186,11 +295,11 @@ 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. -.. _serving static files: http://www.djangoproject.com/documentation/static_files/ +.. _serving static files: ../static_files/ Turning off auto-reload ~~~~~~~~~~~~~~~~~~~~~~~ @@ -223,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 ...] @@ -231,27 +340,29 @@ sqlclear [appname appname ...] Prints the DROP TABLE SQL statements for the given appnames. -sqlindexes [appname appname ...] ----------------------------------------- - -Prints the CREATE INDEX SQL statements for the given appnames. +sqlcustom [appname appname ...] +------------------------------- -sqlinitialdata [appname appname ...] --------------------------------------------- - -Prints the initial INSERT SQL statements for the given appnames. +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. Each of the SQL files, 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. Use this SQL hook to populate -tables with any necessary initial records, SQL functions or test data. +table-creation statements have been executed. Use this SQL hook to make any +table modifications, or insert any SQL functions into the database. + +Note that the order in which the SQL files are processed is undefined. + +sqlindexes [appname appname ...] +---------------------------------------- + +Prints the CREATE INDEX SQL statements for the given appnames. sqlreset [appname appname ...] -------------------------------------- @@ -261,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. @@ -292,11 +403,14 @@ 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`` +with an appropriate extension (e.g. ``json`` or ``xml``). See the +documentation for ``loaddata`` for details on the specification of fixture +data files. + test ---- -**New in Django development version** - Discover and run tests for all installed models. See `Testing Django applications`_ for more information. .. _testing django applications: ../testing/ @@ -341,17 +455,36 @@ setting the Python path for you. .. _import search path: http://diveintopython.org/getting_to_know_python/everything_is_an_object.html +--format +-------- + +Example usage:: + + django-admin.py dumpdata --format=xml + +Specifies the output format that will be used. The name provided must be the name +of a registered serializer. + --help ------ Displays a help message that includes a terse list of all available actions and options. +--indent +-------- + +Example usage:: + + django-admin.py dumpdata --indent=4 + +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. + --noinput --------- -**New in Django development version** - Inform django-admin that the user should NOT be prompted for any input. Useful if the django-admin script will be executed as an unattended, automated script. @@ -374,23 +507,20 @@ Example output:: --verbosity ----------- -**New in Django development version** - Example usage:: django-admin.py syncdb --verbosity=2 -Verbosity determines the amount of notification and debug information that +Verbosity determines the amount of notification and debug information that will be printed to the console. '0' is no output, '1' is normal output, and `2` is verbose output. --adminmedia ------------ -**New in Django development version** - 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 37a4f38a5e..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() =========== @@ -34,8 +44,8 @@ The simplest way to send e-mail is using the function ``django.core.mail.send_mail()``. Here's its definition:: send_mail(subject, message, from_email, recipient_list, - fail_silently=False, auth_user=EMAIL_HOST_USER, - auth_password=EMAIL_HOST_PASSWORD) + fail_silently=False, auth_user=None, + auth_password=None) The ``subject``, ``message``, ``from_email`` and ``recipient_list`` parameters are required. @@ -65,7 +75,7 @@ send_mass_mail() Here's the definition:: send_mass_mail(datatuple, fail_silently=False, - auth_user=EMAIL_HOST_USER, auth_password=EMAIL_HOST_PASSWORD): + auth_user=None, auth_password=None): ``datatuple`` is a tuple in which each element is in this format:: @@ -101,9 +111,9 @@ The "From:" header of the e-mail will be the value of the `SERVER_EMAIL setting` This method exists for convenience and readability. -.. _ADMINS setting: http://www.djangoproject.com/documentation/settings/#admins -.. _EMAIL_SUBJECT_PREFIX setting: http://www.djangoproject.com/documentation/settings/#email-subject-prefix -.. _SERVER_EMAIL setting: http://www.djangoproject.com/documentation/settings/#server-email +.. _ADMINS setting: ../settings/#admins +.. _EMAIL_SUBJECT_PREFIX setting: ../settings/#email-subject-prefix +.. _SERVER_EMAIL setting: ../settings/#server-email mail_managers() function ======================== @@ -114,7 +124,7 @@ Here's the definition:: mail_managers(subject, message, fail_silently=False) -.. _MANAGERS setting: http://www.djangoproject.com/documentation/settings/#managers +.. _MANAGERS setting: ../settings/#managers Examples ======== @@ -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 eaccc6be43..bdd8c5360e 100644 --- a/docs/faq.txt +++ b/docs/faq.txt @@ -63,7 +63,7 @@ at any level -- database servers, caching servers or Web/application servers. The framework cleanly separates components such as its database layer and application layer. And it ships with a simple-yet-powerful `cache framework`_. -.. _`cache framework`: http://www.djangoproject.com/documentation/cache/ +.. _`cache framework`: ../cache/ Who's behind this? ------------------ @@ -191,7 +191,7 @@ Like we said: We're picky. We've documented our philosophies on the `design philosophies page`_. -.. _design philosophies page: http://www.djangoproject.com/documentation/design_philosophies/ +.. _design philosophies page: ../design_philosophies/ Do you have any of those nifty "screencast" things? --------------------------------------------------- @@ -277,9 +277,9 @@ How do I get started? run into trouble. .. _`Download the code`: http://www.djangoproject.com/download/ -.. _`installation guide`: http://www.djangoproject.com/documentation/install/ -.. _tutorial: http://www.djangoproject.com/documentation/tutorial1/ -.. _documentation: http://www.djangoproject.com/documentation/ +.. _`installation guide`: ../install/ +.. _tutorial: ../tutorial01/ +.. _documentation: ../ .. _ask questions: http://www.djangoproject.com/community/ How do I fix the "install a later version of setuptools" error? @@ -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: http://www.djangoproject.com/documentation/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). @@ -464,7 +465,7 @@ Can I use Django with a pre-existing database? Yes. See `Integrating with a legacy database`_. -.. _`Integrating with a legacy database`: http://www.djangoproject.com/documentation/legacy_databases/ +.. _`Integrating with a legacy database`: ../legacy_databases/ If I make changes to a model, how do I update the database? ----------------------------------------------------------- @@ -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: http://www.djangoproject.com/documentation/model_api/#providing-initial-sql-data +.. _SQL initial data file: ../model-api/#providing-initial-sql-data Why is Django leaking memory? ----------------------------- @@ -592,7 +593,7 @@ My admin-site CSS and images showed up fine using the development server, but th See `serving the admin files`_ in the "How to use Django with mod_python" documentation. -.. _serving the admin files: http://www.djangoproject.com/documentation/modpython/#serving-the-admin-files +.. _serving the admin files: ../modpython/#serving-the-admin-files My "list_filter" contains a ManyToManyField, but the filter doesn't display. ---------------------------------------------------------------------------- @@ -630,7 +631,7 @@ site is built using semantic HTML and plenty of CSS hooks, so any changes you'd like to make should be possible by editing the stylesheet. We've got a `guide to the CSS used in the admin`_ to get you started. -.. _`guide to the CSS used in the admin`: http://www.djangoproject.com/documentation/admin_css/ +.. _`guide to the CSS used in the admin`: ../admin_css/ How do I create users without having to edit password hashes? ------------------------------------------------------------- @@ -640,7 +641,7 @@ development version, where this problem was fixed on Aug. 4, 2006. You can also use the Python API. See `creating users`_ for full info. -.. _creating users: http://www.djangoproject.com/documentation/authentication/#creating-users +.. _creating users: ../authentication/#creating-users Contributing code ================= @@ -651,7 +652,7 @@ How can I get started contributing code to Django? Thanks for asking! We've written an entire document devoted to this question. It's titled `Contributing to Django`_. -.. _Contributing to Django: http://www.djangoproject.com/documentation/contributing/ +.. _Contributing to Django: ../contributing/ I submitted a bug fix in the ticket system several weeks ago. Why are you ignoring my patch? -------------------------------------------------------------------------------------------- diff --git a/docs/fastcgi.txt b/docs/fastcgi.txt index e2f4e933b4..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 @@ -17,7 +23,7 @@ served with no startup time. Unlike mod_python (or `mod_perl`_), a FastCGI process doesn't run inside the Web server process, but in a separate, persistent process. -.. _current preferred setup: http://www.djangoproject.com/documentation/modpython/ +.. _current preferred setup: ../modpython/ .. _Apache: http://httpd.apache.org/ .. _mod_python: http://www.modpython.org/ .. _mod_perl: http://perl.apache.org/ @@ -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] @@ -274,7 +296,7 @@ In your Web root directory, add this to a file named ``.htaccess`` :: Then, create a small script that tells Apache how to spawn your FastCGI program. Create a file ``mysite.fcgi`` and place it in your Web directory, and -be sure to make it executable :: +be sure to make it executable:: #!/usr/bin/python import sys, os @@ -304,3 +326,14 @@ If you have access to a command shell on a Unix system, you can accomplish this easily by using the ``touch`` command:: touch mysite.fcgi + +Serving admin media files +========================= + +Regardless of the server and configuration you eventually decide to use, you will +also need to give some thought to how to serve the admin media files. The +advice given in the modpython_ documentation is also applicable in the setups +detailed above. + +.. _modpython: ../modpython/#serving-the-admin-files + diff --git a/docs/flatpages.txt b/docs/flatpages.txt index 06979f7a9a..1422f16b6b 100644 --- a/docs/flatpages.txt +++ b/docs/flatpages.txt @@ -29,8 +29,8 @@ To install the flatpages app, follow these steps: to your MIDDLEWARE_CLASSES_ setting. 3. Run the command ``manage.py syncdb``. -.. _INSTALLED_APPS: http://www.djangoproject.com/documentation/settings/#installed-apps -.. _MIDDLEWARE_CLASSES: http://www.djangoproject.com/documentation/settings/#middleware-classes +.. _INSTALLED_APPS: ../settings/#installed-apps +.. _MIDDLEWARE_CLASSES: ../settings/#middleware-classes How it works ============ @@ -63,9 +63,9 @@ resort. For more on middleware, read the `middleware docs`_. -.. _SITE_ID: http://www.djangoproject.com/documentation/settings/#site-id -.. _RequestContext: http://www.djangoproject.com/documentation/templates_python/#subclassing-context-djangocontext -.. _middleware docs: http://www.djangoproject.com/documentation/middleware/ +.. _SITE_ID: ../settings/#site-id +.. _RequestContext: ../templates_python/#subclassing-context-djangocontext +.. _middleware docs: ../middleware/ How to add, change and delete flatpages ======================================= @@ -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: http://www.djangoproject.com/documentation/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: http://www.djangoproject.com/documentation/db_api/ +.. _Django database API: ../db-api/ Flatpage templates ================== diff --git a/docs/forms.txt b/docs/forms.txt index 6efa24d28f..f6cb55a3f6 100644 --- a/docs/forms.txt +++ b/docs/forms.txt @@ -14,7 +14,7 @@ use the django.newforms system, which we have begun to document in the If you have legacy form/manipulator code, read the "Migration plan" section in that document to understand how we're making the switch. -.. _newforms documentation: http://www.djangoproject.com/documentation/newforms/ +.. _newforms documentation: ../newforms/ Introduction ============ @@ -173,10 +173,10 @@ creation view that takes validation into account:: # Check for validation errors errors = manipulator.get_validation_errors(new_data) + manipulator.do_html2python(new_data) if errors: return render_to_response('places/errors.html', {'errors': errors}) else: - manipulator.do_html2python(new_data) new_place = manipulator.save(new_data) return HttpResponse("Place created: %s" % new_place) @@ -229,10 +229,10 @@ Below is the finished view:: # Check for errors. errors = manipulator.get_validation_errors(new_data) + manipulator.do_html2python(new_data) if not errors: # No errors. This means we can save the data! - manipulator.do_html2python(new_data) new_place = manipulator.save(new_data) # Redirect to the object's "edit" page. Always use a redirect @@ -324,8 +324,8 @@ about editing an existing one? It's shockingly similar to creating a new one:: if request.method == 'POST': new_data = request.POST.copy() errors = manipulator.get_validation_errors(new_data) + manipulator.do_html2python(new_data) if not errors: - manipulator.do_html2python(new_data) manipulator.save(new_data) # Do a post-after-redirect so that reload works, etc. @@ -406,8 +406,8 @@ Here's a simple function that might drive the above form:: if request.method == 'POST': new_data = request.POST.copy() errors = manipulator.get_validation_errors(new_data) + manipulator.do_html2python(new_data) if not errors: - manipulator.do_html2python(new_data) # Send e-mail using new_data here... @@ -417,6 +417,27 @@ Here's a simple function that might drive the above form:: form = forms.FormWrapper(manipulator, new_data, errors) return render_to_response('contact_form.html', {'form': form}) +Implementing ``flatten_data`` for custom manipulators +------------------------------------------------------ + +It is possible (although rarely needed) to replace the default automatically +created manipulators on a model with your own custom manipulators. If you do +this and you are intending to use those models in generic views, you should +also define a ``flatten_data`` method in any ``ChangeManipulator`` replacement. +This should act like the default ``flatten_data`` and return a dictionary +mapping field names to their values, like so:: + + def flatten_data(self): + obj = self.original_object + return dict( + from = obj.from, + subject = obj.subject, + ... + ) + +In this way, your new change manipulator will act exactly like the default +version. + ``FileField`` and ``ImageField`` special cases ============================================== @@ -496,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. @@ -546,6 +567,7 @@ check for the given property: * isValidANSIDate * isValidANSITime * isValidEmail + * isValidFloat * isValidImage * isValidImageURL * isValidPhone @@ -594,20 +616,28 @@ 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 given value, then the current field being validated is required. + An optional ``other_label`` argument can be passed which, if given, is used + in error messages instead of the value. This allows more user friendly error + messages if the value itself is not descriptive enough. + Note that because validators are called before any ``do_html2python()`` functions, the value being compared against is a string. So ``RequiredIfOtherFieldEquals('choice', '1')`` is correct, whilst @@ -625,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). @@ -635,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 @@ -665,6 +695,6 @@ fails. If no message is passed in, a default message is used. the executable specified in the ``JING_PATH`` setting (see the settings_ document for more details). -.. _`generic views`: http://www.djangoproject.com/documentation/generic_views/ -.. _`models API`: http://www.djangoproject.com/documentation/model_api/ -.. _settings: http://www.djangoproject.com/documentation/settings/ +.. _`generic views`: ../generic_views/ +.. _`models API`: ../model-api/ +.. _settings: ../settings/ diff --git a/docs/generic_views.txt b/docs/generic_views.txt index 25635f35d8..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: http://www.djangoproject.com/documentation/db_api/ +.. _database API docs: ../db-api/ "Simple" generic views ====================== @@ -97,9 +97,11 @@ which is a dictionary of the parameters captured in the URL. * ``extra_context``: A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the generic view will call it - just before rendering the template. (**This is new in the - Django development version.**) - + 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:: @@ -205,11 +207,11 @@ If ``template_name`` isn't specified, this view will use the template ``/_archive.html`` by default, where: * ```` is your model's name in all lowercase. For a model - ``StaffMember``, that'd be ``staffmember``. + ``StaffMember``, that'd be ``staffmember``. * ```` is the right-most part of the full Python path to - your model's app. For example, if your model lives in - ``apps/blog/models.py``, that'd be ``blog``. + your model's app. For example, if your model lives in + ``apps/blog/models.py``, that'd be ``blog``. **Template context:** @@ -223,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: http://www.djangoproject.com/documentation/templates_python/#subclassing-context-djangocontext +.. _RequestContext docs: ../templates_python/#subclassing-context-requestcontext ``django.views.generic.date_based.archive_year`` ------------------------------------------------ @@ -266,9 +268,9 @@ to ``True``. the view's template. See the `RequestContext docs`_. * ``template_object_name``: Designates the name of the template variable - to use in the template context. By default, this is ``'object'``. The - view will append ``'_list'`` to the value of this parameter in - determining the variable's name. + to use in the template context. By default, this is ``'object'``. The + view will append ``'_list'`` to the value of this parameter in + determining the variable's name. * ``make_object_list``: A boolean specifying whether to retrieve the full list of objects for this year and pass those to the template. If ``True``, @@ -360,9 +362,9 @@ date in the *future* are not displayed unless you set ``allow_future`` to the view's template. See the `RequestContext docs`_. * ``template_object_name``: Designates the name of the template variable - to use in the template context. By default, this is ``'object'``. The - view will append ``'_list'`` to the value of this parameter in - determining the variable's name. + to use in the template context. By default, this is ``'object'``. The + view will append ``'_list'`` to the value of this parameter in + determining the variable's name. * ``mimetype``: The MIME type to use for the resulting document. Defaults to the value of the ``DEFAULT_CONTENT_TYPE`` setting. @@ -441,9 +443,9 @@ in the *future* are not displayed unless you set ``allow_future`` to ``True``. the view's template. See the `RequestContext docs`_. * ``template_object_name``: Designates the name of the template variable - to use in the template context. By default, this is ``'object'``. The - view will append ``'_list'`` to the value of this parameter in - determining the variable's name. + to use in the template context. By default, this is ``'object'``. The + view will append ``'_list'`` to the value of this parameter in + determining the variable's name. * ``mimetype``: The MIME type to use for the resulting document. Defaults to the value of the ``DEFAULT_CONTENT_TYPE`` setting. @@ -526,9 +528,9 @@ you set ``allow_future`` to ``True``. the view's template. See the `RequestContext docs`_. * ``template_object_name``: Designates the name of the template variable - to use in the template context. By default, this is ``'object'``. The - view will append ``'_list'`` to the value of this parameter in - determining the variable's name. + to use in the template context. By default, this is ``'object'``. The + view will append ``'_list'`` to the value of this parameter in + determining the variable's name. * ``mimetype``: The MIME type to use for the resulting document. Defaults to the value of the ``DEFAULT_CONTENT_TYPE`` setting. @@ -638,7 +640,7 @@ future, the view will throw a 404 error by default, unless you set the view's template. See the `RequestContext docs`_. * ``template_object_name``: Designates the name of the template variable - to use in the template context. By default, this is ``'object'``. + to use in the template context. By default, this is ``'object'``. * ``mimetype``: The MIME type to use for the resulting document. Defaults to the value of the ``DEFAULT_CONTENT_TYPE`` setting. @@ -686,7 +688,7 @@ A page representing a list of objects. * ``paginate_by``: An integer specifying how many objects should be displayed per page. If this is given, the view will paginate objects with ``paginate_by`` objects per page. The view will expect either a ``page`` - query string parameter (via ``GET``) containing a zero-indexed page + query string parameter (via ``GET``) containing a 1-based page number, or a ``page`` variable specified in the URLconf. See "Notes on pagination" below. @@ -710,9 +712,9 @@ A page representing a list of objects. the view's template. See the `RequestContext docs`_. * ``template_object_name``: Designates the name of the template variable - to use in the template context. By default, this is ``'object'``. The - view will append ``'_list'`` to the value of this parameter in - determining the variable's name. + to use in the template context. By default, this is ``'object'``. The + view will append ``'_list'`` to the value of this parameter in + determining the variable's name. * ``mimetype``: The MIME type to use for the resulting document. Defaults to the value of the ``DEFAULT_CONTENT_TYPE`` setting. @@ -752,6 +754,12 @@ If the results are paginated, the context will contain these extra variables: * ``previous``: The previous page number, as an integer. This is 1-based. + * `last_on_page`: The number of the + last result on the current page. This is 1-based. + + * `first_on_page`: The number of the + first result on the current page. This is 1-based. + * ``pages``: The total number of pages, as an integer. * ``hits``: The total number of objects across *all* pages, not just this @@ -824,7 +832,7 @@ A page representing an individual object. the view's template. See the `RequestContext docs`_. * ``template_object_name``: Designates the name of the template variable - to use in the template context. By default, this is ``'object'``. + to use in the template context. By default, this is ``'object'``. * ``mimetype``: The MIME type to use for the resulting document. Defaults to the value of the ``DEFAULT_CONTENT_TYPE`` setting. @@ -916,8 +924,8 @@ In addition to ``extra_context``, the template's context will be: See the `manipulator and formfield documentation`_ for more information about using ``FormWrapper`` objects in templates. -.. _authentication system: http://www.djangoproject.com/documentation/authentication/ -.. _manipulator and formfield documentation: http://www.djangoproject.com/documentation/forms/ +.. _authentication system: ../authentication/ +.. _manipulator and formfield documentation: ../forms/ ``django.views.generic.create_update.update_object`` ---------------------------------------------------- @@ -973,7 +981,7 @@ object. This uses the automatic manipulators that come with Django models. the view's template. See the `RequestContext docs`_. * ``template_object_name``: Designates the name of the template variable - to use in the template context. By default, this is ``'object'``. + to use in the template context. By default, this is ``'object'``. **Template name:** @@ -1054,7 +1062,7 @@ contain a form that POSTs to the same URL. the view's template. See the `RequestContext docs`_. * ``template_object_name``: Designates the name of the template variable - to use in the template context. By default, this is ``'object'``. + to use in the template context. By default, this is ``'object'``. **Template name:** diff --git a/docs/i18n.txt b/docs/i18n.txt index 4d0d92b082..27abadacc9 100644 --- a/docs/i18n.txt +++ b/docs/i18n.txt @@ -53,7 +53,7 @@ internationalization machinery. See the `documentation for USE_I18N`_. You'll probably also want to remove ``'django.core.context_processors.i18n'`` from your ``TEMPLATE_CONTEXT_PROCESSORS`` setting. -.. _documentation for USE_I18N: http://www.djangoproject.com/documentation/settings/#use-i18n +.. _documentation for USE_I18N: ../settings/#use-i18n How to specify translation strings ================================== @@ -175,7 +175,7 @@ class, though:: verbose_name = _('my thing') verbose_name_plural = _('mythings') -.. _Django models: http://www.djangoproject.com/documentation/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. @@ -274,7 +274,7 @@ translation string. Example:: In this case, both the tag and the filter will see the already-translated string, so they don't need to be aware of translations. -.. _Django templates: http://www.djangoproject.com/documentation/templates_python/ +.. _Django templates: ../templates_python/ How to create language files ============================ @@ -282,6 +282,17 @@ How to create language files Once you've tagged your strings for later translation, you need to write (or obtain) the language translations themselves. Here's how that works. +.. admonition:: Locale restrictions + + Django does not support localizing your application into a locale for + which Django itself has not been translated. In this case, it will ignore + your translation files. If you were to try this and Django supported it, + you would inevitably see a mixture of translated strings (from your + application) and English strings (from Django itself). If you want to + support a locale for your application that is not already part of + Django, you'll need to make at least a minimal translation of the Django + core. + Message files ------------- @@ -299,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: @@ -394,7 +405,7 @@ That's it. Your translations are ready for use. please let us know! See `Submitting and maintaining translations`_ for the steps to take. - .. _Submitting and maintaining translations: http://www.djangoproject.com/documentation/contributing/ + .. _Submitting and maintaining translations: ../contributing/ How Django discovers language preference ======================================== @@ -452,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 @@ -472,7 +483,7 @@ Notes: selection to German and English (and any sublanguage, like de-ch or en-us). - .. _LANGUAGES setting: http://www.djangoproject.com/documentation/settings/#languages + .. _LANGUAGES setting: ../settings/#languages * If you define a custom ``LANGUAGES`` setting, as explained in the previous bullet, it's OK to mark the languages as translation strings @@ -530,10 +541,10 @@ Note that, with static (middleware-less) translation, the language is in ``settings.LANGUAGE_CODE``, while with dynamic (middleware) translation, it's in ``request.LANGUAGE_CODE``. -.. _settings file: http://www.djangoproject.com/documentation/settings/ -.. _middleware documentation: http://www.djangoproject.com/documentation/middleware/ -.. _session: http://www.djangoproject.com/documentation/sessions/ -.. _request object: http://www.djangoproject.com/documentation/request_response/#httprequest-objects +.. _settings file: ../settings/ +.. _middleware documentation: ../middleware/ +.. _session: ../sessions/ +.. _request object: ../request_response/#httprequest-objects The ``set_language`` redirect view ================================== @@ -599,7 +610,7 @@ message file. The choice is yours. of the settings file to determine this, and a settings file doesn't exist if you're manually configuring your settings.) -.. _settings documentation: http://www.djangoproject.com/documentation/settings/#using-settings-without-the-django-settings-module-environment-variable +.. _settings documentation: ../settings/#using-settings-without-the-django-settings-module-environment-variable All message file repositories are structured the same way. They are: diff --git a/docs/install.txt b/docs/install.txt index ff8e1a8318..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 ============================= @@ -38,33 +38,68 @@ each platform. .. _Apache: http://httpd.apache.org/ .. _mod_python: http://www.modpython.org/ .. _WSGI: http://www.python.org/peps/pep-0333.html -.. _How to use Django with mod_python: http://www.djangoproject.com/documentation/modpython/ +.. _How to use Django with mod_python: ../modpython/ .. _server-arrangements wiki page: http://code.djangoproject.com/wiki/ServerArrangements 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 1.1 -- - not version 1.0 or version 2, which is still in beta). If you're on Windows, - check out the unofficial `compiled Windows version`_. -* If you're using MySQL, you'll need MySQLdb_. +* 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. .. _PostgreSQL: http://www.postgresql.org/ .. _MySQL: http://www.mysql.com/ .. _Django's ticket system: http://code.djangoproject.com/report/1 -.. _psycopg: http://initd.org/projects/psycopg1 +.. _psycopg: http://initd.org/tracker/psycopg .. _compiled Windows version: http://stickpeople.com/projects/python/win-psycopg/ .. _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 ======================= @@ -77,22 +112,23 @@ It's easy either way. Installing the official version ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -1. Download Django-0.95.tar.gz from our `download page`_. -2. ``tar xzvf Django-0.95.tar.gz`` -3. ``cd Django-0.95`` -4. ``sudo python setup.py install`` + 1. Check the `distribution specific notes`_ to see if your + platform/distribution provides official Django packages/installers. + Distribution-provided packages will typically allow for automatic + installation of dependancies and easy upgrade paths. + + 2. Download the latest release from our `download page`_. + + 3. Untar the downloaded file (e.g. ``tar xzvf Django-NNN.tar.gz``). + + 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 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -113,14 +149,14 @@ latest bug fixes and improvements, follow these instructions: svn co http://code.djangoproject.com/svn/django/trunk/django c:\Python24\lib\site-packages\django -4. Copy the file ``django_src/django/bin/django-admin.py`` to somewhere on your +3. Copy the file ``django_src/django/bin/django-admin.py`` to somewhere on your system path, such as ``/usr/local/bin`` (Unix) or ``C:\Python24\Scripts`` (Windows). This step simply lets you type ``django-admin.py`` from within any directory, rather than having to qualify the command with the full path to the file. You *don't* have to run ``python setup.py install``, because that command -takes care of steps 3 and 4 for you. +takes care of steps 2 and 3 for you. When you want to update your copy of the Django source code, just run the command ``svn update`` from within the ``django`` directory. When you do this, diff --git a/docs/legacy_databases.txt b/docs/legacy_databases.txt index 66cb1a2ef4..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: http://www.djangoproject.com/documentation/tutorial1/ +.. _official tutorial: ../tutorial01/ Give Django your database parameters ==================================== @@ -22,18 +22,16 @@ what the name of the database is. Do that by editing these settings in your * `DATABASE_ENGINE`_ * `DATABASE_USER`_ * `DATABASE_PASSWORD`_ - * `DATABASE_NAME`_ * `DATABASE_HOST`_ * `DATABASE_PORT`_ -.. _settings file: http://www.djangoproject.com/documentation/settings/ -.. _DATABASE_NAME: http://www.djangoproject.com/documentation/settings/#database-name -.. _DATABASE_ENGINE: http://www.djangoproject.com/documentation/settings/#database-engine -.. _DATABASE_USER: http://www.djangoproject.com/documentation/settings/#database-user -.. _DATABASE_PASSWORD: http://www.djangoproject.com/documentation/settings/#database-password -.. _DATABASE_NAME: http://www.djangoproject.com/documentation/settings/#database-name -.. _DATABASE_HOST: http://www.djangoproject.com/documentation/settings/#database-host -.. _DATABASE_PORT: http://www.djangoproject.com/documentation/settings/#database-port +.. _settings file: ../settings/ +.. _DATABASE_NAME: ../settings/#database-name +.. _DATABASE_ENGINE: ../settings/#database-engine +.. _DATABASE_USER: ../settings/#database-user +.. _DATABASE_PASSWORD: ../settings/#database-password +.. _DATABASE_HOST: ../settings/#database-host +.. _DATABASE_PORT: ../settings/#database-port Auto-generate the models ======================== @@ -41,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. @@ -54,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: http://www.djangoproject.com/documentation/django_admin/ +.. _django-admin.py documentation: ../django-admin/ Install the core Django tables ============================== @@ -62,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/middleware.txt b/docs/middleware.txt index efc4d89569..0d533443d3 100644 --- a/docs/middleware.txt +++ b/docs/middleware.txt @@ -47,7 +47,7 @@ Enables site-wide cache. If this is enabled, each Django-powered page will be cached for as long as the ``CACHE_MIDDLEWARE_SECONDS`` setting defines. See the `cache documentation`_. -.. _`cache documentation`: http://www.djangoproject.com/documentation/cache/#the-per-site-cache +.. _`cache documentation`: ../cache/#the-per-site-cache django.middleware.common.CommonMiddleware ----------------------------------------- @@ -104,11 +104,10 @@ Also removes the content from any response to a HEAD request and sets the django.middleware.http.SetRemoteAddrFromForwardedFor ---------------------------------------------------- -**New in Django development version** - -Sets ``request['REMOTE_ADDR']`` based on ``request.['HTTP_X_FORWARDED_FOR']``, -if the latter is set. This is useful if you're sitting behind a reverse proxy -that causes each request's ``REMOTE_ADDR`` to be set to ``127.0.0.1``. +Sets ``request.META['REMOTE_ADDR']`` based on +``request.META['HTTP_X_FORWARDED_FOR']``, if the latter is set. This is useful +if you're sitting behind a reverse proxy that causes each request's +``REMOTE_ADDR`` to be set to ``127.0.0.1``. **Important note:** This does NOT validate ``HTTP_X_FORWARDED_FOR``. If you're not behind a reverse proxy that sets ``HTTP_X_FORWARDED_FOR`` automatically, do @@ -122,7 +121,7 @@ django.contrib.sessions.middleware.SessionMiddleware Enables session support. See the `session documentation`_. -.. _`session documentation`: http://www.djangoproject.com/documentation/sessions/ +.. _`session documentation`: ../sessions/ django.contrib.auth.middleware.AuthenticationMiddleware ------------------------------------------------------- @@ -130,7 +129,7 @@ django.contrib.auth.middleware.AuthenticationMiddleware Adds the ``user`` attribute, representing the currently-logged-in user, to every incoming ``HttpRequest`` object. See `Authentication in Web requests`_. -.. _Authentication in Web requests: http://www.djangoproject.com/documentation/authentication/#authentication-in-web-requests +.. _Authentication in Web requests: ../authentication/#authentication-in-web-requests django.middleware.transaction.TransactionMiddleware --------------------------------------------------- @@ -146,7 +145,7 @@ the same transaction control as the view functions. See the `transaction management documentation`_. -.. _`transaction management documentation`: http://www.djangoproject.com/documentation/transactions/ +.. _`transaction management documentation`: ../transactions/ Writing your own middleware =========================== diff --git a/docs/model-api.txt b/docs/model-api.txt index 1aa8c811f4..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 ====== @@ -94,7 +94,7 @@ Django places only two restrictions on model field names: the way Django's query lookup syntax works. For example:: class Example(models.Model): - foo__bar = models.IntegerField() 'foo__bar' has two underscores! + foo__bar = models.IntegerField() # 'foo__bar' has two underscores! These limitations can be worked around, though, because your field name doesn't necessarily have to match your database column name. See `db_column`_ below. @@ -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. - ====================== =================================================== +A floating-point number represented in Python by a ``float`` instance. -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) - -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`` ~~~~~~~~~~~~~~~~ @@ -362,9 +400,8 @@ Like a ``PositiveIntegerField``, but only allows values under a certain containing only letters, numbers, underscores or hyphens. They're generally used in URLs. -In the Django development version, you can specify ``maxlength``. If -``maxlength`` is not specified, Django will use a default length of 50. In -previous Django versions, there's no way to override the length of 50. +Like a CharField, you can specify ``maxlength``. If ``maxlength`` is +not specified, Django will use a default length of 50. Implies ``db_index=True``. @@ -410,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`` ~~~~~~~~~~~~~~~~ @@ -438,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 @@ -451,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 @@ -498,6 +542,12 @@ or outside your model class altogether:: class Foo(models.Model): gender = models.CharField(maxlength=1, choices=GENDER_CHOICES) +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 + 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 yourself hacking ``choices`` to be dynamic, you're probably better off using @@ -621,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 ------------------- @@ -729,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 @@ -787,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 ~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -875,6 +925,10 @@ the relationship should work. All are optional: relationship, allowing ``ManyToMany`` relationships to be non-symmetrical. + ``db_table`` The name of the table to create for storing the many-to-many + data. If this is not provided, Django will assume a default + name based upon the names of the two tables being joined. + ======================= ============================================================ One-to-one relationships @@ -954,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`` ------------------------- @@ -1206,6 +1260,10 @@ screen via ``