master 61b91988b5b3 cached
49 files
1.2 MB
316.8k tokens
16 symbols
1 requests
Download .txt
Showing preview only (1,254K chars total). Download the full file or copy to clipboard to get everything.
Repository: peter-kimanzi/programming-ebooks-to-help-you-code-better
Branch: master
Commit: 61b91988b5b3
Files: 49
Total size: 1.2 MB

Directory structure:
gitextract_7wf_t8i0/

├── Python/
│   └── DjangoBook/
│       ├── Makefile
│       ├── Procfile
│       ├── README.rst
│       ├── app.py
│       ├── appendixA.rst
│       ├── appendixB.rst
│       ├── appendixC.rst
│       ├── appendixD.rst
│       ├── appendixE.rst
│       ├── appendixF.rst
│       ├── appendixG.rst
│       ├── bin/
│       │   └── post_compile
│       ├── chapter01.rst
│       ├── chapter02.rst
│       ├── chapter03.rst
│       ├── chapter04.rst
│       ├── chapter05.rst
│       ├── chapter06.rst
│       ├── chapter07.rst
│       ├── chapter08.rst
│       ├── chapter09.rst
│       ├── chapter10.rst
│       ├── chapter11.rst
│       ├── chapter12.rst
│       ├── chapter13.rst
│       ├── chapter14.rst
│       ├── chapter15.rst
│       ├── chapter16.rst
│       ├── chapter17.rst
│       ├── chapter18.rst
│       ├── chapter19.rst
│       ├── chapter20.rst
│       ├── conf.py
│       ├── frontmatter.rst
│       ├── graphics/
│       │   ├── chapter03.graffle
│       │   └── chapter20.graffle
│       ├── index.rst
│       ├── introduction.rst
│       ├── license.rst
│       ├── requirements.txt
│       └── themes/
│           └── djangobook/
│               ├── layout.html
│               ├── page.html
│               ├── search.html
│               ├── static/
│               │   ├── djangobook.css
│               │   ├── grids-min.css
│               │   ├── pea.py
│               │   └── reset-min.css
│               └── theme.conf.txt
└── README.md

================================================
FILE CONTENTS
================================================

================================================
FILE: Python/DjangoBook/Makefile
================================================
# Makefile for Sphinx documentation
#

# You can set these variables from the command line.
SPHINXOPTS    =
SPHINXBUILD   = sphinx-build
PAPER         =
BUILDDIR      = _build

# Internal variables.
PAPEROPT_a4     = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS   = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS  = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .

.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext

help:
	@echo "Please use \`make <target>' where <target> is one of"
	@echo "  html       to make standalone HTML files"
	@echo "  dirhtml    to make HTML files named index.html in directories"
	@echo "  singlehtml to make a single large HTML file"
	@echo "  pickle     to make pickle files"
	@echo "  json       to make JSON files"
	@echo "  htmlhelp   to make HTML files and a HTML help project"
	@echo "  qthelp     to make HTML files and a qthelp project"
	@echo "  devhelp    to make HTML files and a Devhelp project"
	@echo "  epub       to make an epub"
	@echo "  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
	@echo "  latexpdf   to make LaTeX files and run them through pdflatex"
	@echo "  text       to make text files"
	@echo "  man        to make manual pages"
	@echo "  texinfo    to make Texinfo files"
	@echo "  info       to make Texinfo files and run them through makeinfo"
	@echo "  gettext    to make PO message catalogs"
	@echo "  changes    to make an overview of all changed/added/deprecated items"
	@echo "  linkcheck  to check all external links for integrity"
	@echo "  doctest    to run all doctests embedded in the documentation (if enabled)"

clean:
	-rm -rf $(BUILDDIR)/*

html:
	$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
	@echo
	@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."

dirhtml:
	$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
	@echo
	@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."

singlehtml:
	$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
	@echo
	@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."

pickle:
	$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
	@echo
	@echo "Build finished; now you can process the pickle files."

json:
	$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
	@echo
	@echo "Build finished; now you can process the JSON files."

htmlhelp:
	$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
	@echo
	@echo "Build finished; now you can run HTML Help Workshop with the" \
	      ".hhp project file in $(BUILDDIR)/htmlhelp."

qthelp:
	$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
	@echo
	@echo "Build finished; now you can run "qcollectiongenerator" with the" \
	      ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
	@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/TheDjangoBook.qhcp"
	@echo "To view the help file:"
	@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/TheDjangoBook.qhc"

devhelp:
	$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
	@echo
	@echo "Build finished."
	@echo "To view the help file:"
	@echo "# mkdir -p $$HOME/.local/share/devhelp/TheDjangoBook"
	@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/TheDjangoBook"
	@echo "# devhelp"

epub:
	$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
	@echo
	@echo "Build finished. The epub file is in $(BUILDDIR)/epub."

latex:
	$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
	@echo
	@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
	@echo "Run \`make' in that directory to run these through (pdf)latex" \
	      "(use \`make latexpdf' here to do that automatically)."

latexpdf:
	$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
	@echo "Running LaTeX files through pdflatex..."
	$(MAKE) -C $(BUILDDIR)/latex all-pdf
	@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."

text:
	$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
	@echo
	@echo "Build finished. The text files are in $(BUILDDIR)/text."

man:
	$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
	@echo
	@echo "Build finished. The manual pages are in $(BUILDDIR)/man."

texinfo:
	$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
	@echo
	@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
	@echo "Run \`make' in that directory to run these through makeinfo" \
	      "(use \`make info' here to do that automatically)."

info:
	$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
	@echo "Running Texinfo files through makeinfo..."
	make -C $(BUILDDIR)/texinfo info
	@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."

gettext:
	$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
	@echo
	@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."

changes:
	$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
	@echo
	@echo "The overview file is in $(BUILDDIR)/changes."

linkcheck:
	$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
	@echo
	@echo "Link check complete; look for any errors in the above output " \
	      "or in $(BUILDDIR)/linkcheck/output.txt."

doctest:
	$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
	@echo "Testing of doctests in the sources finished, look at the " \
	      "results in $(BUILDDIR)/doctest/output.txt."


================================================
FILE: Python/DjangoBook/Procfile
================================================
web: gunicorn -kgevent -w4 -b0.0.0.0:$PORT app:app


================================================
FILE: Python/DjangoBook/README.rst
================================================
===============
The Django Book
===============

Welcome to the community edition of the Django Book!

This book was originally published by Apress in 2009, and covered Django 1.0. Since then, it's languished. We're working on getting the book updated to cover Django 1.4, 1.5, and beyond. But **we need your help**, so we're making this book — warts and all — open source in the hopes that it'll find love as a community project.

So, if you'd like to help out, send us a pull request!


================================================
FILE: Python/DjangoBook/app.py
================================================
"""
The simplest possible app that can serve these Sphinx docs and issue
redirects for the previous URLs.
"""

import static
import selector
from unipath import FSPath as Path

app = selector.Selector()

def redirect(to):
    """
    Create a 301 redirect WSGI app.

    `to` may contain str.format-style formatting which'll be formatted against
    the routing arguments (wsgiorg.routing_args).
    """
    def _redirect(environ, start_response):
        args, kwargs = environ['wsgiorg.routing_args']
        start_response('301 MOVED PERMANENTLY',
                       [('Location', to.format(*args, **kwargs))])
        return []
    return _redirect

# Redirects for old doc URLs, since Cool URIs Don't Change.
app.add('/',                    GET=redirect('/en/2.0/index.html'))
app.add('/license/',            GET=redirect('/en/2.0/license.html'))
app.add('/about/',              GET=redirect('/en/2.0/frontmatter.html'))
app.add('/en/1.0/',             GET=redirect('/en/2.0/index.html'))
app.add('/en/1.0/{doc:chunk}/', GET=redirect('/en/2.0/{doc}.html'))
app.add('/en/2.0/{doc:chunk}/', GET=redirect('/en/2.0/{doc}.html'))

# Serve docs at "/en/2.0" still, to leave room for the future.
# One of these days I'll actually do this, not just talk about it!
docs = static.Cling(Path(__file__).parent.child('_build', 'html'))
app.add("/en/2.0|", GET=docs)


================================================
FILE: Python/DjangoBook/appendixA.rst
================================================
======================================
Appendix A: Model Definition Reference
======================================

Chapter 5 explains the basics of defining models, and we use them throughout
the rest of the book. There is, however, a *huge* range of model options
available not covered elsewhere. This appendix explains each possible model
definition option.

Note that although these APIs are considered stable, the Django developers
consistently add new shortcuts and conveniences to the model definition. It's a
good idea to always check the latest documentation online at
http://docs.djangoproject.com/.

Fields
======

The most important part of a model -- and the only required part of a model --
is the list of database fields it defines.

.. admonition:: Field Name Restrictions

    Django places only two restrictions on model field names:

    1. A field name cannot be a Python reserved word, because that would result
       in a Python syntax error. For example::

           class Example(models.Model):
               pass = models.IntegerField() # 'pass' is a reserved word!

    2. A field name cannot contain more than one underscore in a row, due to
       the way Django's query lookup syntax works. For example::

           class Example(models.Model):
               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.

    SQL reserved words, such as ``join``, ``where``, or ``select``, *are* allowed
    as model field names, because Django escapes all database table names and
    column names in every underlying SQL query. It uses the quoting syntax of your
    particular database engine.

Each field in your model should be an instance of the appropriate ``Field``
class. Django uses the field class types to determine a few things:

* The database column type (e.g., ``INTEGER``, ``VARCHAR``).

* The widget to use in Django's forms and admin site, if you care to use it
  (e.g., ``<input type="text">``, ``<select>``).

* The minimal validation requirements, which are used in Django's admin
  interface and by forms.

A complete list of field classes follows, sorted alphabetically. Note that
relationship fields (``ForeignKey``, etc.) are handled in the next section.

AutoField
---------

An ``IntegerField`` that automatically increments according to available IDs.
You usually won't need to use this directly; a primary key field will
automatically be added to your model if you don't specify otherwise.

BooleanField
------------

A true/false field.

.. admonition:: MySQL users...

    A boolean field in MySQL is stored as a ``TINYINT`` column with a value of
    either 0 or 1 (most databases have a proper ``BOOLEAN`` type instead). So,
    for MySQL, only, when a ``BooleanField`` is retrieved from the database
    and stored on a model attribute, it will have the values 1 or 0, rather
    than ``True`` or ``False``. Normally, this shouldn't be a problem, since
    Python guarantees that ``1 == True`` and ``0 == False`` are both true.
    Just be careful if you're writing something like ``obj is True`` when
    ``obj`` is a value from a boolean attribute on a model. If that model was
    constructed using the ``mysql`` backend, the "``is``" test will fail.
    Prefer an equality test (using "``==``") in cases like this.

CharField
---------

A string field, for small- to large-sized strings.

For very large amounts of text, use ``TextField``.

``CharField`` has one extra required argument: ``max_length``. This is the
maximum length (in characters) of the field. The ``max_length`` is enforced
at the database level and in Django's validation.

CommaSeparatedIntegerField
--------------------------

A field of integers separated by commas. As in ``CharField``, the
``max_length`` argument is required.

DateField
---------

A date, represented in Python by a ``datetime.date`` instance.

DateTimeField
-------------

A date and time, represented in Python by a ``datetime.datetime`` instance.

DecimalField
------------

A fixed-precision decimal number, represented in Python by a
``decimal.Decimal`` instance. Has two **required** arguments:

``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)

When assigning to a ``DecimalField``, use either a ``decimal.Decimal`` object
or a string -- not a Python float.

EmailField
----------

A ``CharField`` that checks that the value is a valid e-mail address.

FileField
---------

A file-upload field.

.. note::
    The ``primary_key`` and ``unique`` arguments are not supported, and will
    raise a ``TypeError`` if used.

Has one **required** argument:

``upload_to``
    A local filesystem path that will be appended to your ``MEDIA_ROOT``
    setting to determine the value of the ``django.core.files.File.url``
    attribute.

    This path may contain "strftime formatting" (see the Python docs for the
    ``time`` standard library module), which will be replaced using the
    date/time of the file upload (so that uploaded files don't fill up the given
    directory).

    This may also be a callable, such as a function, which will be called to
    obtain the upload path, including the filename. This callable must be able
    to accept two arguments, and return a Unix-style path (with forward slashes)
    to be passed along to the storage system. The two arguments that will be
    passed are:

    ======================  ===============================================
    Argument                Description
    ======================  ===============================================
    ``instance``            An instance of the model where the
                            ``FileField`` is defined. More specifically,
                            this is the particular instance where the
                            current file is being attached.

                            In most cases, this object will not have been
                            saved to the database yet, so if it uses the
                            default ``AutoField``, *it might not yet have a
                            value for its primary key field*.

    ``filename``            The filename that was originally given to the
                            file. This may or may not be taken into account
                            when determining the final destination path.
    ======================  ===============================================

Also has one optional argument:

``storage``
    Optional. A storage object, which handles the storage and retrieval of your
    files.

Using a ``FileField`` or an ``ImageField`` (see below) in a model
takes a few steps:

1. In your settings file, you'll need to define ``MEDIA_ROOT`` as the
   full path to a directory where you'd like Django to store uploaded files.
   (For performance, these files are not stored in the database.) Define
   ``MEDIA_URL`` as the base public URL of that directory. Make sure
   that this directory is writable by the Web server's user account.

2. Add the ``FileField`` or ``ImageField`` to your model, making
   sure to define the ``upload_to`` option to tell Django
   to which subdirectory of ``MEDIA_ROOT`` it should upload files.

3. All that will be stored in your database is a path to the file
   (relative to ``MEDIA_ROOT``). You'll most likely want to use the
   convenience ``url`` function provided by
   Django. For example, if your ``ImageField`` is called ``mug_shot``,
   you can get the absolute URL to your image in a template with
   ``{{ object.mug_shot.url }}``.

For example, say your ``MEDIA_ROOT`` is set to ``'/home/media'``, and
``upload_to`` is set to ``'photos/%Y/%m/%d'``. The ``'%Y/%m/%d'``
part of ``upload_to`` is strftime formatting; ``'%Y'`` is the
four-digit year, ``'%m'`` is the two-digit month and ``'%d'`` is the two-digit
day. If you 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
``name``, ``url`` and ``size`` attributes.

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
what you think they are. For example, if you blindly let somebody upload files,
without validation, to a directory that's within your Web server's document
root, then somebody could upload a CGI or PHP script and execute that script by
visiting its URL on your site. Don't allow that.

By default, ``FileField`` instances are
created as ``varchar(100)`` columns in your database. As with other fields, you
can change the maximum length using the ``max_length`` argument.

FilePathField
-------------

A ``CharField`` whose choices are limited to the filenames in a certain
directory on the filesystem. Has three special arguments, of which the first is
**required**:

``path``
    Required. The absolute filesystem path to a directory from which this
    ``FilePathField`` should get its choices. Example: ``"/home/images"``.

``match``
    Optional. A regular expression, as a string, that ``FilePathField``
    will use to filter filenames. Note that the regex will be applied to the
    base filename, not the full path. Example: ``"foo.*\.txt$"``, which will
    match a file called ``foo23.txt`` but not ``bar.txt`` or ``foo23.gif``.

``recursive``
    Optional. Either ``True`` or ``False``. Default is ``False``. Specifies
    whether all subdirectories of ``path`` should be included.

Of course, these arguments can be used together.

The one potential gotcha is that ``match`` applies to the
base filename, not the full path. So, this example::

    FilePathField(path="/home/images", match="foo.*", recursive=True)

...will match ``/home/images/bar/foo.gif`` but not ``/home/images/foo/bar.gif``
because the ``match`` applies to the base filename
(``foo.gif`` and ``bar.gif``).

By default, ``FilePathField`` instances are
created as ``varchar(100)`` columns in your database. As with other fields, you
can change the maximum length using the ``max_length`` argument.

FloatField
----------

A floating-point number represented in Python by a ``float`` instance.

ImageField
----------

Like ``FileField``, but validates that the uploaded object is a valid
image. Has two extra optional arguments:

``height_field``
    Name of a model field which will be auto-populated with the height of the
    image each time the model instance is saved.

``width_field``
    Name of a model field which will be auto-populated with the width of the
    image each time the model instance is saved.

In addition to the special attributes that are available for FileField``,
an ``ImageField`` also has ``height`` and ``width`` attributes, both of which
correspond to the image's height and width in pixels.

Requires the Python Imaging Library, available at http://www.pythonware.com/products/pil/.

By default, ``ImageField`` instances are
created as ``varchar(100)`` columns in your database. As with other fields, you
can change the maximum length using the ``max_length`` argument.

IntegerField
------------

An integer.

IPAddressField
--------------

An IP address, in string format (e.g. ``'192.0.2.30'``).

NullBooleanField
----------------

Like a ``BooleanField``, but allows ``NULL`` as one of the options. Use
this instead of a ``BooleanField`` with ``null=True``.

PositiveIntegerField
--------------------

Like an ``IntegerField``, but must be positive.

PositiveSmallIntegerField
-------------------------

Like a ``PositiveIntegerField``, but only allows values under a certain
(database-dependent) point.

SlugField
---------

"Slug" is a newspaper term. A slug is a short label for something,
containing only letters, numbers, underscores or hyphens. They're generally used
in URLs.

Like a ``CharField``, you can specify ``max_length``. If ``max_length`` is not
specified, Django will use a default length of 50.

Implies setting ``db_index`` to ``True``.

SmallIntegerField
-----------------

Like an ``IntegerField``, but only allows values under a certain
(database-dependent) point.

TextField
---------

A large text field.

Also see ``CharField`` for storing smaller bits of text.

TimeField
---------

A time, represented in Python by a ``datetime.time`` instance. Accepts the same
auto-population options as ``DateField``.

URLField
--------

A ``CharField`` for a URL. Has one extra optional argument:

``verify_exists``
    If ``True`` (the default), the URL given will be checked for existence
    (i.e., the URL actually loads and doesn't give a 404 response). It should
    be noted that when using the single-threaded development server, validating
    a url being served by the same server will hang.
    This should not be a problem for multithreaded servers.

Like all ``CharField`` subclasses, ``URLField`` takes the optional
``max_length`` argument. If you don't specify
``max_length``, a default of 200 is used.

XMLField
--------

A ``TextField`` that checks that the value is valid XML that matches a
given schema. Takes one required argument:

``schema_path``
    The filesystem path to a RelaxNG schema against which to validate the
    field. For more on RelaxNG, see http://www.relaxng.org/.

Universal Field Options
=======================

The following arguments are available to all field types. All are optional.

null
----

If ``True``, Django will store empty values as ``NULL`` in the database. If
``False``, saving empty values will likely result in a database error. Default
is ``False``.

Note that empty string values will always get stored as empty strings, not 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``).

Avoid using ``null`` on string-based fields such as
``CharField`` and ``TextField`` unless you have an excellent reason.
If a string-based field has ``null=True``, that means it has two possible values
for "no data": ``NULL``, and the empty string. In most cases, it's redundant to
have two possible values for "no data;" Django's convention is to use the empty
string, not ``NULL``.

.. note::

    When using the Oracle database backend, the ``null=True`` option will be
    coerced for string-based fields that have the empty string as a possible
    value, and the value ``NULL`` will be stored to denote the empty string.

For more on this, see the section "Making Date and Numeric Fields Optional" in
Chapter 6.

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 ``blank=True``, validation on Django's admin site will allow entry
of an empty value. If a field has ``blank=False``, the field will be required.

choices
-------

An iterable (e.g., a list or tuple) of 2-tuples to use as choices for this
field.

A choices list looks like this::

    YEAR_IN_SCHOOL_CHOICES = (
        ('FR', 'Freshman'),
        ('SO', 'Sophomore'),
        ('JR', 'Junior'),
        ('SR', 'Senior'),
        ('GR', 'Graduate'),
    )

The first element in each tuple is the actual value to be stored. The second
element is the human-readable name for the option.

The choices list can be defined either as part of your model class::

    class Foo(models.Model):
        GENDER_CHOICES = (
            ('M', 'Male'),
            ('F', 'Female'),
        )
        gender = models.CharField(max_length=1, choices=GENDER_CHOICES)

or outside your model class altogether::

    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    class Foo(models.Model):
        gender = models.CharField(max_length=1, choices=GENDER_CHOICES)

You can also collect your available choices into named groups that can
be used for organizational purposes in a form::

    MEDIA_CHOICES = (
        ('Audio', (
                ('vinyl', 'Vinyl'),
                ('cd', 'CD'),
            )
        ),
        ('Video', (
                ('vhs', 'VHS Tape'),
                ('dvd', 'DVD'),
            )
        ),
        ('unknown', 'Unknown'),
    )

The first element in each tuple is the name to apply to the group. The
second element is an iterable of 2-tuples, with each 2-tuple containing
a value and a human-readable name for an option. Grouped options may be
combined with ungrouped options within a single list (such as the
`unknown` option in this example).

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 a
proper database table with a `ForeignKey``. ``choices`` is
meant for static data that doesn't change much, if ever.

db_column
---------

The name of the database column to use for this field. If this isn't given,
Django will use the field's name.

If your database column name is an SQL reserved word, or contains
characters that aren't allowed in Python variable names -- notably, the
hyphen -- that's OK. Django quotes column and table names behind the
scenes.

db_index
--------

If ``True``, ``django-admin.py sqlindexes`` will output a
``CREATE INDEX`` statement for this field.

db_tablespace
-------------

The name of the database tablespace to use for this field's index, if this field
is indexed. The default is the project's ``DEFAULT_INDEX_TABLESPACE``
setting, if set, or the ``db_tablespace`` of the model, if any. If
the backend doesn't support tablespaces, this option is ignored.

default
-------

The default value for the field. This can be a value or a callable object. If
callable it will be called every time a new object is created.

editable
--------

If ``False``, the field will not be editable in the admin or via forms
automatically generated from the model class. Default is ``True``.

help_text
---------

Extra "help" text to be displayed under the field on the object's admin form.
It's useful for documentation even if your object doesn't have an admin form.

Note that this value is *not* HTML-escaped when it's displayed in the admin
interface. This lets you include HTML in ``help_text`` if you so
desire. For example::

    help_text="Please use the following format: <em>YYYY-MM-DD</em>."

Alternatively you can use plain text and
``django.utils.html.escape()`` to escape any HTML special characters.

primary_key
-----------

If ``True``, this field is the primary key for the model.

If you don't specify ``primary_key=True`` for any fields in your model, Django
will automatically add an ``AutoField`` to hold the primary key, so you
don't need to set ``primary_key=True`` on any of your fields unless you want to
override the default primary-key behavior.

``primary_key=True`` implies ``null=False`` and ``unique=True``.
Only one primary key is allowed on an object.

unique
------

If ``True``, this field must be unique throughout the table.

This is enforced at the database level and at the level of forms created with
``ModelForm`` (including forms in the Django admin site). If
you try to save a model with a duplicate value in a ``unique``
field, an ``IntegrityError`` will be raised by the model's
``save`` method.

This option is valid on all field types except ``ManyToManyField``,
``FileField`` and ``ImageField``.

unique_for_date
---------------

Set this to the name of a ``DateField`` or ``DateTimeField`` to
require that this field be unique for the value of the date field.

For example, if you have a field ``title`` that has
``unique_for_date="pub_date"``, then Django wouldn't allow the entry of two
records with the same ``title`` and ``pub_date``.

This is enforced at the level of forms created with ``ModelForm`` (including
forms in the Django admin site) but not at the database level.

unique_for_month
----------------

Like ``unique_for_date``, but requires the field to be unique with
respect to the month.

unique_for_year
---------------

Like ``unique_for_date`` and ``unique_for_month``.

verbose_name
------------

A human-readable name for the field. If the verbose name isn't given, Django
will automatically create it using the field's attribute name, converting
underscores to spaces.

Relationships
=============

Clearly, the power of relational databases lies in relating tables to each
other. Django offers ways to define the three most common types of database
relationships: many-to-one, many-to-many, and one-to-one.

ForeignKey
----------

A many-to-one relationship. Requires a positional argument: the class to which
the model is related.

To create a recursive relationship -- an object that has a many-to-one
relationship with itself -- use ``models.ForeignKey('self')``.

If you need to create a relationship on a model that has not yet been defined,
you can use the name of the model, rather than the model object itself::

    class Car(models.Model):
        manufacturer = models.ForeignKey('Manufacturer')
        # ...

    class Manufacturer(models.Model):
        # ...

Note, however, that this only refers to models in the same ``models.py`` file.

To refer to models defined in another
application, you must instead explicitly specify the application label. For
example, if the ``Manufacturer`` model above is defined in another application
called ``production``, you'd need to use::

    class Car(models.Model):
        manufacturer = models.ForeignKey('production.Manufacturer')

Behind the scenes, Django appends ``"_id"`` to the field name to create its
database column name. In the above example, the database table for the ``Car``
model will have a ``manufacturer_id`` column. (You can change this explicitly by
specifying ``db_column``) However, your code should never have to
deal with the database column name, unless you write custom SQL. You'll always
deal with the field names of your model object.

``ForeignKey`` accepts an extra set of arguments -- all optional -- that
define the details of how the relation works.

``limit_choices_to``
    A dictionary of lookup arguments and values
    that limit the available admin choices for this object. Use this with
    functions from the Python ``datetime`` module to limit choices of objects by
    date. For example::

        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 chosen.

    ``limit_choices_to`` has no effect on the inline FormSets that are created
    to display related objects in the admin.

``related_name``
    The name to use for the relation from the related object back to this one.

``to_field``
    The field on the related object that the relation is to. By default, Django
    uses the primary key of the related object.

ManyToManyField
---------------

A many-to-many relationship. Requires a positional argument: the class to which
the model is related. This works exactly the same as it does for
``ForeignKey``, including all the options regarding recursive relationships
and lazy relationships.

Behind the scenes, Django creates an intermediary join table to represent the
many-to-many relationship. By default, this table name is generated using the
names of the two tables being joined. Since some databases don't support table
names above a certain length, these table names will be automatically
truncated to 64 characters and a uniqueness hash will be used. This means you
might see table names like ``author_books_9cdf4``; this is perfectly normal.
You can manually provide the name of the join table using the
``db_table`` option.

``ManyToManyField`` accepts an extra set of arguments -- all optional --
that control how the relationship functions.

``related_name``
    Same as ``related_name`` in ``ForeignKey``.

``limit_choices_to``
    Same as ``limit_choices_to`` in ``ForeignKey``.

    ``limit_choices_to`` has no effect when used on a ``ManyToManyField`` with a
    custom intermediate table specified using the
    ``through`` paramter.

``symmetrical``
    Only used in the definition of ManyToManyFields on self. Consider the
    following model::

        class Person(models.Model):
            friends = models.ManyToManyField("self")

    When Django processes this model, it identifies that it has a
    ``ManyToManyField`` on itself, and as a result, it doesn't add a
    ``person_set`` attribute to the ``Person`` class. Instead, the
    ``ManyToManyField`` is assumed to be symmetrical -- that is, if I am
    your friend, then you are my friend.

    If you do not want symmetry in many-to-many relationships with ``self``, set
    ``symmetrical`` to ``False``. This will force Django to
    add the descriptor for the reverse relationship, allowing
    ``ManyToManyField`` relationships to be non-symmetrical.

``through``
    Django will automatically generate a table to manage many-to-many
    relationships. However, if you want to manually specify the intermediary
    table, you can use the ``through`` option to specify
    the Django model that represents the intermediate table that you want to
    use.

    The most common use for this option is when you want to associate
    extra data with a many-to-many relationship.

``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.

OneToOneField
-------------

A one-to-one relationship. Conceptually, this is similar to a
``ForeignKey`` with ``unique=True``, but the
"reverse" side of the relation will directly return a single object.

This is most useful as the primary key of a model which "extends"
another model in some way; multi-table-inheritance is
implemented by adding an implicit one-to-one relation from the child
model to the parent model, for example.

One positional argument is required: the class to which the model will be
related. This works exactly the same as it does for ``ForeignKey``,
including all the options regarding recursive relationships and lazy
relationships.

Additionally, ``OneToOneField`` accepts all of the extra arguments
accepted by ``ForeignKey``, plus one extra argument:

``parent_link``
    When ``True`` and used in a model which inherits from another
    (concrete) model, indicates that this field should be used as the
    link back to the parent class, rather than the extra
    ``OneToOneField`` which would normally be implicitly created by
    subclassing.

Model Metadata Options
======================

Model-specific metadata lives in a ``class Meta`` defined in the body of your
model class::

    class Book(models.Model):
        title = models.CharField(maxlength=100)

        class Meta:
            # model metadata options go here
            ...

Model metadata is "anything that's not a field," such as ordering options and so forth.

The sections that follow present a list of all possible ``Meta`` options.
No options are required. Adding ``class Meta`` to a model is completely optional.

abstract
--------

If ``True``, this model will be an abstract base class. See the Django
documentation for more on abstract base classes.

db_table
--------

The name of the database table to use for the model::

    db_table = 'music_album'

Table names
~~~~~~~~~~~

To save you time, Django automatically derives the name of the database table
from the name of your model class and the app that contains it. A model's
database table name is constructed by joining the model's "app label" -- the
name you used in ``manage.py startapp`` -- to the model's class name, with an
underscore between them.

For example, if you have an app ``bookstore`` (as created by
``manage.py startapp bookstore``), a model defined as ``class Book`` will have
a database table named ``bookstore_book``.

To override the database table name, use the ``db_table`` parameter in
``class Meta``.

If your database table name is an SQL reserved word, or contains characters that
aren't allowed in Python variable names -- notably, the hyphen -- that's OK.
Django quotes column and table names behind the scenes.

db_tablespace
-------------

The name of the database tablespace to use for the model. If the backend doesn't
support tablespaces, this option is ignored.

get_latest_by
-------------

The name of a ``DateField`` or ``DateTimeField`` in the model. This
specifies the default field to use in your model ``Manager``'s
``latest`` method.

Example::

    get_latest_by = "order_date"

managed
-------

Defaults to ``True``, meaning Django will create the appropriate database
tables in ``django-admin.py syncdb`` and remove them as part of a ``reset``
management command. That is, Django *manages* the database tables' lifecycles.

If ``False``, no database table creation or deletion operations will be
performed for this model. This is useful if the model represents an existing
table or a database view that has been created by some other means. This is
the *only* difference when ``managed`` is ``False``. All other aspects of
model handling are exactly the same as normal. This includes

1. Adding an automatic primary key field to the model if you don't declare
   it. To avoid confusion for later code readers, it's recommended to
   specify all the columns from the database table you are modeling when
   using unmanaged models.

2. If a model with ``managed=False`` contains a
   ``ManyToManyField`` that points to another
   unmanaged model, then the intermediary table for the many-to-many join
   will also not be created. However, the intermediary table between one
   managed and one unmanaged model *will* be created.

   If you need to change this default behavior, create the intermediary
   table as an explicit model (with ``managed`` set as needed) and use the
   ``through`` attribute to make the relation use your
   custom model.

For tests involving models with ``managed=False``, it's up to you to ensure
the correct tables are created as part of the test setup.

If you're interested in changing the Python-level behavior of a model class,
you *could* use ``managed=False`` and create a copy of an existing model.
However, there's a better approach for that situation: proxy-models.

ordering
--------

The default ordering for the object, for use when obtaining lists of objects::

    ordering = ['-order_date']

This is a tuple or list of strings. Each string is a field name with an optional
"-" prefix, which indicates descending order. Fields without a leading "-" will
be ordered ascending. Use the string "?" to order randomly.

.. note::

    Regardless of how many fields are in ``ordering``, the admin
    site uses only the first field.

For example, to order by a ``pub_date`` field ascending, use this::

    ordering = ['pub_date']

To order by ``pub_date`` descending, use this::

    ordering = ['-pub_date']

To order by ``pub_date`` descending, then by ``author`` ascending, use this::

    ordering = ['-pub_date', 'author']

proxy
-----

If set to ``True``, a model which subclasses another model will be treated as
a proxy model. For more on proxy models, see the Django documentation.

unique_together
---------------

Sets of field names that, taken together, must be unique::

    unique_together = (("driver", "restaurant"),)

This is a list of lists of fields that must be unique when considered together.
It's used by ``ModelForm`` forms (including forms in the Django admin site) and
is enforced at the database level (i.e., the appropriate ``UNIQUE`` statements
are included in the ``CREATE TABLE`` statement).

For convenience, unique_together can be a single sequence when dealing with a single
set of fields::

    unique_together = ("driver", "restaurant")

verbose_name
------------

A human-readable name for the object, singular::

    verbose_name = "pizza"

If this isn't given, Django will use a munged version of the class name:
``CamelCase`` becomes ``camel case``.

verbose_name_plural
-------------------

The plural name for the object::

    verbose_name_plural = "stories"

If this isn't given, Django will use ``verbose_name`` + ``"s"``.


================================================
FILE: Python/DjangoBook/appendixB.rst
================================================
==================================
Appendix B: Database API Reference
==================================

Django's database API is the other half of the model API discussed in Appendix
A. Once you've defined a model, you'll use this API any time you need to
access the database. You've seen examples of this API in use throughout the
book; this appendix explains all the various options in detail.

Like the model APIs discussed in Appendix A, though these APIs are considered
very stable, the Django developers consistently add new shortcuts and
conveniences. It's a good idea to always check the latest documentation online,
available at http://docs.djangoproject.com/.

Throughout this reference, we'll refer to the following models, which might form
a simple blog application::

    from django.db import models

    class Blog(models.Model):
        name = models.CharField(max_length=100)
        tagline = models.TextField()

        def __unicode__(self):
            return self.name

    class Author(models.Model):
        name = models.CharField(max_length=50)
        email = models.EmailField()

        def __unicode__(self):
            return self.name

    class Entry(models.Model):
        blog = models.ForeignKey(Blog)
        headline = models.CharField(max_length=255)
        body_text = models.TextField()
        pub_date = models.DateTimeField()
        authors = models.ManyToManyField(Author)

        def __unicode__(self):
            return self.headline

Creating Objects
================

To create an object, instantiate it using keyword arguments to the model class, and
then call ``save()`` to save it to the database::

    >>> from mysite.blog.models import Blog
    >>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
    >>> b.save()

This performs an ``INSERT`` SQL statement behind the scenes. Django doesn't hit
the database until you explicitly call ``save()``.

The ``save()`` method has no return value.

To create an object and save it all in one step, see the ``create`` manager
method.

What Happens When You Save?
---------------------------

When you save an object, Django performs the following steps:

#. **Emit a pre_save signal.** This provides a notification that
   an object is about to be saved. You can register a listener that
   will be invoked whenever this signal is emitted. Check the online
   documentation for more on signals.

#. **Preprocess the data.** Each field on the object is asked to
   perform any automated data modification that the field may need
   to perform.

   Most fields do *no* preprocessing -- the field data is kept as is.
   Preprocessing is only used on fields that have special behavior,
   like file fields.

#. **Prepare the data for the database.** Each field is asked to provide
   its current value in a data type that can be written to the database.

   Most fields require no data preparation. Simple data types, such as
   integers and strings, are "ready to write" as a Python object. However,
   more complex data types often require some modification. For example,
   ``DateFields`` use a Python ``datetime`` object to store data.
   Databases don't store ``datetime`` objects, so the field value
   must be converted into an ISO-compliant date string for insertion
   into the database.

#. **Insert the data into the database.** The preprocessed, prepared
   data is then composed into an SQL statement for insertion into the
   database.

#. **Emit a post_save signal.** As with the ``pre_save`` signal, this
   is used to provide notification that an object has been successfully
   saved.

Autoincrementing Primary Keys
------------------------------

For convenience, each model is given an autoincrementing primary key field
named ``id`` unless you explicitly specify ``primary_key=True`` on a field (see
the section titled "AutoField" in Appendix A).

If your model has an ``AutoField``, that autoincremented value will be
calculated and saved as an attribute on your object the first time you call
``save()``::

    >>> b2 = Blog(name='Cheddar Talk', tagline='Thoughts on cheese.')
    >>> b2.id     # Returns None, because b doesn't have an ID yet.
    None

    >>> b2.save()
    >>> b2.id     # Returns the ID of your new object.
    14

There's no way to tell what the value of an ID will be before you call
``save()``, because that value is calculated by your database, not by Django.

If a model has an ``AutoField`` but you want to define a new object's ID
explicitly when saving, just define it explicitly before saving, rather than
relying on the autoassignment of the ID::

    >>> b3 = Blog(id=3, name='Cheddar Talk', tagline='Thoughts on cheese.')
    >>> b3.id
    3
    >>> b3.save()
    >>> b3.id
    3

If you assign auto-primary-key values manually, make sure not to use an
already existing primary key value! If you create a new object with an explicit
primary key value that already exists in the database, Django will assume you're
changing the existing record rather than creating a new one.

Given the preceding ``'Cheddar Talk'`` blog example, this example would override 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!

Explicitly specifying auto-primary-key values is mostly useful for bulk-saving
objects, when you're confident you won't have primary key collision.

Saving Changes to Objects
=========================

To save changes to an object that's already in the database, use ``save()``.

Given a ``Blog`` instance ``b5`` that has already been saved to the database,
this example changes its name and updates its record in the database::

    >>> b5.name = 'New name'
    >>> b5.save()

This performs an ``UPDATE`` SQL statement behind the scenes. Again, Django
doesn't hit the database until you explicitly call ``save()``.

.. admonition:: How Django Knows When to ``UPDATE`` and When to ``INSERT``

    You may have noticed that Django database objects use the same ``save()`` method
    for creating and changing objects. Django abstracts the need to use
    ``INSERT`` 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 primary key already exists.

    * If the record with the given primary key does already exist, Django
      executes an ``UPDATE`` query.

    * If the object's primary key attribute is *not* set, or if it's set but
      a record doesn't exist, Django executes an ``INSERT``.

    Because of this, you should be careful not to specify a primary key value
    explicitly when saving new objects if you cannot guarantee the primary key
    value is unused.

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.

Retrieving Objects
==================

Throughout the book you've seen objects retrieved using code like the following::

    >>> blogs = Blog.objects.filter(author__name__contains="Joe")

There are quite a few "moving parts" behind the scenes here: when you
retrieve objects from the database, you're actually constructing a ``QuerySet``
using the model's ``Manager``. This ``QuerySet`` knows how to execute SQL and
return the requested objects.

Appendix A looked at both of these objects from a model-definition point of
view; now we'll look at how they operate.

A ``QuerySet`` represents a collection of objects from your database. It can
have zero, one, or many *filters* -- criteria that narrow down the collection
based on given parameters. In SQL terms, a ``QuerySet`` equates to a ``SELECT``
statement, and a filter is a ``WHERE``.

You get a ``QuerySet`` by using your model's ``Manager``. Each model has at
least one ``Manager``, and it's called ``objects`` by default. Access it
directly via the model class, like so::

    >>> Blog.objects
    <django.db.models.manager.Manager object at 0x137d00d>

``Manager``\s are accessible only via model classes, rather than from model
instances, to enforce a separation between "table-level" operations and
"record-level" operations::

    >>> b = Blog(name='Foo', tagline='Bar')
    >>> b.objects
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: Manager isn't accessible via Blog instances.

The ``Manager`` is the main source of ``QuerySet``\s for a model. It acts as a
"root" ``QuerySet`` that describes all objects in the model's database table.
For example, ``Blog.objects`` is the initial ``QuerySet`` that contains all
``Blog`` objects in the database.

Caching and QuerySets
=====================

Each ``QuerySet`` contains a cache, to minimize database access. It's important
to understand how it works, in order to write the most efficient code.

In a newly created ``QuerySet``, the cache is empty. The first time a
``QuerySet`` is evaluated -- and, hence, a database query happens -- Django
saves the query results in the ``QuerySet``'s cache and returns the results
that have been explicitly requested (e.g., the next element, if the
``QuerySet`` is being iterated over). Subsequent evaluations of the
``QuerySet`` reuse the cached results.

Keep this caching behavior in mind, because it may bite you if you don't use
your ``QuerySet``\s correctly. For example, the following will create two
``QuerySet``\s, evaluate them, and throw them away::

    print [e.headline for e in Entry.objects.all()]
    print [e.pub_date for e in Entry.objects.all()]

That means the same database query will be executed twice, effectively doubling
your database load. Also, there's a possibility the two lists may not include
the same database records, because an ``Entry`` may have been added or deleted
in the split second between the two requests.

To avoid this problem, simply save the ``QuerySet`` and reuse it::

    queryset = Poll.objects.all()
    print [p.headline for p in queryset] # Evaluate the query set.
    print [p.pub_date for p in queryset] # Reuse the cache from the evaluation.

Filtering Objects
=================

The simplest way to retrieve objects from a table is to get all of them.
To do this, use the ``all()`` method on a ``Manager``::

    >>> Entry.objects.all()

The ``all()`` method returns a ``QuerySet`` of all the objects in the database.

Usually, though, you'll need to select only a subset of the complete set of
objects. To create such a subset, you refine the initial ``QuerySet``, adding filter
conditions. You'll usually do this using the ``filter()`` and/or ``exclude()``
methods::

    >>> y2006 = Entry.objects.filter(pub_date__year=2006)
    >>> not2006 = Entry.objects.exclude(pub_date__year=2006)

``filter()`` and ``exclude()`` both take *field lookup* arguments, which are
discussed in detail shortly.

Chaining Filters
----------------

The result of refining a ``QuerySet`` is itself a ``QuerySet``, so it's
possible to chain refinements together, for example::

    >>> qs = Entry.objects.filter(headline__startswith='What')
    >>> qs = qs.exclude(pub_date__gte=datetime.datetime.now())
    >>> qs = qs.filter(pub_date__gte=datetime.datetime(2005, 1, 1))

This takes the initial ``QuerySet`` of all entries in the database, adds a
filter, then an exclusion, and then another filter. The final result is a
``QuerySet`` containing all entries with a headline that starts with "What"
that were published between January 1, 2005, and the current day.

It's important to point out here that ``QuerySets`` are lazy -- the act of creating
a ``QuerySet`` doesn't involve any database activity. In fact, the three preceding lines
don't make *any* database calls; you can chain filters together all day
long and Django won't actually run the query until the ``QuerySet`` is
*evaluated*.

You can evaluate a ``QuerySet`` in any following ways:

* *Iterating*: A ``QuerySet`` is iterable, and it executes its database query the first
  time you iterate over it. For example, the following ``QuerySet`` isn't evaluated
  until it's iterated over in the ``for`` loop::

      qs = Entry.objects.filter(pub_date__year=2006)
      qs = qs.filter(headline__icontains="bill")
      for e in qs:
          print e.headline

  This prints all headlines from 2006 that contain "bill" but causes
  only one database hit.

* *Printing it*: A ``QuerySet`` is evaluated when you call ``repr()`` on it.
  This is for convenience in the Python interactive interpreter, so you can
  immediately see your results when using the API interactively.

* *Slicing*: As explained in the upcoming "Limiting QuerySets" section,
  a ``QuerySet`` can be sliced using Python's array-slicing syntax.
  Usually slicing a ``QuerySet`` returns another (unevaluated)``QuerySet``,
  but Django will execute the database query if you use the "step"
  parameter of slice syntax.

* *Converting to a list*: You can force evaluation of a ``QuerySet`` by calling
  ``list()`` on it, for example::

      >>> entry_list = list(Entry.objects.all())

  Be warned, though, that this could have a large memory overhead, because
  Django will load each element of the list into memory. In contrast,
  iterating over a ``QuerySet`` will take advantage of your database to load
  data and instantiate objects only as you need them.

.. admonition:: Filtered QuerySets Are Unique

    Each time you refine a ``QuerySet``, you get a brand-new ``QuerySet`` that
    is in no way bound to the previous ``QuerySet``. Each refinement creates a
    separate and distinct ``QuerySet`` that can be stored, used, and reused::

        q1 = Entry.objects.filter(headline__startswith="What")
        q2 = q1.exclude(pub_date__gte=datetime.now())
        q3 = q1.filter(pub_date__gte=datetime.now())

    These three ``QuerySets`` are separate. The first is a base ``QuerySet``
    containing all entries that contain a headline starting with "What". The
    second is a subset of the first, with an additional criterion that excludes
    records whose ``pub_date`` is greater than now. The third is a subset of the
    first, with an additional criterion that selects only the records whose
    ``pub_date`` is greater than now. The initial ``QuerySet`` (``q1``) is
    unaffected by the refinement process.

Limiting QuerySets
------------------

Use Python's array-slicing syntax to limit your ``QuerySet`` to a certain number
of results. This is the equivalent of SQL's ``LIMIT`` and ``OFFSET`` clauses.

For example, this returns the first five entries (``LIMIT 5``)::

    >>> Entry.objects.all()[:5]

This returns the sixth through tenth entries (``OFFSET 5 LIMIT 5``)::

    >>> Entry.objects.all()[5:10]

Generally, slicing a ``QuerySet`` returns a new ``QuerySet`` -- it doesn't
evaluate the query. An exception is if you use the "step" parameter
of Python slice syntax. For example, this would actually execute the query in
order to return a list of every *second* object of the first ten::

    >>> Entry.objects.all()[:10:2]

To retrieve a *single* object rather than a list (e.g., ``SELECT foo FROM bar
LIMIT 1``), use a simple index instead of a slice. For example, this returns the
first ``Entry`` in the database, after ordering entries alphabetically by
headline::

    >>> Entry.objects.order_by('headline')[0]

This is roughly equivalent to the following::

    >>> Entry.objects.order_by('headline')[0:1].get()

Note, however, that the first of these will raise ``IndexError`` while the
second will raise ``DoesNotExist`` if no objects match the given criteria.

Query Methods That Return New QuerySets
---------------------------------------

Django provides a range of ``QuerySet`` refinement methods that modify either
the types of results returned by the ``QuerySet`` or the way its SQL query is
executed. These methods are described in the sections that follow. Some of the
methods take field lookup arguments, which are discussed in detail a bit later
on.

filter(\*\*lookup)
~~~~~~~~~~~~~~~~~~

Returns a new ``QuerySet`` containing objects that match the given lookup
parameters.

exclude(\*\*lookup)
~~~~~~~~~~~~~~~~~~~

Returns a new ``QuerySet`` containing objects that do *not* match the given
lookup parameters.

order_by(\*fields)
~~~~~~~~~~~~~~~~~~

By default, results returned by a ``QuerySet`` are ordered by the ordering
tuple given by the ``ordering`` option in the model's metadata (see Appendix A). You can
override this for a particular query using the ``order_by()`` method::

    >> Entry.objects.filter(pub_date__year=2005).order_by('-pub_date', 'headline')

This result will be ordered by ``pub_date`` descending, then by
``headline`` ascending. The negative sign in front of ``"-pub_date"`` indicates
*descending* order. Ascending order is assumed if the ``-`` is absent. To order
randomly, use ``"?"``, like so::

    >>> Entry.objects.order_by('?')

Ordering randomly incurs a performance penalty, though, so you shouldn't use it
for anything with heavy load.

If no ordering is specified in a model's ``class Meta`` and a ``QuerySet`` from
that model doesn't include ``order_by()``, then ordering will be undefined and
may differ from query to query.

distinct()
~~~~~~~~~~

Returns a new ``QuerySet`` that uses ``SELECT DISTINCT`` in its SQL query. This
eliminates duplicate rows from the query results.

By default, a ``QuerySet`` will not eliminate duplicate rows. In practice, this
is rarely a problem, because simple queries such as ``Blog.objects.all()`` don't
introduce the possibility of duplicate result rows.

However, if your query spans multiple tables, it's possible to get duplicate
results when a ``QuerySet`` is evaluated. That's when you'd use ``distinct()``.

values(\*fields)
~~~~~~~~~~~~~~~~

Returns a special ``QuerySet`` that evaluates to a list of dictionaries instead
of model-instance objects. Each of those dictionaries represents an object, with
the keys corresponding to the attribute names of model objects::

    # This list contains a Blog object.
    >>> Blog.objects.filter(name__startswith='Beatles')
    [Beatles Blog]

    # This list contains a dictionary.
    >>> Blog.objects.filter(name__startswith='Beatles').values()
    [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}]

``values()`` takes optional positional arguments, ``*fields``, which specify
field names to which the ``SELECT`` should be limited. If you specify the
fields, each dictionary will contain only the field keys/values for the fields
you specify. If you don't specify the fields, each dictionary will contain a
key and value for every field in the database table::

    >>> Blog.objects.values()
    [{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}],
    >>> Blog.objects.values('id', 'name')
    [{'id': 1, 'name': 'Beatles Blog'}]

This method is useful when you know you're only going to need values from a
small number of the available fields and you won't need the functionality of a
model instance object. It's more efficient to select only the fields you need to
use.

dates(field, kind, order)
~~~~~~~~~~~~~~~~~~~~~~~~~

Returns a special ``QuerySet`` that evaluates to a list of ``datetime.datetime``
objects representing all available dates of a particular kind within the
contents of the ``QuerySet``.

The ``field`` argument must be the name of a ``DateField`` or ``DateTimeField``
of your model. The ``kind`` argument must be either ``"year"``, ``"month"``, or
``"day"``. Each ``datetime.datetime`` object in the result list is "truncated"
to the given ``type``:

* ``"year"`` returns a list of all distinct year values for the field.

* ``"month"`` returns a list of all distinct year/month values for the field.

* ``"day"`` returns a list of all distinct year/month/day values for the field.

``order``, which defaults to ``'ASC'``, should be either ``'ASC'`` or
``'DESC'``. This specifies how to order the results.

Here are a few examples::

    >>> Entry.objects.dates('pub_date', 'year')
    [datetime.datetime(2005, 1, 1)]

    >>> Entry.objects.dates('pub_date', 'month')
    [datetime.datetime(2005, 2, 1), datetime.datetime(2005, 3, 1)]

    >>> Entry.objects.dates('pub_date', 'day')
    [datetime.datetime(2005, 2, 20), datetime.datetime(2005, 3, 20)]

    >>> Entry.objects.dates('pub_date', 'day', order='DESC')
    [datetime.datetime(2005, 3, 20), datetime.datetime(2005, 2, 20)]

    >>> Entry.objects.filter(headline__contains='Lennon').dates('pub_date', 'day')
    [datetime.datetime(2005, 3, 20)]

select_related()
~~~~~~~~~~~~~~~~

Returns a ``QuerySet`` that will automatically "follow" foreign key
relationships, selecting that additional related-object data when it executes
its query. This is a performance booster that results in (sometimes much)
larger queries but means later use of foreign key relationships won't require
database queries.

The following examples illustrate the difference between plain lookups and
``select_related()`` lookups. Here's standard lookup::

    # Hits the database.
    >>> e = Entry.objects.get(id=5)

    # Hits the database again to get the related Blog object.
    >>> b = e.blog

And here's ``select_related`` lookup::

    # Hits the database.
    >>> e = Entry.objects.select_related().get(id=5)

    # Doesn't hit the database, because e.blog has been prepopulated
    # in the previous query.
    >>> b = e.blog

``select_related()`` follows foreign keys as far as possible. If you have the
following models::

    class City(models.Model):
        # ...

    class Person(models.Model):
        # ...
        hometown = models.ForeignKey(City)

    class Book(models.Model):
        # ...
        author = models.ForeignKey(Person)

then a call to ``Book.objects.select_related().get(id=4)`` will cache the
related ``Person`` *and* the related ``City``::

    >>> b = Book.objects.select_related().get(id=4)
    >>> p = b.author         # Doesn't hit the database.
    >>> c = p.hometown       # Doesn't hit the database.

    >>> 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
application 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.

QuerySet Methods That Do Not Return QuerySets
---------------------------------------------

The following ``QuerySet`` methods evaluate the ``QuerySet`` and return
something *other than* a ``QuerySet`` -- a single object, value, and so forth.

get(\*\*lookup)
~~~~~~~~~~~~~~~

Returns the object matching the given lookup parameters, which should be in the
format described in the "Field Lookups" section. This raises ``AssertionError`` if
more than one object was found.

``get()`` raises a ``DoesNotExist`` exception if an object wasn't found for the
given parameters. The ``DoesNotExist`` exception is an attribute of the model
class, for example::

    >>> Entry.objects.get(id='foo') # raises Entry.DoesNotExist

The ``DoesNotExist`` exception inherits from
``django.core.exceptions.ObjectDoesNotExist``, so you can target multiple
``DoesNotExist`` exceptions::

    >>> from django.core.exceptions import ObjectDoesNotExist
    >>> try:
    ...     e = Entry.objects.get(id=3)
    ...     b = Blog.objects.get(id=1)
    ... except ObjectDoesNotExist:
    ...     print "Either the entry or blog doesn't exist."

create(\*\*kwargs)
~~~~~~~~~~~~~~~~~~

This is a convenience method for creating an object and saving it all in one step.
It lets you compress two common steps::

    >>> p = Person(first_name="Bruce", last_name="Springsteen")
    >>> p.save()

into a single line::

    >>> p = Person.objects.create(first_name="Bruce", last_name="Springsteen")

get_or_create(\*\*kwargs)
~~~~~~~~~~~~~~~~~~~~~~~~~

This is a convenience method for looking up an object and creating one if it doesn't
exist. It returns a tuple of ``(object, created)``, where ``object`` is the retrieved or
created object and ``created`` is a Boolean specifying whether a new object was
created.

This method is meant as a shortcut to boilerplate code and is mostly useful for
data-import scripts. For example::

    try:
        obj = Person.objects.get(first_name='John', last_name='Lennon')
    except Person.DoesNotExist:
        obj = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9))
        obj.save()

This pattern gets quite unwieldy as the number of fields in a model increases. The
previous example can be rewritten using ``get_or_create()`` like so::

    obj, created = Person.objects.get_or_create(
        first_name = 'John',
        last_name  = 'Lennon',
        defaults   = {'birthday': date(1940, 10, 9)}
    )

Any keyword arguments passed to ``get_or_create()`` -- *except* an optional one
called ``defaults`` -- will be used in a ``get()`` call. If an object is found,
``get_or_create()`` returns a tuple of that object and ``False``. If an object
is *not* found, ``get_or_create()`` will instantiate and save a new object,
returning a tuple of the new object and ``True``. The new object will be created
according to this algorithm::

    defaults = kwargs.pop('defaults', {})
    params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
    params.update(defaults)
    obj = self.model(**params)
    obj.save()

In English, that means start with any non-``'defaults'`` keyword argument that
doesn't contain a double underscore (which would indicate a nonexact lookup).
Then add the contents of ``defaults``, overriding any keys if necessary, and
use the result as the keyword arguments to the model class.

If you have a field named ``defaults`` and want to use it as an exact lookup in
``get_or_create()``, just use ``'defaults__exact'`` like so::

    Foo.objects.get_or_create(
        defaults__exact = 'bar',
        defaults={'defaults': 'bar'}
    )

.. note::

    As mentioned earlier, ``get_or_create()`` is mostly useful in scripts that
    need to parse data and create new records if existing ones aren't available.
    But if you need to use ``get_or_create()`` in a view, please make sure to
    use it only in ``POST`` requests unless you have a good reason not to.
    ``GET`` requests shouldn't have any effect on data; use ``POST`` whenever a
    request to a page has a side effect on your data.

count()
~~~~~~~

Returns an integer representing the number of objects in the database matching
the ``QuerySet``. ``count()`` never raises exceptions. Here's an example::

    # Returns the total number of entries in the database.
    >>> Entry.objects.count()
    4

    # Returns the number of entries whose headline contains 'Lennon'
    >>> Entry.objects.filter(headline__contains='Lennon').count()
    1

``count()`` performs a ``SELECT COUNT(*)`` behind the scenes, so you should
always use ``count()`` rather than loading all of the records into Python objects
and calling ``len()`` on the result.

Depending on which database you're using (e.g., PostgreSQL or MySQL),
``count()`` may return a long integer instead of a normal Python integer. This
is an underlying implementation quirk that shouldn't pose any real-world
problems.

in_bulk(id_list)
~~~~~~~~~~~~~~~~

Takes a list of primary key values and returns a dictionary mapping each
primary key value to an instance of the object with the given ID, for example::

    >>> Blog.objects.in_bulk([1])
    {1: Beatles Blog}
    >>> Blog.objects.in_bulk([1, 2])
    {1: Beatles Blog, 2: Cheddar Talk}
    >>> Blog.objects.in_bulk([])
    {}

IDs of objects that don't exist are silently dropped from the result dictionary.
If you pass ``in_bulk()`` an empty list, you'll get an empty dictionary.

latest(field_name=None)
~~~~~~~~~~~~~~~~~~~~~~~

Returns the latest object in the table, by date, using the ``field_name``
provided as the date field. This example returns the latest ``Entry`` in the
table, according to the ``pub_date`` field::

    >>> Entry.objects.latest('pub_date')

If your model's ``Meta`` specifies ``get_latest_by``, you can leave off the
``field_name`` argument to ``latest()``. Django will use the field specified in
``get_latest_by`` by default.

Like ``get()``, ``latest()`` raises ``DoesNotExist`` if an object doesn't exist
with the given parameters.

Field Lookups
=============

Field lookups are how you specify the meat of an SQL ``WHERE`` clause. They're
specified as keyword arguments to the ``QuerySet`` methods ``filter()``,
``exclude()``, and ``get()``.

Basic lookup keyword arguments take the form ``field__lookuptype=value``
(note the double underscore). For example::

    >>> Entry.objects.filter(pub_date__lte='2006-01-01')

translates (roughly) into the following SQL::

    SELECT * FROM blog_entry WHERE pub_date <= '2006-01-01';

If you pass an invalid keyword argument, a lookup function will raise
``TypeError``.

The supported lookup types follow.

exact
-----

Performs an exact match::

    >>> Entry.objects.get(headline__exact="Man bites dog")

This matches any object with the exact headline "Man bites dog".

If you don't provide a lookup type -- that is, if your keyword argument doesn't
contain a double underscore -- the lookup type is assumed to be ``exact``.

For example, the following two statements are equivalent::

    >>> Blog.objects.get(id__exact=14) # Explicit form
    >>> Blog.objects.get(id=14) # __exact is implied

This is for convenience, because ``exact`` lookups are the common case.

iexact
------

Performs a case-insensitive exact match::

    >>> Blog.objects.get(name__iexact='beatles blog')

This will match ``'Beatles Blog'``, ``'beatles blog'``,
``'BeAtLes BLoG'``, and so forth.

contains
--------

Performs a case-sensitive containment test::

    Entry.objects.get(headline__contains='Lennon')

This will match the headline ``'Today Lennon honored'`` but not
``'today lennon honored'``.

SQLite doesn't support case-sensitive ``LIKE`` statements; when using
SQLite,``contains`` acts like ``icontains``.

.. admonition:: Escaping Percent Signs and Underscores in LIKE Statements

    The field lookups that equate to ``LIKE`` SQL statements (``iexact``,
    ``contains``, ``icontains``, ``startswith``, ``istartswith``, ``endswith``,
    and ``iendswith``) will automatically escape the two special characters used in
    ``LIKE`` statements -- the percent sign and the underscore. (In a ``LIKE``
    statement, the percent sign signifies a multiple-character wildcard and the
    underscore signifies a single-character wildcard.)

    This means things should work intuitively, so the abstraction doesn't leak.
    For example, to retrieve all the entries that contain a percent sign, just use
    the percent sign as any other character::

        Entry.objects.filter(headline__contains='%')

    Django takes care of the quoting for you. The resulting SQL will look something
    like this::

        SELECT ... WHERE headline LIKE '%\%%';

    The same goes for underscores. Both percentage signs and underscores are handled
    for you transparently.

icontains
---------

Performs a case-insensitive containment test::

    >>> Entry.objects.get(headline__icontains='Lennon')

Unlike ``contains``, ``icontains`` *will* match ``'today lennon honored'``.

gt, gte, lt, and lte
--------------------

These represent greater than, greater than or equal to, less than, and less
than or equal to::

    >>> Entry.objects.filter(id__gt=4)
    >>> Entry.objects.filter(id__lt=15)
    >>> Entry.objects.filter(id__gte=0)

These queries return any object with an ID greater than 4, an ID less than 15,
and an ID greater than or equal to 1, respectively.

You'll usually use these on numeric fields. Be careful with character fields
since character order isn't always what you'd expect (i.e., the string "4" sorts
*after* the string "10").

in
--

Filters where a value is on a given list::

    Entry.objects.filter(id__in=[1, 3, 4])

This returns all objects with the ID 1, 3, or 4.

startswith
----------

Performs a case-sensitive starts-with::

    >>> Entry.objects.filter(headline__startswith='Will')

This will return the headlines "Will he run?" and "Willbur named judge", but not
"Who is Will?" or "will found in crypt".

istartswith
-----------

Performs a case-insensitive starts-with::

    >>> Entry.objects.filter(headline__istartswith='will')

This will return the headlines "Will he run?", "Willbur named judge", and
"will found in crypt", but not "Who is Will?"

endswith and iendswith
----------------------

Perform case-sensitive and case-insensitive ends-with::

    >>> Entry.objects.filter(headline__endswith='cats')
    >>> Entry.objects.filter(headline__iendswith='cats')

Similar to ``startswith`` and ``istartswith``.

range
-----

Performs an inclusive range check::

    >>> start_date = datetime.date(2005, 1, 1)
    >>> end_date = datetime.date(2005, 3, 31)
    >>> Entry.objects.filter(pub_date__range=(start_date, end_date))

You can use ``range`` anywhere you can use ``BETWEEN`` in SQL -- for dates,
numbers, and even characters.

year, month, and day
--------------------

For date/datetime fields, perform exact year, month, or day matches::

    # Return all entries published in 2005
    >>>Entry.objects.filter(pub_date__year=2005)

    # Return all entries published in December
    >>> Entry.objects.filter(pub_date__month=12)

    # Return all entries published on the 3rd of the month
    >>> Entry.objects.filter(pub_date__day=3)

    # Combination: return all entries on Christmas of any year
    >>> Entry.objects.filter(pub_date__month=12, pub_date_day=25)

isnull
------

Takes either ``True`` or ``False``, which correspond to SQL queries of
``IS NULL`` and ``IS NOT NULL``, respectively::

    >>> Entry.objects.filter(pub_date__isnull=True)

search
------

A Boolean full-text search that takes advantage of full-text indexing. This is like
``contains`` but is significantly faster due to full-text indexing.

Note this is available only in MySQL and requires direct manipulation of the
database to add the full-text index.

The pk Lookup Shortcut
----------------------

For convenience, Django provides a ``pk`` lookup type, which stands for
"primary_key".

In the example ``Blog`` model, the primary key is the ``id`` field, so these
three statements are equivalent::

    >>> Blog.objects.get(id__exact=14) # Explicit form
    >>> 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 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)

``pk`` lookups also work across joins. For example, these three statements are
equivalent::

    >>> Entry.objects.filter(blog__id__exact=3) # Explicit form
    >>> Entry.objects.filter(blog__id=3) # __exact is implied
    >>> Entry.objects.filter(blog__pk=3) # __pk implies __id__exact

The point of ``pk`` is to give you a generic way to refer to the primary key in
cases where you're not sure whether the model's primary key is called ``id``.

Complex Lookups with Q Objects
==============================

Keyword argument queries -- in ``filter()`` and so on -- are ANDed together. If
you need to execute more complex queries (e.g., queries with ``OR``
statements), you can use ``Q`` objects.

A ``Q`` object (``django.db.models.Q``) is an object used to encapsulate a
collection of keyword arguments. These keyword arguments are specified as in
the "Field Lookups" section.

For example, this ``Q`` object encapsulates a single ``LIKE`` query::

    Q(question__startswith='What')

``Q`` objects can be combined using the ``&`` and ``|`` operators. When an
operator is used on two ``Q`` objects, it yields a new ``Q`` object. For example,
this statement yields a single ``Q`` object that represents the
OR of two ``"question__startswith"`` queries::

    Q(question__startswith='Who') | Q(question__startswith='What')

This is equivalent to the following SQL ``WHERE`` clause::

    WHERE question LIKE 'Who%' OR question LIKE 'What%'

You can compose statements of arbitrary complexity by combining ``Q`` objects
with the ``&`` and ``|`` operators. You can also use parenthetical grouping.

Each lookup function that takes keyword arguments (e.g., ``filter()``,
``exclude()``, ``get()``) can also be passed one or more ``Q`` objects as
positional (not-named) arguments. If you provide multiple ``Q`` object
arguments to a lookup function, the arguments will be ANDed together, for
example::

    Poll.objects.get(
        Q(question__startswith='Who'),
        Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
    )

roughly translates into the following SQL::

    SELECT * from polls WHERE question LIKE 'Who%'
        AND (pub_date = '2005-05-02' OR pub_date = '2005-05-06')

Lookup functions can mix the use of ``Q`` objects and keyword arguments. All
arguments provided to a lookup function (be they keyword arguments or ``Q``
objects) are ANDed together. However, if a ``Q`` object is provided, it must
precede the definition of any keyword arguments. For example, the following::

    Poll.objects.get(
        Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
        question__startswith='Who')

would be a valid query, equivalent to the previous example, but this::

    # INVALID QUERY
    Poll.objects.get(
        question__startswith='Who',
        Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)))

would not be valid.

You can find some examples online at http://www.djangoproject.com/documentation/models/or_lookups/.

Related Objects
===============

When you define a relationship in a model (i.e., a ``ForeignKey``,
``OneToOneField``, or ``ManyToManyField``), instances of that model will have
a convenient API to access the related object(s).

For example, an ``Entry`` object ``e`` can get its associated ``Blog`` object by
accessing the ``blog`` attribute ``e.blog``.

Django also creates API accessors for the "other" side of the relationship --
the link from the related model to the model that defines the relationship.
For example, a ``Blog`` object ``b`` has access to a list of all related
``Entry`` objects via the ``entry_set`` attribute: ``b.entry_set.all()``.

All examples in this section use the sample ``Blog``, ``Author``, and ``Entry``
models defined at the start of the appendix.

Lookups That Span Relationships
-------------------------------

Django offers a powerful and intuitive way to "follow" relationships in
lookups, taking care of the SQL ``JOIN``\s for you automatically behind the
scenes. To span a relationship, just use the field name of related fields
across models, separated by double underscores, until you get to the field you
want.

This example retrieves all ``Entry`` objects with a ``Blog`` whose ``name``
is ``'Beatles Blog'``::

    >>> Entry.objects.filter(blog__name__exact='Beatles Blog')

This spanning can be as deep as you'd like.

It works backward, too. To refer to a "reverse" relationship, just use the
lowercase name of the model.

This example retrieves all ``Blog`` objects that have at least one ``Entry``
whose ``headline`` contains ``'Lennon'``::

    >>> Blog.objects.filter(entry__headline__contains='Lennon')

Foreign Key Relationships
-------------------------

If a model has a ``ForeignKey``, instances of that model will have access to
the related (foreign) object via a simple attribute of the model, for example::

    e = Entry.objects.get(id=2)
    e.blog # Returns the related Blog object.

You can get and set via a foreign key attribute. As you may expect, changes to
the foreign key aren't saved to the database until you call ``save()``, for example::

    e = Entry.objects.get(id=2)
    e.blog = some_blog
    e.save()

If a ``ForeignKey`` field has ``null=True`` set (i.e., it allows ``NULL``
values), you can set it to ``NULL`` by assigning ``None`` to it and saving::

    e = Entry.objects.get(id=2)
    e.blog = None
    e.save() # "UPDATE blog_entry SET blog_id = NULL ...;"

Forward access to one-to-many relationships is cached the first time the
related object is accessed. Subsequent accesses to the foreign key on the same
object instance are cached, for example::

    e = Entry.objects.get(id=2)
    print e.blog  # Hits the database to retrieve the associated Blog.
    print e.blog  # Doesn't hit the database; uses cached version.

Note that the ``select_related()`` ``QuerySet`` method recursively prepopulates
the cache of all one-to-many relationships ahead of time::

    e = Entry.objects.select_related().get(id=2)
    print e.blog  # Doesn't hit the database; uses cached version.
    print e.blog  # Doesn't hit the database; uses cached version.

``select_related()`` is documented in the "QuerySet Methods That Return New
QuerySets" section.

"Reverse" Foreign Key Relationships
-----------------------------------

Foreign key relationships are automatically symmetrical -- a reverse
relationship is inferred from the presence of a ``ForeignKey`` pointing to
another model.

If a model has a ``ForeignKey``, instances of the foreign key model will have
access to a ``Manager`` that returns all instances of the first model that
relate to that object. By default, this ``Manager`` is named ``FOO_set``, where
``FOO`` is the source model name, lowercased. This ``Manager`` returns
``QuerySets``, which can be filtered and manipulated as described in the
"Retrieving Objects" section.

Here's an example::

    b = Blog.objects.get(id=1)
    b.entry_set.all() # Returns all Entry objects related to Blog.

    # b.entry_set is a Manager that returns QuerySets.
    b.entry_set.filter(headline__contains='Lennon')
    b.entry_set.count()

You can override the ``FOO_set`` name by setting the ``related_name``
parameter in the ``ForeignKey()`` definition. For example, if the ``Entry``
model was altered to ``blog = ForeignKey(Blog, related_name='entries')``, the
preceding example code would look like this::

    b = Blog.objects.get(id=1)
    b.entries.all() # Returns all Entry objects related to Blog.

    # b.entries is a Manager that returns QuerySets.
    b.entries.filter(headline__contains='Lennon')
    b.entries.count()

``related_name`` is particularly useful if a model has two foreign keys to the
same second model.

You cannot access a reverse ``ForeignKey`` ``Manager`` from the class; it must
be accessed from an instance::

    Blog.entry_set # Raises AttributeError: "Manager must be accessed via instance".

In addition to the ``QuerySet`` methods defined in the "Retrieving Objects" section,
the ``ForeignKey`` ``Manager`` has these additional methods:

* ``add(obj1, obj2, ...)``: Adds the specified model objects to the related
  object set, for example::

      b = Blog.objects.get(id=1)
      e = Entry.objects.get(id=234)
      b.entry_set.add(e) # Associates Entry e with Blog b.

* ``create(**kwargs)``: Creates a new object, saves it, and puts it in the
  related object set. It returns the newly created object::

      b = Blog.objects.get(id=1)
      e = b.entry_set.create(headline='Hello', body_text='Hi', pub_date=datetime.date(2005, 1, 1))
      # No need to call e.save() at this point -- it's already been saved.

  This is equivalent to (but much simpler than) the following::

      b = Blog.objects.get(id=1)
      e = Entry(blog=b, headline='Hello', body_text='Hi', pub_date=datetime.date(2005, 1, 1))
      e.save()

  Note that there's no need to specify the keyword argument of the model
  that defines the relationship. In the preceding example, we don't pass the
  parameter ``blog`` to ``create()``. Django figures out that the new
  ``Entry`` object's ``blog`` field should be set to ``b``.

* ``remove(obj1, obj2, ...)``: Removes the specified model objects from the
  related object set::

      b = Blog.objects.get(id=1)
      e = Entry.objects.get(id=234)
      b.entry_set.remove(e) # Disassociates Entry e from Blog b.

  In order to prevent database inconsistency, this method only exists on
  ``ForeignKey`` objects where ``null=True``. If the related field can't be
  set to ``None`` (``NULL``), then an object can't be removed from a
  relation without being added to another. In the preceding example, removing
  ``e`` from ``b.entry_set()`` is equivalent to doing ``e.blog = None``,
  and because the ``blog`` ``ForeignKey`` doesn't have ``null=True``, this
  is invalid.

* ``clear()``: Removes all objects from the related object set::

      b = Blog.objects.get(id=1)
      b.entry_set.clear()

  Note this doesn't delete the related objects -- it just disassociates
  them.

  Just like ``remove()``, ``clear()`` is only available on ``ForeignKey``s
  where ``null=True``.

To assign the members of a related set in one fell swoop, just assign to it
from any iterable object, for example::

    b = Blog.objects.get(id=1)
    b.entry_set = [e1, e2]

If the ``clear()`` method is available, any pre-existing objects will be
removed from the ``entry_set`` before all objects in the iterable (in this
case, a list) are added to the set. If the ``clear()`` method is *not*
available, all objects in the iterable will be added without removing any
existing elements.

Each "reverse" operation described in this section has an immediate effect on
the database. Every addition, creation, and deletion is immediately and
automatically saved to the database.

Many-to-Many Relationships
--------------------------

Both ends of a many-to-many relationship get automatic API access to the other
end. The API works just as a "reverse" one-to-many relationship (described
in the previous section).

The only difference is in the attribute naming: the model that defines the
``ManyToManyField`` uses the attribute name of that field itself, whereas the
"reverse" model uses the lowercased model name of the original model, plus
``'_set'`` (just like reverse one-to-many relationships).

An example makes this concept easier to understand::

    e = Entry.objects.get(id=3)
    e.authors.all() # Returns all Author objects for this Entry.
    e.authors.count()
    e.authors.filter(name__contains='John')

    a = Author.objects.get(id=5)
    a.entry_set.all() # Returns all Entry objects for this Author.

Like ``ForeignKey``, ``ManyToManyField`` can specify ``related_name``. In the
preceding example, if the ``ManyToManyField`` in ``Entry`` had specified
``related_name='entries'``, then each ``Author`` instance would have an
``entries`` attribute instead of ``entry_set``.

.. admonition:: How Are the Backward Relationships Possible?

    Other object-relational mappers require you to define relationships on both
    sides. The Django developers believe this is a violation of the DRY (Don't
    Repeat Yourself) principle, so Django requires you to define the
    relationship on only one end. But how is this possible, given that a model
    class doesn't know which other model classes are related to it until those
    other model classes are loaded?

    The answer lies in the ``INSTALLED_APPS`` setting. The first time any model
    is loaded, Django iterates over every model in ``INSTALLED_APPS`` and
    creates the backward relationships in memory as needed. Essentially, one of
    the functions of ``INSTALLED_APPS`` is to tell Django the entire model
    domain.

Queries Over Related Objects
----------------------------

Queries involving related objects follow the same rules as queries involving
normal value fields. When specifying the value for a query to match, you
may use either an object instance itself or the primary key value for the
object.

For example, if you have a ``Blog`` object ``b`` with ``id=5``, the following
three queries would be identical::

    Entry.objects.filter(blog=b) # Query using object instance
    Entry.objects.filter(blog=b.id) # Query using id from instance
    Entry.objects.filter(blog=5) # Query using id directly

Deleting Objects
================

The delete method, conveniently, is named ``delete()``. This method immediately
deletes the object and has no return value::

    e.delete()

You can also delete objects in bulk. Every ``QuerySet`` has a ``delete()``
method, which deletes all members of that ``QuerySet``. For example, this
deletes all ``Entry`` objects with a ``pub_date`` year of 2005::

    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 that
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
*do* want to delete all the objects, then you have to explicitly request a
complete query set::

    Entry.objects.all().delete()

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 default
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::

    # 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
=======================

If you find yourself needing to write an SQL query that is too complex for
Django's database mapper to handle, you can fall back into raw SQL statement
mode.

The preferred way to do this is by giving your model custom methods or custom
manager methods that execute queries. Although there's nothing in Django that
*requires* database queries to live in the model layer, this approach keeps all
your data access logic in one place, which is smart from a code organization
standpoint. For instructions, see Appendix A.

Finally, it's important to note that the Django database layer is merely an
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.


================================================
FILE: Python/DjangoBook/appendixC.rst
================================================
==================================
Appendix C: Generic View Reference
==================================

Chapter 11 introduced generic views but leaves out some of the gory details.
This appendix describes each generic view along with all the options each view can
take. Be sure to read Chapter 11 before trying to understand the reference
material that follows. You might want to refer back to the ``Book``,
``Publisher``, and ``Author`` objects defined in that chapter; the examples that
follow use these models.

Common Arguments to Generic Views
=================================

Most of these views take a large number of arguments that can change the generic
view's behavior. Many of these arguments work the same across a large number of
views. Table C-1 describes each of these common arguments; anytime you see one
of these arguments in a generic view's argument list, it will work as described in
the table.

.. table:: Table C-1. Common Arguments to Generic Views

    ==========================  ===============================================
    Argument                    Description
    ==========================  ===============================================
    ``allow_empty``             A Boolean specifying whether to display the
                                page if no objects are available. If this is
                                ``False`` and no objects are available, the view
                                will raise a 404 error instead of displaying an
                                empty page. By default, this is ``True``.

    ``context_processors``      A list of additional template-context processors
                                (besides the defaults) to apply to the view's
                                template. See Chapter 9 for information on
                                template context processors.

    ``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.

    ``mimetype``                The MIME type to use for the resulting
                                document. It defaults to the value of the
                                ``DEFAULT_MIME_TYPE`` setting, which is
                                ``text/html`` if you haven't changed it.

    ``queryset``                A ``QuerySet`` (i.e., something like
                                ``Author.objects.all()``) to read objects from.
                                See Appendix B for more information about
                                ``QuerySet`` objects. Most generic views require
                                this argument.

    ``template_loader``         The template loader to use when loading the
                                template. By default, it's
                                ``django.template.loader``. See Chapter 9 for
                                information on template loaders.

    ``template_name``           The full name of a template to use in rendering
                                the page. This lets you override the default
                                template name derived from the ``QuerySet``.

    ``template_object_name``    The name of the template variable to
                                use in the template context. By default, this is
                                ``'object'``. Views that list more than one
                                object (i.e., ``object_list`` views and various
                                objects-for-date views) will append ``'_list'``
                                to the value of this parameter.
    ==========================  ===============================================

"Simple" Generic Views
======================

The module``django.views.generic.simple`` contains simple views that handle a
couple of common cases: rendering a template when no view logic is needed and
issuing a redirect.

Rendering a Template
--------------------

*View function*: ``django.views.generic.simple.direct_to_template``

This view renders a given template, passing it a ``{{ params }}`` template
variable, which is a dictionary of the parameters captured in the URL.

Example
```````

Given the following URLconf::

    from django.conf.urls.defaults import *
    from django.views.generic.simple import direct_to_template

    urlpatterns = patterns('',
        (r'^foo/$',             direct_to_template, {'template': 'foo_index.html'}),
        (r'^foo/(?P<id>\d+)/$', direct_to_template, {'template': 'foo_detail.html'}),
    )

a request to ``/foo/`` would render the template ``foo_index.html``, and a
request to ``/foo/15/`` would render ``foo_detail.html`` with a context
variable ``{{ params.id }}`` that is set to ``15``.

Required Arguments
``````````````````

* ``template``: The full name of a template to use.

Redirecting to Another URL
--------------------------

*View function*: ``django.views.generic.simple.redirect_to``

This view redirects to another URL. The given URL may contain dictionary-style string
formatting, which will be interpolated against the parameters captured in the
URL.

If the given URL is ``None``, Django will return an HTTP 410 ("Gone") message.

Example
```````

This URLconf redirects from ``/foo/<id>/`` to ``/bar/<id>/``::

    from django.conf.urls.defaults import *
    from django.views.generic.simple import redirect_to

    urlpatterns = patterns('django.views.generic.simple',
        ('^foo/(?p<id>\d+)/$', redirect_to, {'url': '/bar/%(id)s/'}),
    )

This example returns a "Gone" response for requests to ``/bar/``::

    from django.views.generic.simple import redirect_to

    urlpatterns = patterns('django.views.generic.simple',
        ('^bar/$', redirect_to, {'url': None}),
    )

Required Arguments
``````````````````

* ``url``: The URL to redirect to, as a string. Or ``None`` to return a 410
  ("Gone") HTTP response.

List/Detail Generic Views
=========================

The list/detail generic views (in the module
``django.views.generic.list_detail``) handle the common case of displaying a
list of items at one view and individual "detail" views of those items at
another.

Lists of Objects
----------------

*View function*: ``django.views.generic.list_detail.object_list``

Use this view to display a page representing a list of objects.

Example
```````

Given the ``Author`` object from Chapter 5, we can use the ``object_list`` view
to show a simple list of all authors given the following URLconf snippet::

    from mysite.books.models import Author
    from django.conf.urls.defaults import *
    from django.views.generic import list_detail

    author_list_info = {
        'queryset':   Author.objects.all(),
    }

    urlpatterns = patterns('',
        (r'authors/$', list_detail.object_list, author_list_info)
    )

Required Arguments
``````````````````

* ``queryset``: A ``QuerySet`` of objects to list (see Table C-1).

Optional Arguments
``````````````````

* ``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
  number, or a ``page`` variable specified in the URLconf. See the following
  "Notes on Pagination" section.

Additionally, this view may take any of these common arguments described in
Table C-1:

* ``allow_empty``
* ``context_processors``
* ``extra_context``
* ``mimetype``
* ``template_loader``
* ``template_name``
* ``template_object_name``

Template Name
`````````````

If ``template_name`` isn't specified, this view will use the template
``<app_label>/<model_name>_list.html`` by default. Both the application label and the
model name are derived from the ``queryset`` parameter. The application label is the
name of the application that the model is defined in, and the model name is the
lowercased version of the name of the model class.

In the previous example using ``Author.objects.all()`` as the ``queryset``, the application
label would be ``books`` and the model name would be ``author``. This means
the default template would be ``books/author_list.html``.

Template Context
````````````````

In addition to ``extra_context``, the template's context will contain the following:

* ``object_list``: The list of objects. This variable's name depends on the
  ``template_object_name`` parameter, which is ``'object'`` by default. If
  ``template_object_name`` is ``'foo'``, this variable's name will be
  ``foo_list``.

* ``is_paginated``: A Boolean representing whether the results are
  paginated. Specifically, this is set to ``False`` if the number of
  available objects is less than or equal to ``paginate_by``.

If the results are paginated, the context will contain these extra variables:

* ``results_per_page``: The number of objects per page. (This is the same as
  the ``paginate_by`` parameter.)

* ``has_next``: A Boolean representing whether there's a next page.

* ``has_previous``: A Boolean representing whether there's a previous page.

* ``page``: The current page number, as an integer. This is 1-based.

* ``next``: The next page number, as an integer. If there's no next page,
  this will still be an integer representing the theoretical next-page
  number. This is 1-based.

* ``previous``: The previous page number, as an integer. 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
  page.

.. admonition:: A Note on Pagination

    If ``paginate_by`` is specified, Django will paginate the results. You can
    specify the page number in the URL in one of two ways:

    * Use the ``page`` parameter in the URLconf. For example, this is what
      your URLconf might look like::

        (r'^objects/page(?P<page>[0-9]+)/$', 'object_list', dict(info_dict))

    * Pass the page number via the ``page`` query-string parameter. For
      example, a URL would look like this::

        /objects/?page=3

    In both cases, ``page`` is 1-based, not 0-based, so the first page would be
    represented as page ``1``.

Detail Views
------------

*View function*: ``django.views.generic.list_detail.object_detail``

This view provides a "detail" view of a single object.

Example
```````

Continuing the previous ``object_list`` example, we could add a detail view for a
given author by modifying the URLconf:

.. parsed-literal::

    from mysite.books.models import Author
    from django.conf.urls.defaults import *
    from django.views.generic import list_detail

    author_list_info = {
        'queryset' :   Author.objects.all(),
    }
    **author_detail_info = {**
        **"queryset" : Author.objects.all(),**
        **"template_object_name" : "author",**
    **}**

    urlpatterns = patterns('',
        (r'authors/$', list_detail.object_list, author_list_info),
        **(r'^authors/(?P<object_id>\d+)/$', list_detail.object_detail, author_detail_info),**
    )

Required Arguments
``````````````````

* ``queryset``: A ``QuerySet`` that will be searched for the object (see Table C-1).

and either

* ``object_id``: The value of the primary-key field for the object.

or

* ``slug``: The slug of the given object. If you pass this field, then the
  ``slug_field`` argument (see the following section) is also required.

Optional Arguments
``````````````````

* ``slug_field``: The name of the field on the object containing the slug.
  This is required if you are using the ``slug`` argument, but it must be
  absent if you're using the ``object_id`` argument.

* ``template_name_field``: The name of a field on the object whose value is
  the template name to use. This lets you store template names in your data.

  In other words, if your object has a field ``'the_template'`` that
  contains a string ``'foo.html'``, and you set ``template_name_field`` to
  ``'the_template'``, then the generic view for this object will use the
  template ``'foo.html'``.

  If the template named by ``template_name_field`` doesn't exist, the one
  named by ``template_name`` is used instead.  It's a bit of a
  brain-bender, but it's useful in some cases.

This view may also take these common arguments (see Table C-1):

* ``context_processors``
* ``extra_context``
* ``mimetype``
* ``template_loader``
* ``template_name``
* ``template_object_name``

Template Name
`````````````

If ``template_name`` and ``template_name_field`` aren't specified, this view
will use the template ``<app_label>/<model_name>_detail.html`` by default.

Template Context
````````````````

In addition to ``extra_context``, the template's context will be as follows:

* ``object``: The object. This variable's name depends on the
  ``template_object_name`` parameter, which is ``'object'`` by default. If
  ``template_object_name`` is ``'foo'``, this variable's name will be
  ``foo``.

Date-Based Generic Views
========================

Date-based generic views are generally used to provide a set of "archive"
pages for dated material. Think year/month/day archives for a newspaper, or a
typical blog archive.

.. admonition:: Tip:

    By default, these views ignore objects with dates in the future.

    This means that if you try to visit an archive page in the future, Django
    will automatically show a 404 ("Page not found") error, even if there are objects
    published that day.

    Thus, you can publish postdated objects that don't appear publicly until
    their desired publication date.

    However, for different types of date-based objects, this isn't appropriate
    (e.g., a calendar of upcoming events). For these views, setting the
    ``allow_future`` option to ``True`` will make the future objects appear (and
    allow users to visit "future" archive pages).

Archive Index
-------------

*View function*: ``django.views.generic.date_based.archive_index``

This view provides a top-level index page showing the "latest" (i.e., most
recent) objects by date.

Example
```````

Say a typical book publisher wants a page of recently published books. Given some
``Book`` object with a ``publication_date`` field, we can use the
``archive_index`` view for this common task:

.. parsed-literal::

    from mysite.books.models import Book
    from django.conf.urls.defaults import *
    from django.views.generic import date_based

    book_info = {
        "queryset"   : Book.objects.all(),
        "date_field" : "publication_date"
    }

    urlpatterns = patterns('',
        (r'^books/$', date_based.archive_index, book_info),
    )

Required Arguments
``````````````````

* ``date_field``: The name of the ``DateField`` or ``DateTimeField`` in the
  ``QuerySet``'s model that the date-based archive should use to determine
  the objects on the page.

* ``queryset``: A ``QuerySet`` of objects for which the archive serves.

Optional Arguments
``````````````````

* ``allow_future``: A Boolean specifying whether to include "future" objects
  on this page, as described in the previous note.

* ``num_latest``: The number of latest objects to send to the template
  context. By default, it's 15.

This view may also take these common arguments (see Table C-1):

* ``allow_empty``
* ``context_processors``
* ``extra_context``
* ``mimetype``
* ``template_loader``
* ``template_name``

Template Name
`````````````

If ``template_name`` isn't specified, this view will use the template
``<app_label>/<model_name>_archive.html`` by default.

Template Context
````````````````

In addition to ``extra_context``, the template's context will be as follows:

* ``date_list``: A list of ``datetime.date`` objects representing all years
  that have objects available according to ``queryset``. These are ordered
  in reverse.

  For example, if you have blog entries from 2003 through 2006, this list
  will contain four ``datetime.date`` objects: one for each of those years.

* ``latest``: The ``num_latest`` objects in the system, in descending order
  by ``date_field``. For example, if ``num_latest`` is ``10``, then
  ``latest`` will be a list of the latest ten objects in ``queryset``.

Year Archives
-------------

*View function*: ``django.views.generic.date_based.archive_year``

Use this view for yearly archive pages. These pages have a list of months in
which objects exists, and they can optionally display all the objects published in
a given year.

Example
```````

Extending the ``archive_index`` example from earlier, we'll add a way to view all
the books published in a given year:

.. parsed-literal::

    from mysite.books.models import Book
    from django.conf.urls.defaults import *
    from django.views.generic import date_based

    book_info = {
        "queryset"   : Book.objects.all(),
        "date_field" : "publication_date"
    }

    urlpatterns = patterns('',
        (r'^books/$', date_based.archive_index, book_info),
        **(r'^books/(?P<year>\d{4})/?$', date_based.archive_year, book_info),**
    )

Required Arguments
``````````````````

* ``date_field``: As for ``archive_index`` (see the previous section).

* ``queryset``: A ``QuerySet`` of objects for which the archive serves.

* ``year``: The four-digit year for which the archive serves (as in our
  example, this is usually taken from a URL parameter).

Optional Arguments
``````````````````

* ``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``,
  this list of objects will be made available to the template as
  ``object_list``. (The name ``object_list`` may be different; see the
  information about ``object_list`` in the following "Template Context"
  section.) By default, this is ``False``.

* ``allow_future``: A Boolean specifying whether to include "future" objects
  on this page.

This view may also take these common arguments (see Table C-1):

* ``allow_empty``
* ``context_processors``
* ``extra_context``
* ``mimetype``
* ``template_loader``
* ``template_name``
* ``template_object_name``

Template Name
`````````````

If ``template_name`` isn't specified, this view will use the template
``<app_label>/<model_name>_archive_year.html`` by default.

Template Context
````````````````

In addition to ``extra_context``, the template's context will be as follows:

* ``date_list``: A list of ``datetime.date`` objects representing all months
  that have objects available in the given year, according to ``queryset``,
  in ascending order.

* ``year``: The given year, as a four-character string.

* ``object_list``: If the ``make_object_list`` parameter is ``True``, this
  will be set to a list of objects available for the given year, ordered by
  the date field. This variable's name depends on the
  ``template_object_name`` parameter, which is ``'object'`` by default. If
  ``template_object_name`` is ``'foo'``, this variable's name will be
  ``foo_list``.

  If ``make_object_list`` is ``False``, ``object_list`` will be passed to
  the template as an empty list.

Month Archives
--------------

*View function*: ``django.views.generic.date_based.archive_month``

This view provides monthly archive pages showing all objects for a given month.

Example
```````

Continuing with our example, adding month views should look familiar:

.. parsed-literal::

    urlpatterns = patterns('',
        (r'^books/$', date_based.archive_index, book_info),
        (r'^books/(?P<year>\d{4})/?$', date_based.archive_year, book_info),
        **(**
            **r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/$',**
            **date_based.archive_month,**
            **book_info**
        **),**
    )

Required Arguments
``````````````````

* ``year``: The four-digit year for which the archive serves (a string).

* ``month``: The month for which the archive serves, formatted according to
  the ``month_format`` argument.

* ``queryset``: A ``QuerySet`` of objects for which the archive serves.

* ``date_field``: The name of the ``DateField`` or ``DateTimeField`` in the
  ``QuerySet``'s model that the date-based archive should use to determine
  the objects on the page.

Optional Arguments
``````````````````

* ``month_format``: A format string that regulates what format the ``month``
  parameter uses. This should be in the syntax accepted by Python's
  ``time.strftime``. (See Python's strftime documentation at
  http://docs.python.org/library/time.html#time.strftime.) It's set
  to ``"%b"`` by default, which is a three-letter month abbreviation (i.e.,
  "jan", "feb", etc.). To change it to use numbers, use ``"%m"``.

* ``allow_future``: A Boolean specifying whether to include "future" objects
  on this page, as described in the previous note.

This view may also take these common arguments (see Table C-1):

* ``allow_empty``
* ``context_processors``
* ``extra_context``
* ``mimetype``
* ``template_loader``
* ``template_name``
* ``template_object_name``

Template Name
`````````````

If ``template_name`` isn't specified, this view will use the template
``<app_label>/<model_name>_archive_month.html`` by default.

Template Context
````````````````

In addition to ``extra_context``, the template's context will be as follows:

* ``month``: A ``datetime.date`` object representing the given month.

* ``next_month``: A ``datetime.date`` object representing the first day of
  the next month. If the next month is in the future, this will be ``None``.

* ``previous_month``: A ``datetime.date`` object representing the first day
  of the previous month. Unlike ``next_month``, this will never be ``None``.

* ``object_list``: A list of objects available for the given month. This
  variable's name depends on the ``template_object_name`` parameter, which
  is ``'object'`` by default. If ``template_object_name`` is ``'foo'``, this
  variable's name will be ``foo_list``.

Week Archives
-------------

*View function*: ``django.views.generic.date_based.archive_week``

This view shows all objects in a given week.

.. note::

    For the sake of consistency with Python's built-in date/time handling,
    Django assumes that the first day of the week is Sunday.

Example
```````

.. parsed-literal::

    urlpatterns = patterns('',
        # ...
        **(**
            **r'^(?P<year>\d{4})/(?P<week>\d{2})/$',**
            **date_based.archive_week,**
            **book_info**
        **),**
    )


Required Arguments
``````````````````

* ``year``: The four-digit year for which the archive serves (a string).

* ``week``: The week of the year for which the archive serves (a string).

* ``queryset``: A ``QuerySet`` of objects for which the archive serves.

* ``date_field``: The name of the ``DateField`` or ``DateTimeField`` in the
  ``QuerySet``'s model that the date-based archive should use to determine
  the objects on the page.

Optional Arguments
``````````````````

* ``allow_future``: A Boolean specifying whether to include "future" objects
  on this page, as described in the previous note.

This view may also take these common arguments (see Table C-1):

* ``allow_empty``
* ``context_processors``
* ``extra_context``
* ``mimetype``
* ``template_loader``
* ``template_name``
* ``template_object_name``

Template Name
`````````````

If ``template_name`` isn't specified, this view will use the template
``<app_label>/<model_name>_archive_week.html`` by default.

Template Context
````````````````

In addition to ``extra_context``, the template's context will be as follows:

* ``week``: A ``datetime.date`` object representing the first day of the
  given week.

* ``object_list``: A list of objects available for the given week. This
  variable's name depends on the ``template_object_name`` parameter, which
  is ``'object'`` by default. If ``template_object_name`` is ``'foo'``, this
  variable's name will be ``foo_list``.

Day Archives
------------

*View function*: ``django.views.generic.date_based.archive_day``

This view generates all objects in a given day.

Example
```````

.. parsed-literal::

    urlpatterns = patterns('',
        # ...
        **(**
            **r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\d{2})/$',**
            **date_based.archive_day,**
            **book_info**
        **),**
    )


Required Arguments
``````````````````

* ``year``: The four-digit year for which the archive serves (a string).

* ``month``: The month for which the archive serves, formatted according to the
  ``month_format`` argument.

* ``day``: The day for which the archive serves, formatted according to the
  ``day_format`` argument.

* ``queryset``: A ``QuerySet`` of objects for which the archive serves.

* ``date_field``: The name of the ``DateField`` or ``DateTimeField`` in the
  ``QuerySet``'s model that the date-based archive should use to determine
  the objects on the page.

Optional Arguments
``````````````````

* ``month_format``: A format string that regulates what format the ``month``
  parameter uses. See the detailed explanation in the "Month Archives"
  section, above.

* ``day_format``: Like ``month_format``, but for the ``day`` parameter. It
  defaults to ``"%d"`` (the day of the month as a decimal number, 01-31).

* ``allow_future``: A Boolean specifying whether to include "future" objects
  on this page, as described in the previous note.

This view may also take these common arguments (see Table C-1):

* ``allow_empty``
* ``context_processors``
* ``extra_context``
* ``mimetype``
* ``template_loader``
* ``template_name``
* ``template_object_name``

Template Name
`````````````

If ``template_name`` isn't specified, this view will use the template
``<app_label>/<model_name>_archive_day.html`` by default.

Template Context
````````````````

In addition to ``extra_context``, the template's context will be as follows:

* ``day``: A ``datetime.date`` object representing the given day.

* ``next_day``: A ``datetime.date`` object representing the next day. If the
  next day is in the future, this will be ``None``.

* ``previous_day``: A ``datetime.date`` object representing the previous day.
  Unlike ``next_day``, this will never be ``None``.

* ``object_list``: A list of objects available for the given day. This
  variable's name depends on the ``template_object_name`` parameter, which
  is ``'object'`` by default. If ``template_object_name`` is ``'foo'``, this
  variable's name will be ``foo_list``.

Archive for Today
-----------------

The ``django.views.generic.date_based.archive_today`` view shows all objects for
*today*. This is exactly the same as ``archive_day``, except the
``year``/``month``/``day`` arguments are not used, and today's date is used
instead.

Example
```````

.. parsed-literal::

    urlpatterns = patterns('',
        # ...
        **(r'^books/today/$', date_based.archive_today, book_info),**
    )


Date-Based Detail Pages
-----------------------

*View function*: ``django.views.generic.date_based.object_detail``

Use this view for a page representing an individual object.

This has a different URL from the ``object_detail`` view; the ``object_detail``
view uses URLs like ``/entries/<slug>/``, while this one uses URLs like
``/entries/2006/aug/27/<slug>/``.

.. note::

    If you're using date-based detail pages with slugs in the URLs, you probably
    also want to use the ``unique_for_date`` option on the slug field to
    validate that slugs aren't duplicated in a single day. See Appendix A for
    details on ``unique_for_date``.

Example
```````

This one differs (slightly) from all the other date-based examples in that we
need to provide either an object ID or a slug so that Django can look up the
object in question.

Since the object we're using doesn't have a slug field, we'll use ID-based URLs.
It's considered a best practice to use a slug field, but in the interest of
simplicity we'll let it go.

.. parsed-literal::

    urlpatterns = patterns('',
        # ...
        **(**
            **r'^(?P<year>\d{4})/(?P<month>[a-z]{3})/(?P<day>\d{2})/(?P<object_id>[\w-]+)/$',**
            **date_based.object_detail,**
            **book_info**
        **),**
    )

Required Arguments
``````````````````

* ``year``: The object's four-digit year (a string).

* ``month``: The object's month, formatted according to the ``month_format``
  argument.

* ``day``: The object's day, formatted according to the ``day_format`` argument.

* ``queryset``: A ``QuerySet`` that contains the object.

* ``date_field``: The name of the ``DateField`` or ``DateTimeField`` in the
  ``QuerySet``'s model that the generic view should use to look up the
  object according to ``year``, ``month``, and ``day``.

You'll also need either:

* ``object_id``: The value of the primary-key field for the object.

or:

* ``slug``: The slug of the given object. If you pass this field, then the
  ``slug_field`` argument (described in the following section) is also
  required.

Optional Arguments
``````````````````

* ``allow_future``: A Boolean specifying whether to include "future" objects
  on this page, as described in the previous note.

* ``day_format``: Like ``month_format``, but for the ``day`` parameter. It
  defaults to ``"%d"`` (the day of the month as a decimal number, 01-31).

* ``month_format``: A format string that regulates what format the ``month``
  parameter uses. See the detailed explanation in the "Month Archives"
  section, above.

* ``slug_field``: The name of the field on the object containing the slug.
  This is required if you are using the ``slug`` argument, but it must be
  absent if you're using the ``object_id`` argument.

* ``template_name_field``: The name of a field on the object whose value is
  the template name to use. This lets you store template names in the data.
  In other words, if your object has a field ``'the_template'`` that
  contains a string ``'foo.html'``, and you set ``template_name_field`` to
  ``'the_template'``, then the generic view for this object will use the
  template ``'foo.html'``.

This view may also take these common arguments (see Table C-1):

* ``context_processors``
* ``extra_context``
* ``mimetype``
* ``template_loader``
* ``template_name``
* ``template_object_name``

Template Name
`````````````

If ``template_name`` and ``template_name_field`` aren't specified, this view
will use the template ``<app_label>/<model_name>_detail.html`` by default.

Template Context
````````````````

In addition to ``extra_context``, the template's context will be as follows:

* ``object``: The object. This variable's name depends on the
  ``template_object_name`` parameter, which is ``'object'`` by default. If
  ``template_object_name`` is ``'foo'``, this variable's name will be
  ``foo``.


================================================
FILE: Python/DjangoBook/appendixD.rst
================================================
====================
Appendix D: Settings
====================

Your Django settings file contains all the configuration of your Django
installation. This appendix explains how settings work and which settings are
available.

What's a Settings File?
=======================

A *settings file* is just a Python module with module-level variables.

Here are a couple of example settings::

    DEBUG = False
    DEFAULT_FROM_EMAIL = 'webmaster@example.com'
    TEMPLATE_DIRS = ('/home/templates/mike', '/home/templates/john')

Because a settings file is a Python module, the following apply:

* It must be valid Python code; syntax errors aren't allowed.

* It can assign settings dynamically using normal Python syntax,
  for example::

      MY_SETTING = [str(i) for i in range(30)]

* It can import values from other settings files.

Default Settings
----------------

A Django settings file doesn't have to define any settings if it doesn't need
to. Each setting has a sensible default value. These defaults live in the file
``django/conf/global_settings.py``.

Here's the algorithm Django uses in compiling settings:

* Load settings from ``global_settings.py``.
* Load settings from the specified settings file, overriding the global
  settings as necessary.

Note that a settings file should *not* import from ``global_settings``, because
that's redundant.

Seeing Which Settings You've Changed
------------------------------------

There's an easy way to view which of your settings deviate from the default
settings. The command ``manage.py diffsettings`` displays differences between
the current settings file and Django's default settings.

``manage.py`` is described in more detail in Appendix F.

Using Settings in Python Code
-----------------------------

In your Django applications, use settings by importing the object
``django.conf.settings``, for example::

    from django.conf import settings

    if settings.DEBUG:
        # Do something

Note that ``django.conf.settings`` isn't a module -- it's an object. So
importing individual settings is not possible::

    from django.conf.settings import DEBUG  # This won't work.

Also note that your code should *not* import from either ``global_settings`` or
your own settings file. ``django.conf.settings`` abstracts the concepts of
default settings and site-specific settings; it presents a single interface.
It also decouples the code that uses settings from the location of your
settings.

Altering Settings at Runtime
----------------------------

You shouldn't alter settings in your applications at runtime. For example,
don't do this in a view::

    from django.conf import settings

    settings.DEBUG = True   # Don't do this!

The only place that settings should be defined in is a settings file.

Security
--------

Because a settings file contains sensitive information, such as the database
password, you should make every attempt to limit access to it. For example,
change its file permissions so that only you and your Web server's user can
read it. This is especially important in a shared-hosting environment.

Creating Your Own Settings
--------------------------

There's nothing stopping you from creating your own settings, for your own
Django applications. Just follow these conventions:

* Use all uppercase for setting names.

* For settings that are sequences, use tuples instead of lists. Settings
  should be considered immutable and shouldn't be changed once they're
  defined. Using tuples mirrors these semantics.

* Don't reinvent an already existing setting.

Designating the Settings: DJANGO_SETTINGS_MODULE
================================================

When you use Django, you have to tell it which settings you're using. Do this
by using the environment variable ``DJANGO_SETTINGS_MODULE``.

The value of ``DJANGO_SETTINGS_MODULE`` should be in Python path syntax (e.g.,
``mysite.settings``). Note that the settings module should be on the
Python import search path (``PYTHONPATH``).

.. admonition:: Tip:

    A good guide to ``PYTHONPATH`` can be found at
    http://diveintopython.org/getting_to_know_python/everything_is_an_object.html.

The django-admin.py Utility
---------------------------

When using ``django-admin.py`` (see Appendix F), you can either set the
environment variable once or explicitly pass in the settings module each time
you run the utility.

Here's an example using the Unix Bash shell::

    export DJANGO_SETTINGS_MODULE=mysite.settings
    django-admin.py runserver

Here's an example using the Windows shell::

    set DJANGO_SETTINGS_MODULE=mysite.settings
    django-admin.py runserver

Use the ``--settings`` command-line argument to specify the settings manually::

    django-admin.py runserver --settings=mysite.settings

The ``manage.py`` utility created by ``startproject`` as part of the project
skeleton sets ``DJANGO_SETTINGS_MODULE`` automatically; see Appendix F for more
about ``manage.py``.

On the Server (mod_python)
--------------------------

In your live server environment, you'll need to tell Apache/mod_python which
settings file to use. Do that with ``SetEnv``::

    <Location "/mysite/">
        SetHandler python-program
        PythonHandler django.core.handlers.modpython
        SetEnv DJANGO_SETTINGS_MODULE mysite.settings
    </Location>

For more information, read the Django mod_python documentation online at
http://docs.djangoproject.com/en/dev/howto/deployment/modpython/.

Using Settings Without Setting DJANGO_SETTINGS_MODULE
=====================================================

In some cases, you might want to bypass the ``DJANGO_SETTINGS_MODULE``
environment variable. For example, if you're using the template system by
itself, you likely don't want to have to set up an environment variable
pointing to a settings module.

In these cases, you can configure Django's settings manually. Do this by
calling ``django.conf.settings.configure()``. Here's an example::

    from django.conf import settings

    settings.configure(
        DEBUG = True,
        TEMPLATE_DEBUG = True,
        TEMPLATE_DIRS = [
            '/home/web-apps/myapp',
            '/home/web-apps/base',
        ]
    )

Pass ``configure()`` as many keyword arguments as you'd like, with each keyword
argument representing a setting and its value. Each argument name should be all
uppercase, with the same name as the settings described earlier. If a particular
setting is not passed to ``configure()`` and is needed at some later point,
Django will use the default setting value.

Configuring Django in this fashion is mostly necessary -- and, indeed,
recommended -- when you're using a piece of the framework inside a larger
application.

Consequently, when configured via ``settings.configure()``, Django will not
make any modifications to the process environment variables. (See the
explanation of ``TIME_ZONE`` later in this appendix for why this would normally occur.)
It's assumed that you're already in full control of your environment in these cases.

Custom Default Settings
-----------------------

If you'd like default values to come from somewhere other than
``django.conf.global_settings``, you can pass in a module or class that
provides the default settings as the ``default_settings`` argument (or as the
first positional argument) in the call to ``configure()``.

In this example, default settings are taken from ``myapp_defaults``, and the
``DEBUG`` setting is set to ``True``, regardless of its value in
``myapp_defaults``::

    from django.conf import settings
    from myapp import myapp_defaults

    settings.configure(default_settings=myapp_defaults, DEBUG=True)

The following example, which uses ``myapp_defaults`` as a positional argument,
is equivalent::

    settings.configure(myapp_defaults, DEBUG = True)

Normally, you will not need to override the defaults in this fashion. The
Django defaults are sufficiently tame that you can safely use them. Be aware
that if you do pass in a new default module, it entirely *replaces* the Django
defaults, so you must specify a value for every possible setting that might be
used in that code you are importing. Check in
``django.conf.settings.global_settings`` for the full list.

Either configure() or DJANGO_SETTINGS_MODULE Is Required
--------------------------------------------------------

If you're not setting the ``DJANGO_SETTINGS_MODULE`` environment variable, you
*must* call ``configure()`` at some point before using any code that reads
settings.

If you don't set ``DJANGO_SETTINGS_MODULE`` and don't call ``configure()``,
Django will raise an ``EnvironmentError`` exception the first time a setting
is accessed.

If you set ``DJANGO_SETTINGS_MODULE``, access settings values somehow, and *then*
call ``configure()``, Django will raise an ``EnvironmentError`` stating that settings
have already been configured.

Also, it's an error to call ``configure()`` more than once, or to call
``configure()`` after any setting has been accessed.

It boils down to this: use exactly one of either ``configure()`` or
``DJANGO_SETTINGS_MODULE``, and only once.

Available Settings
==================

The following sections consist of a list of the main available settings,
in alphabetical order, and their default values.

ABSOLUTE_URL_OVERRIDES
----------------------

*Default*: ``{}`` (empty dictionary)

This is a dictionary mapping ``"app_label.model_name"`` strings to functions that take
a model object and return its URL. This is a way of overriding
``get_absolute_url()`` methods on a per-installation basis. Here's an example::

    ABSOLUTE_URL_OVERRIDES = {
        'blogs.weblog': lambda o: "/blogs/%s/" % o.slug,
        'news.story': lambda o: "/stories/%s/%s/" % (o.pub_year, o.slug),
    }

Note that the model name used in this setting should be all lowercase, regardless
of the case of the actual model class name.

ADMIN_MEDIA_PREFIX
------------------

*Default*: ``'/media/'``

This setting is the URL prefix for admin media: CSS, JavaScript, and images.
Make sure to use a trailing slash.

ADMINS
------

*Default*: ``()`` (empty tuple)

This is a tuple that lists people who get code error notifications. When
``DEBUG=False`` and a view raises an exception, Django will email these people
with the full exception information. Each member of the tuple should be a tuple
of (Full name, e-mail address), for example::

    (('John', 'john@example.com'), ('Mary', 'mary@example.com'))

Note that Django will email *all* of these people whenever an error happens.

ALLOWED_INCLUDE_ROOTS
---------------------

*Default*: ``()`` (empty tuple)

This is a tuple of strings representing allowed prefixes for the ``{% ssi %}`` template
tag. This is a security measure, so that template authors can't access files
that they shouldn't be accessing.

For example, if ``ALLOWED_INCLUDE_ROOTS`` is ``('/home/html', '/var/www')``,
then ``{% ssi /home/html/foo.txt %}`` would work, but ``{% ssi /etc/passwd %}``
wouldn't.

APPEND_SLASH
------------

*Default*: ``True``

This setting indicates whether to append trailing slashes to URLs. This is used only if
``CommonMiddleware`` is installed (see Chapter 17). See also ``PREPEND_WWW``.

CACHE_BACKEND
-------------

*Default*: ``'locmem://'``

This is the cache back-end to use (see Chapter 15).

CACHE_MIDDLEWARE_KEY_PREFIX
---------------------------

*Default*: ``''`` (empty string)

This is the cache key prefix that the cache middleware should use (see Chapter 15).

DATABASE_ENGINE
---------------

*Default*: ``''`` (empty string)

This setting indicates which database back-end to use, e.g.
``'postgresql_psycopg2'``, or ``'mysql'``.

DATABASE_HOST
-------------

*Default*: ``''`` (empty string)

This setting indicates which host to use when connecting to the database.
An empty string means ``localhost``. This is not used with SQLite.

If this value starts with a forward slash (``'/'``) and you're using MySQL,
MySQL will connect via a Unix socket to the specified socket::

    DATABASE_HOST = '/var/run/mysql'

If you're using MySQL and this value *doesn't* start with a forward slash, then
this value is assumed to be the host.

DATABASE_NAME
-------------

*Default*: ``''`` (empty string)

This is the name of the database to use. For SQLite, it's the full path to the database
file.

DATABASE_OPTIONS
----------------

*Default*: ``{}`` (empty dictionary)

This is extra parameters to use when connecting to the database. Consult the back-end
module's document for available keywords.

DATABASE_PASSWORD
-----------------

*Default*: ``''`` (empty string)

This setting is the password to use when connecting to the database. It is not used with SQLite.

DATABASE_PORT
-------------

*Default*: ``''`` (empty string)

This is the port to use when connecting to the database. An empty string means the
default port. It is not used with SQLite.

DATABASE_USER
-------------

*Default*: ``''`` (empty string)

This setting is the username to use when connecting to the database. It is not used with SQLite.

DATE_FORMAT
-----------

*Default*: ``'N j, Y'`` (e.g., ``Feb. 4, 2003``)

This is the default formatting to use for date fields on Django admin change-list pages
-- and, possibly, by other parts of the system. It accepts the same format as the
``now`` tag (see Appendix E, Table E-2).

See also ``DATETIME_FORMAT``, ``TIME_FORMAT``, ``YEAR_MONTH_FORMAT``, and
``MONTH_DAY_FORMAT``.

DATETIME_FORMAT
---------------

*Default*: ``'N j, Y, P'`` (e.g., ``Feb. 4, 2003, 4 p.m.``)

This is the default formatting to use for datetime fields on Django admin change-list
pages -- and, possibly, by other parts of the system. It accepts the same format as the
``now`` tag (see Appendix E, Table E-2).

See also ``DATE_FORMAT``, ``DATETIME_FORMAT``, ``TIME_FORMAT``,
``YEAR_MONTH_FORMAT``, and ``MONTH_DAY_FORMAT``.

DEBUG
-----

*Default*: ``False``

This setting is a Boolean that turns debug mode on and off.

If you define custom settings, ``django/views/debug.py`` has a ``HIDDEN_SETTINGS``
regular expression that will hide from the ``DEBUG`` view anything that contains
``'SECRET``, ``PASSWORD``, or ``PROFANITIES'``. This allows untrusted users to
be able to give backtraces without seeing sensitive (or offensive) settings.

Still, note that there are always going to be sections of your debug output that
are inappropriate for public consumption. File paths, configuration options, and
the like all give attackers extra information about your server. Never deploy a
site with ``DEBUG`` turned on.

DEFAULT_CHARSET
---------------

*Default*: ``'utf-8'``

This is the default charset to use for all ``HttpResponse`` objects, if a MIME type isn't
manually specified. It is used with ``DEFAULT_CONTENT_TYPE`` to construct the
``Content-Type`` header. See Appendix G for more about ``HttpResponse`` objects.

DEFAULT_CONTENT_TYPE
--------------------

*Default*: ``'text/html'``

This is the default content type to use for all ``HttpResponse`` objects, if a MIME type
isn't manually specified. It is used with ``DEFAULT_CHARSET`` to construct the
``Content-Type`` header. See Appendix G for more about ``HttpResponse`` objects.

DEFAULT_FROM_EMAIL
------------------

*Default*: ``'webmaster@localhost'``

This is the default email address to use for various automated correspondence from the
site manager(s).

DISALLOWED_USER_AGENTS
----------------------

*Default*: ``()`` (empty tuple)

This is a list of compiled regular expression objects representing User-Agent strings
that are not allowed to visit any page, systemwide. Use this for bad
robots/crawlers. This is used only if ``CommonMiddleware`` is installed (see
Chapter 17).

EMAIL_HOST
----------

*Default*: ``'localhost'``

This is the host to use for sending email. See also ``EMAIL_PORT``.

EMAIL_HOST_PASSWORD
-------------------

*Default*: ``''`` (empty string)

This is the password to use for the SMTP server defined in ``EMAIL_HOST``. This setting is
used in conjunction with ``EMAIL_HOST_USER`` when authenticating to the SMTP
server. If either of these settings is empty, Django won't attempt
authentication.

See also ``EMAIL_HOST_USER``.

EMAIL_HOST_USER
---------------

*Default*: ``''`` (empty string)

This is the username to use for the SMTP server defined in ``EMAIL_HOST``. If it's empty,
Django won't attempt authentication. See also ``EMAIL_HOST_PASSWORD``.

EMAIL_PORT
----------

*Default*: ``25``

This is the port to use for the SMTP server defined in ``EMAIL_HOST``.

EMAIL_SUBJECT_PREFIX
--------------------

*Default*: ``'[Django] '``

This is the subject-line prefix for email messages sent with ``django.core.mail.mail_admins``
or ``django.core.mail.mail_managers``. You'll probably want to include the
trailing space.

FIXTURE_DIRS
-------------

*Default*: ``()`` (empty tuple)

This is a list of locations of the fixture data files, in search order. Note that these
paths should use Unix-style forward slashes, even on Windows. It is used by Django's
testing framework, which is covered online at
http://docs.djangoproject.com/en/dev/topics/testing/.

IGNORABLE_404_ENDS
------------------

*Default*: ``('mail.pl', 'mailform.pl', 'mail.cgi', 'mailform.cgi', 'favicon.ico',
'.php')``

This is a tuple of strings that specify beginnings of URLs that should be
ignored by the 404 e-mailer. (See Chapter 12 for more on the 404 e-mailer.)

No errors will be sent for URLs end with strings from this sequence.

See also ``IGNORABLE_404_STARTS`` and ``SEND_BROKEN_LINK_EMAILS``.

IGNORABLE_404_STARTS
--------------------

*Default*: ``('/cgi-bin/', '/_vti_bin', '/_vti_inf')``

See also ``SEND_BROKEN_LINK_EMAILS`` and ``IGNORABLE_404_ENDS``.

INSTALLED_APPS
--------------

*Default*: ``()`` (empty tuple)

A tuple of strings designating all applications that are enabled in this Django
installation. Each string should be a full Python path to a Python package that
contains a Django application. See Chapter 5 for more about applications.

LANGUAGE_CODE
-------------

*Default*: ``'en-us'``

This is a string representing the language code for this installation. This should be
in standard language format -- for example, U.S. English is ``"en-us"``. See
Chapter 19.

LANGUAGES
---------

*Default*: A tuple of all available languages. This list is continually growing
and any copy included here would inevitably become rapidly out of date. You can
see the current list of translated languages by looking in
``django/conf/global_settings.py``.

The list is a tuple of two-tuples in the format (language code, language name)
-- for example, ``('ja', 'Japanese')``. This specifies which languages are
available for language selection. See Chapter 19 for more on language selection.

Generally, the default value should suffice. Only set this setting if you want
to restrict language selection to a subset of the Django-provided languages.

If you define a custom ``LANGUAGES`` setting, it's OK to mark the languages as
translation strings, but you should *never* import ``django.utils.translation``
from within your settings file, because that module in itself depends on the
settings, and that would cause a circular import.

The solution is to use a "dummy" ``gettext()`` function. Here's a sample
settings file::

    gettext = lambda s: s

    LANGUAGES = (
        ('de', gettext('German')),
        ('en', gettext('English')),
    )

With this arrangement, ``make-messages.py`` will still find and mark these
strings for translation, but the translation won't happen at runtime -- so
you'll have to remember to wrap the languages in the *real* ``gettext()`` in
any code that uses ``LANGUAGES`` at runtime.

MANAGERS
--------

*Default*: ``()`` (empty tuple)

This tuple is in the same format as ``ADMINS`` that specifies who should get
broken-link notifications when ``SEND_BROKEN_LINK_EMAILS=True``.

MEDIA_ROOT
----------

*Default*: ``''`` (empty string)

This is an absolute path to the directory that holds media for this installation (e.g.,
``"/home/media/media.lawrence.com/"``). See also ``MEDIA_URL``.

MEDIA_URL
---------

*Default*: ``''`` (empty string)

This URL handles the media served from ``MEDIA_ROOT`` (e.g.,
``"http://media.lawrence.com"``).

Note that this should have a trailing slash if it has a path component:

* *Correct*: ``"http://www.example.com/static/"``
* *Incorrect*: ``"http://www.example.com/static"``

See Chapter 12 for more on deployment and serving media.

MIDDLEWARE_CLASSES
------------------

*Default*::

    ("django.contrib.sessions.middleware.SessionMiddleware",
     "django.contrib.auth.middleware.AuthenticationMiddleware",
     "django.middleware.common.CommonMiddleware",
     "django.middleware.doc.XViewMiddleware")

This is a tuple of middleware classes to use. See Chapter 17.

MONTH_DAY_FORMAT
----------------

*Default*: ``'F j'``

This is the default formatting to use for date fields on Django admin change-list
pages -- and, possibly, by other parts of the system -- in cases when only the
month and day are displayed. It accepts the same format as the
``now`` tag (see Appendix E, Table E-2).

For example, when a Django admin change-list page is being filtered by a date,
the header for a given day displays the day and month. Different locales have
different formats. For example, U.S. English would have "January 1," whereas
Spanish might have "1 Enero."

See also ``DATE_FORMAT``, ``DATETIME_FORMAT``, ``TIME_FORMAT``, and
``YEAR_MONTH_FORMAT``.

PREPEND_WWW
-----------

*Default*: ``False``

This setting indicates whether to prepend the "www." subdomain to URLs that don't have it.
This is used only if ``CommonMiddleware`` is installed (see the Chapter 17). See also
``APPEND_SLASH``.

ROOT_URLCONF
------------

*Default*: Not defined

This is a string representing the full Python import path to your root URLconf (e.g.,
``"mydjangoapps.urls"``). See Chapter 3.

SECRET_KEY
----------

*Default*: (Generated automatically when you start a project)

This is a secret key for this particular Django installation. It is used to provide a seed in
secret-key hashing algorithms. Set this to a random string -- the longer, the
better. ``django-admin.py startproject`` creates one automatically and most
of the time you won't need to change it

SEND_BROKEN_LINK_EMAILS
-----------------------

*Default*: ``False``

This setting indicates whether to send an email to the ``MANAGERS`` each time somebody visits a
Django-powered page that is 404-ed with a nonempty referer (i.e., a broken
link). This is only used if ``CommonMiddleware`` is installed (see Chapter 17).
See also ``IGNORABLE_404_STARTS`` and ``IGNORABLE_404_ENDS``.

SERIALIZATION_MODULES
---------------------

*Default*: Not defined.

Serialization is a feature still under heavy development. Refer to the online
documentation at http://docs.djangoproject.com/en/dev/topics/serialization/
for more information.

SERVER_EMAIL
------------

*Default*: ``'root@localhost'``

This is the email address that error messages come from, such as those sent to
``ADMINS`` and ``MANAGERS``.

SESSION_COOKIE_AGE
------------------

*Default*: ``1209600`` (two weeks, in seconds)

This is the age of session cookies, in seconds. See Chapter 14.

SESSION_COOKIE_DOMAIN
---------------------

*Default*: ``None``

This is the domain to use for session cookies. Set this to a string such as
``".lawrence.com"`` for cross-domain cookies, or use ``None`` for a standard
domain cookie. See Chapter 14.

SESSION_COOKIE_NAME
-------------------

*Default*: ``'sessionid'``

This is the name of the cookie to use for sessions; it can be whatever you want.
See Chapter 14.

SESSION_COOKIE_SECURE
---------------------

*Default*: ``False``

This setting indicates whether to use a secure cookie for the session cookie.
If this is set to ``True``, the cookie will be marked as "secure,"
which means browsers may ensure that the cookie is only sent under an HTTPS connection.
See Chapter 14.

SESSION_EXPIRE_AT_BROWSER_CLOSE
-------------------------------

*Default*: ``False``

This setting indicates whether to expire the session when the user closes
his browser. See Chapter 14.

SESSION_SAVE_EVERY_REQUEST
--------------------------

*Default*: ``False``

This setting indicates whether to save the session data on every request. See Chapter 14.

SITE_ID
-------

*Default*: Not defined

This is the ID, as an integer, of the current site in the ``django_site`` database
table. It is used so that application data can hook into specific site(s)
and a single database can manage content for multiple sites. See Chapter 16.

TEMPLATE_CONTEXT_PROCESSORS
---------------------------

*Default*::

    ("django.core.context_processors.auth",
    "django.core.context_processors.debug",
    "django.core.context_processors.i18n",
    "django.core.context_processors.media")

This is a tuple of callables that are used to populate the context in ``RequestContext``.
These callables take a request object as their argument and return a dictionary
of items to be merged into the context. See Chapter 9.

TEMPLATE_DEBUG
--------------

*Default*: ``False``

This Boolean turns template debug mode on and off. If it is ``True``, the fancy
error page will display a detailed report for any ``TemplateSyntaxError``. This
report contains the relevant snippet of the template, with the appropriate line
highlighted.

Note that Django only displays fancy error pages if ``DEBUG`` is ``True``, so
you'll want to set that to take advantage of this setting.

See also ``DEBUG``.

TEMPLATE_DIRS
-------------

*Default*: ``()`` (empty tuple)

This is a list of locations of the template source files, in search order. Note that these
paths should use Unix-style forward slashes, even on Windows. See Chapters 4 and
9.

TEMPLATE_LOADERS
----------------

*Default*::

    ('django.template.loaders.filesystem.load_template_source',
    'django.template.loaders.app_directories.load_template_source')

This is a tuple of callables (as strings) that know how to import templates from
various sources. See Chapter 9.

TEMPLATE_STRING_IF_INVALID
--------------------------

*Default*: ``''`` (Empty string)

This is output, as a string, that the template system should use for invalid (e.g.,
misspelled) variables. See Chapter 9.

TEST_RUNNER
-----------

*Default*: ``'django.test.simple.run_tests'``

This is the name of the method to use for starting the test suite. It is used by Django's
testing framework, which is covered online at
http://docs.djangoproject.com/en/dev/topics/testing/.

TEST_DATABASE_NAME
------------------

*Default*: ``None``

This is the name of database to use when running the test suite. If a value of ``None``
is specified, the test database will use the name ``'test_' +
settings.DATABASE_NAME``. See the documentation for Django's testing framework,
which is covered online at http://docs.djangoproject.com/en/dev/topics/testing/.

TIME_FORMAT
-----------

*Default*: ``'P'`` (e.g., ``4 p.m.``)

This is the default formatting to use for time fields on Django admin change-list pages
-- and, possibly, by other parts of the system. It accepts the same format as the
``now`` tag (see Appendix E, Table E-2).

See also ``DATE_FORMAT``, ``DATETIME_FORMAT``, ``TIME_FORMAT``,
``YEAR_MONTH_FORMAT``, and ``MONTH_DAY_FORMAT``.

TIME_ZONE
---------

*Default*: ``'America/Chicago'``

This is a string representing the time zone for this installation. Time zones are in the
Unix-standard ``zic`` format. One relatively complete list of time zone strings
can be found at
http://www.postgresql.org/docs/8.1/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE.

This is the time zone to which Django will convert all dates/times --
not necessarily the time zone of the server. For example, one server may serve
multiple Django-powered sites, each with a separate time-zone setting.

Normally, Django sets the ``os.environ['TZ']`` variable to the time zone you
specify in the ``TIME_ZONE`` setting. Thus, all your views and models will
automatically operate in the correct time zone. However, if you're using the
manually configuring settings (described above in the section titled "Using
Settings Without Setting DJANGO_SETTINGS_MODULE"), Django will *not* touch the
``TZ`` environment variable, and it will be up to you to ensure your processes
are running in the correct environment.

.. note::
    Django cannot reliably use alternate time zones in a Windows environment. If
    you're running Django on Windows, this variable must be set to match the
    system time zone.

URL_VALIDATOR_USER_AGENT
------------------------

*Default*: ``Django/<version> (http://www.djangoproject.com/)``

This is the string to use as the ``User-Agent`` header when checking to see if URLs
exist (see the ``verify_exists`` option on ``URLField``; see Appendix A).

USE_ETAGS
---------

*Default*: ``False``

This Boolean specifies whether to output the ETag header. It saves
bandwidth but slows down performance. This is only used if ``CommonMiddleware``
is installed (see Chapter 17).

USE_I18N
--------

*Default*: ``True``

This Boolean specifies whether Django's internationalization system (see
Chapter 19) should be enabled. It provides an easy way to turn off internationalization, for
performance. If this is set to ``False``, Django will make some optimizations so
as not to load the internationalization machinery.

YEAR_MONTH_FORMAT
-----------------

*Default*: ``'F Y'``

This is the default formatting to use for date fields on Django admin change-list pages
-- and, possibly, by other parts of the system -- in cases when only the year
and month are displayed. It accepts the same format as the ``now`` tag (see
Appendix E).

For example, when a Django admin change-list page is being filtered by a date
drill-down, the header for a given month displays the month and the year.
Different locales have different formats. For example, U.S. English would use
"January 2006," whereas another locale might use "2006/January."

See also ``DATE_FORMAT``, ``DATETIME_FORMAT``, ``TIME_FORMAT``, and
``MONTH_DAY_FORMAT``.


================================================
FILE: Python/DjangoBook/appendixE.rst
================================================
==============================================
Appendix E: Built-in Template Tags and Filters
==============================================

Chapter 4 lists a number of the most useful built-in template tags and
filters. However, Django ships with many more built-in tags and filters.
This appendix covers them.

Built-in Tag Reference
======================

autoescape
----------

Control the current auto-escaping behavior. This tag takes either ``on`` or
``off`` as an argument and that determines whether auto-escaping is in effect
inside the block.

When auto-escaping is in effect, all variable content has HTML escaping applied
to it before placing the result into the output (but after any filters have
been applied). This is equivalent to manually applying the ``escape`` filter
to each variable.

The only exceptions are variables that are already marked as "safe" from
escaping, either by the code that populated the variable, or because it has had
the ``safe`` or ``escape`` filters applied.

block
-----

Define a block that can be overridden by child templates. See
Chapter 4 for more information on template inheritance.

comment
-------

Ignore everything between ``{% comment %}`` and ``{% endcomment %}``

cycle
-----

Cycle among the given strings or variables each time this tag is encountered.

Within a loop, cycles among the given strings each time through the
loop::

    {% for o in some_list %}
        <tr class="{% cycle 'row1' 'row2' %}">
            ...
        </tr>
    {% endfor %}

You can use variables, too. For example, if you have two template variables,
``rowvalue1`` and ``rowvalue2``, you can cycle between their values like this::

    {% for o in some_list %}
        <tr class="{% cycle rowvalue1 rowvalue2 %}">
            ...
        </tr>
    {% endfor %}

Yes, you can mix variables and strings::

    {% for o in some_list %}
        <tr class="{% cycle 'row1' rowvalue2 'row3' %}">
            ...
        </tr>
    {% endfor %}

In some cases you might want to refer to the next value of a cycle from
outside of a loop. To do this, just give the ``{% cycle %}`` tag a name, using
"as", like this::

    {% cycle 'row1' 'row2' as rowcolors %}

From then on, you can insert the current value of the cycle wherever you'd like
in your template::

    <tr class="{% cycle rowcolors %}">...</tr>
    <tr class="{% cycle rowcolors %}">...</tr>

You can use any number of values in a ``{% cycle %}`` tag, separated by spaces.
Values enclosed in single (``'``) or double quotes (``"``) are treated as
string literals, while values without quotes are treated as template variables.

For backwards compatibility, the ``{% cycle %}`` tag supports the much inferior
old syntax from previous Django versions. You shouldn't use this in any new
projects, but for the sake of the people who are still using it, here's what it
looks like::

    {% cycle row1,row2,row3 %}

In this syntax, each value gets interpreted as a literal string, and there's no
way to specify variable values. Or literal commas. Or spaces. Did we mention
you shouldn't use this syntax in any new projects?

debug
-----

Output a whole load of debugging information, including the current context and
imported modules.

extends
-------

Signal that this template extends a parent template.

This tag can be used in two ways:

* ``{% extends "base.html" %}`` (with quotes) uses the literal value
  ``"base.html"`` as the name of the parent template to extend.

* ``{% extends variable %}`` uses the value of ``variable``. If the variable
  evaluates to a string, Django will use that string as the name of the
  parent template. If the variable evaluates to a ``Template`` object,
  Django will use that object as the parent template.

See Chapter 4 for more information on template inheritance.

filter
------

Filter the contents of the variable through variable filters.

Filters can also be piped through each other, and they can have arguments --
just like in variable syntax.

Sample usage::

    {% filter force_escape|lower %}
        This text will be HTML-escaped, and will appear in all lowercase.
    {% endfilter %}

firstof
-------

Outputs the first variable passed that is not False.  Outputs nothing if all the
passed variables are False.

Sample usage::

    {% firstof var1 var2 var3 %}

This is equivalent to::

    {% if var1 %}
        {{ var1 }}
    {% else %}{% if var2 %}
        {{ var2 }}
    {% else %}{% if var3 %}
        {{ var3 }}
    {% endif %}{% endif %}{% endif %}

You can also use a literal string as a fallback value in case all
passed variables are False::

    {% firstof var1 var2 var3 "fallback value" %}

for
---

Loop over each item in an array.  For example, to display a list of athletes
provided in ``athlete_list``::

    <ul>
    {% for athlete in athlete_list %}
        <li>{{ athlete.name }}</li>
    {% endfor %}
    </ul>

You can loop over a list in reverse by using ``{% for obj in list reversed %}``.

If you need to loop over a list of lists, you can unpack the values
in each sub-list into individual variables. For example, if your context
contains a list of (x,y) coordinates called ``points``, you could use the
following to output the list of points::

    {% for x, y in points %}
        There is a point at {{ x }},{{ y }}
    {% endfor %}

This can also be useful if you need to access the items in a dictionary.
For example, if your context contained a dictionary ``data``, the following
would display the keys and values of the dictionary::

    {% for key, value in data.items %}
        {{ key }}: {{ value }}
    {% endfor %}

The ``for`` loop sets a number of variables available within the loop (see
Table E-1).

.. table:: Table E-1. Variables Available Inside {% for %} Loops

    ==========================  ================================================
    Variable                    Description
    ==========================  ================================================
    ``forloop.counter``         The current iteration of the loop (1-indexed)
    ``forloop.counter0``        The current iteration of the loop (0-indexed)
    ``forloop.revcounter``      The number of iterations from the end of the
                                loop (1-indexed)
    ``forloop.revcounter0``     The number of iterations from the end of the
                                loop (0-indexed)
    ``forloop.first``           True if this is the first time through the loop
    ``forloop.last``            True if this is the last time through the loop
    ``forloop.parentloop``      For nested loops, this is the loop "above" the
                                current one
    ==========================  ================================================

The ``for`` tag can take an optional ``{% empty %}`` clause that will be
displayed if the given array is empty or could not be found::

    <ul>
    {% for athlete in athlete_list %}
        <li>{{ athlete.name }}</li>
    {% empty %}
        <li>Sorry, no athlete in this list!</li>
    {% endfor %}
    <ul>

The above is equivalent to -- but shorter, cleaner, and possibly faster
than -- the following::

    <ul>
      {% if athlete_list %}
        {% for athlete in athlete_list %}
          <li>{{ athlete.name }}</li>
        {% endfor %}
      {% else %}
        <li>Sorry, no athletes in this list.</li>
      {% endif %}
    </ul>

if
--

The ``{% if %}`` tag evaluates a variable, and if that variable is "true" (i.e.
exists, is not empty, and is not a false boolean value) the contents of the
block are output::

    {% if athlete_list %}
        Number of athletes: {{ athlete_list|length }}
    {% else %}
        No athletes.
    {% endif %}

In the above, if ``athlete_list`` is not empty, the number of athletes will be
displayed by the ``{{ athlete_list|length }}`` variable.

As you can see, the ``if`` tag can take an optional ``{% else %}`` clause that
will be displayed if the test fails.

``if`` tags may use ``and``, ``or`` or ``not`` to test a number of variables or
to negate a given variable::

    {% if athlete_list and coach_list %}
        Both athletes and coaches are available.
    {% endif %}

    {% if not athlete_list %}
        There are no athletes.
    {% endif %}

    {% if athlete_list or coach_list %}
        There are some athletes or some coaches.
    {% endif %}

    {% if not athlete_list or coach_list %}
        There are no athletes or there are some coaches (OK, so
        writing English translations of boolean logic sounds
        stupid; it's not our fault).
    {% endif %}

    {% if athlete_list and not coach_list %}
        There are some athletes and absolutely no coaches.
    {% endif %}

``if`` tags don't allow ``and`` and ``or`` clauses within the same tag, because
the order of logic would be ambiguous. For example, this is invalid::

    {% if athlete_list and coach_list or cheerleader_list %}

If you need to combine ``and`` and ``or`` to do advanced logic, just use nested
``if`` tags. For example::

    {% if athlete_list %}
        {% if coach_list or cheerleader_list %}
            We have athletes, and either coaches or cheerleaders!
        {% endif %}
    {% endif %}

Multiple uses of the same logical operator are fine, as long as you use the
same operator. For example, this is valid::

    {% if athlete_list or coach_list or parent_list or teacher_list %}

ifchanged
---------

Check if a value has changed from the last iteration of a loop.

The ``ifchanged`` tag is used within a loop. It has two possible uses.

1. Checks its own rendered contents against its previous state and only
   displays the content if it has changed. For example, this displays a list of
   days, only displaying the month if it changes::

        <h1>Archive for {{ year }}</h1>

        {% for date in days %}
            {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %}
            <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a>
        {% endfor %}

2. If given a variable, check whether that variable has changed. For
   example, the following shows the date every time it changes, but
   only shows the hour if both the hour and the date has changed::

        {% for date in days %}
            {% ifchanged date.date %} {{ date.date }} {% endifchanged %}
            {% ifchanged date.hour date.date %}
                {{ date.hour }}
            {% endifchanged %}
        {% endfor %}

The ``ifchanged`` tag can also take an optional ``{% else %}`` clause that
will be displayed if the value has not changed::

        {% for match in matches %}
            <div style="background-color:
                {% ifchanged match.ballot_id %}
                    {% cycle red,blue %}
                {% else %}
                    grey
                {% endifchanged %}
            ">{{ match }}</div>
        {% endfor %}

ifequal
-------

Output the contents of the block if the two arguments equal each other.

Example::

    {% ifequal user.id comment.user_id %}
        ...
    {% endifequal %}

As in the ``{% if %}`` tag, an ``{% else %}`` clause is optional.

The arguments can be hard-coded strings, so the following is valid::

    {% ifequal user.username "adrian" %}
        ...
    {% endifequal %}

It is only possible to compare an argument to template variables or strings.
You cannot check for equality with Python objects such as ``True`` or
``False``.  If you need to test if something is true or false, use the ``if``
tag instead.

ifnotequal
----------

Just like ``ifequal``, except it tests that the two arguments are not equal.

include
-------

Loads a template and renders it with the current context. This is a way of
"including" other templates within a template.

The template name can either be a variable or a hard-coded (quoted) string,
in either single or double quotes.

This example includes the contents of the template ``"foo/bar.html"``::

    {% include "foo/bar.html" %}

This example includes the contents of the template whose name is contained in
the variable ``template_name``::

    {% include template_name %}

An included template is rendered with the context of the template that's
including it. This example produces the output ``"Hello, John"``:

* Context: variable ``person`` is set to ``"john"``.
* Template::

    {% include "name_snippet.html" %}

* The ``name_snippet.html`` template::

    Hello, {{ person }}

See also: ``{% ssi %}``.

load
----

Load a custom template tag set. See Chapter 9 for more information on custom
template libraries.

now
---

Display the date, formatted according to the given string.

Uses the same format as PHP's ``date()`` function (http://php.net/date)
with some custom extensions.

Table E-2 shows the available format strings.

.. table:: Table E-2. Available Date Format Strings

    ================  ========================================  =====================
    Format character  Description                               Example output
    ================  ========================================  =====================
    a                 ``'a.m.'`` or ``'p.m.'`` (Note that       ``'a.m.'``
                      this is slightly different than PHP's
                      output, because this includes periods
                      to match Associated Press style.)
    A                 ``'AM'`` or ``'PM'``.                     ``'AM'``
    b                 Month, textual, 3 letters, lowercase.     ``'jan'``
    B                 Not implemented.
    d                 Day of the month, 2 digits with           ``'01'`` to ``'31'``
                      leading zeros.
    D                 Day of the week, textual, 3 letters.      ``'Fri'``
    f                 Time, in 12-hour hours and minutes,       ``'1'``, ``'1:30'``
                      with minutes left off if they're zero.
                      Proprietary extension.
    F                 Month, textual, long.                     ``'January'``
    g                 Hour, 12-hour format without leading      ``'1'`` to ``'12'``
                      zeros.
    G                 Hour, 24-hour format without leading      ``'0'`` to ``'23'``
                      zeros.
    h                 Hour, 12-hour format.                     ``'01'`` to ``'12'``
    H                 Hour, 24-hour format.                     ``'00'`` to ``'23'``
    i                 Minutes.                                  ``'00'`` to ``'59'``
    I                 Not implemented.
    j                 Day of the month without leading          ``'1'`` to ``'31'``
                      zeros.
    l                 Day of the week, textual, long.           ``'Friday'``
    L                 Boolean for whether it's a leap year.     ``True`` or ``False``
    m                 Month, 2 digits with leading zeros.       ``'01'`` to ``'12'``
    M                 Month, textual, 3 letters.                ``'Jan'``
    n                 Month without leading zeros.              ``'1'`` to ``'12'``
    N                 Month abbreviation in Associated Press    ``'Jan.'``, ``'Feb.'``, ``'March'``, ``'May'``
                      style. Proprietary extension.
    O                 Difference to Greenwich time in hours.    ``'+0200'``
    P                 Time, in 12-hour hours, minutes and       ``'1 a.m.'``, ``'1:30 p.m.'``, ``'midnight'``, ``'noon'``, ``'12:30 p.m.'``
                      'a.m.'/'p.m.', with minutes left off
                      if they're zero and the special-case
                      strings 'midnight' and 'noon' if
                      appropriate. Proprietary extension.
    r                 RFC 2822 formatted date.                  ``'Thu, 21 Dec 2000 16:01:07 +0200'``
    s                 Seconds, 2 digits with leading zeros.     ``'00'`` to ``'59'``
    S                 English ordinal suffix for day of the     ``'st'``, ``'nd'``, ``'rd'`` or ``'th'``
                      month, 2 characters.
    t                 Number of days in the given month.        ``28`` to ``31``
    T                 Time zone of this machine.                ``'EST'``, ``'MDT'``
    U                 Not implemented.
    w                 Day of the week, digits without           ``'0'`` (Sunday) to ``'6'`` (Saturday)
                      leading zeros.
    W                 ISO-8601 week number of year, with        ``1``, ``53``
                      weeks starting on Monday.
    y                 Year, 2 digits.                           ``'99'``
    Y                 Year, 4 digits.                           ``'1999'``
    z                 Day of the year.                          ``0`` to ``365``
    Z                 Time zone offset in seconds. The          ``-43200`` to ``43200``
                      offset for timezones west of UTC is
                      always negative, and for those east of
                      UTC is always positive.
    ================  ========================================  =====================

Example::

    It is {% now "jS F Y H:i" %}

Note that you can backslash-escape a format string if you want to use the
"raw" value. In this example, "f" is backslash-escaped, because otherwise
"f" is a format string that displays the time. The "o" doesn't need to be
escaped, because it's not a format character::

    It is the {% now "jS o\f F" %}

This would display as "It is the 4th of September".

regroup
-------

Regroup a list of alike objects by a common attribute.

This complex tag is best illustrated by use of an example: say that ``people``
is a list of people represented by dictionaries with ``first_name``,
``last_name``, and ``gender`` keys:

.. code-block:: python

    people = [
        {'first_name': 'George', 'last_name': 'Bush', 'gender': 'Male'},
        {'first_name': 'Bill', 'last_name': 'Clinton', 'gender': 'Male'},
        {'first_name': 'Margaret', 'last_name': 'Thatcher', 'gender': 'Female'},
        {'first_name': 'Condoleezza', 'last_name': 'Rice', 'gender': 'Female'},
        {'first_name': 'Pat', 'last_name': 'Smith', 'gender': 'Unknown'},
    ]

...and you'd like to display a hierarchical list that is ordered by gender,
like this::

    * Male:
        * George Bush
        * Bill Clinton
    * Female:
        * Margaret Thatcher
        * Condoleezza Rice
    * Unknown:
        * Pat Smith

You can use the ``{% regroup %}`` tag to group the list of people by gender.
The following snippet of template code would accomplish this::

    {% regroup people by gender as gender_list %}

    <ul>
    {% for gender in gender_list %}
        <li>{{ gender.grouper }}
        <ul>
            {% for item in gender.list %}
            <li>{{ item.first_name }} {{ item.last_name }}</li>
            {% endfor %}
        </ul>
        </li>
    {% endfor %}
    </ul>

Let's walk through this example. ``{% regroup %}`` takes three arguments: the
list you want to regroup, the attribute to group by, and the name of the
resulting list. Here, we're regrouping the ``people`` list by the ``gender``
attribute and calling the result ``gender_list``.

``{% regroup %}`` produces a list (in this case, ``gender_list``) of
**group objects**. Each group object has two attributes:

* ``grouper`` -- the item that was grouped by (e.g., the string "Male" or
  "Female").
* ``list`` -- a list of all items in this group (e.g., a list of all people
  with gender='Male').

Note that ``{% regroup %}`` does not order its input! Our example relies on
the fact that the ``people`` list was ordered by ``gender`` in the first place.
If the ``people`` list did *not* order its members by ``gender``, the regrouping
would naively display more than one group for a single gender. For example,
say the ``people`` list was set to this (note that the males are not grouped
together):

.. code-block:: python

    people = [
        {'first_name': 'Bill', 'last_name': 'Clinton', 'gender': 'Male'},
        {'first_name': 'Pat', 'last_name': 'Smith', 'gender': 'Unknown'},
        {'first_name': 'Margaret', 'last_name': 'Thatcher', 'gender': 'Female'},
        {'first_name': 'George', 'last_name': 'Bush', 'gender': 'Male'},
        {'first_name': 'Condoleezza', 'last_name': 'Rice', 'gender': 'Female'},
    ]

With this input for ``people``, the example ``{% regroup %}`` template code
above would result in the following output::

    * Male:
        * Bill Clinton
    * Unknown:
        * Pat Smith
    * Female:
        * Margaret Thatcher
    * Male:
        * George Bush
    * Female:
        * Condoleezza Rice

The easiest solution to this gotcha is to make sure in your view code that the
data is ordered according to how you want to display it.

Another solution is to sort the data in the template using the ``dictsort``
filter, if your data is in a list of dictionaries::

    {% regroup people|dictsort:"gender" by gender as gender_list %}

spaceless
---------

Removes whitespace between HTML tags. This includes tab
characters and newlines.

Example usage::

    {% spaceless %}
        <p>
            <a href="foo/">Foo</a>
        </p>
    {% endspaceless %}

This example would return this HTML::

    <p><a href="foo/">Foo</a></p>

Only space between *tags* is removed -- not space between tags and text. In
this example, the space around ``Hello`` won't be stripped::

    {% spaceless %}
        <strong>
            Hello
        </strong>
    {% endspaceless %}

ssi
---

Output the contents of a given file into the page.

Like a simple "include" tag, ``{% ssi %}`` includes the contents of another
file -- which must be specified using an absolute path -- in the current
page::

    {% ssi /home/html/ljworld.com/includes/right_generic.html %}

If the optional "parsed" parameter is given, the contents of the included
file are evaluated as template code, within the current context::

    {% ssi /home/html/ljworld.com/includes/right_generic.html parsed %}

Note that if you use ``{% ssi %}``, you'll need to define
``ALLOWED_INCLUDE_ROOTS`` in your Django settings, as a security measure.

See also: ``{% include %}``.

templatetag
-----------

Output one of the syntax characters used to compose template tags.

Since the template system has no concept of "escaping", to display one of the
bits used in template tags, you must use the ``{% templatetag %}`` tag.

See Table E-3 for the available arguments.

.. table:: Table E-3. Available Arguments for templatetag Filter

    ==================  =======
    Argument            Outputs
    ==================  =======
    ``openblock``       ``{%``
    ``closeblock``      ``%}``
    ``openvariable``    ``{{``
    ``closevariable``   ``}}``
    ``openbrace``       ``{``
    ``closebrace``      ``}``
    ``opencomment``     ``{#``
    ``closecomment``    ``#}``
    ==================  =======

url
---

Returns an absolute URL (i.e., a URL without the domain name) matching a given
view function and optional parameters. This is a way to output links without
violating the DRY principle by having to hard-code URLs in your templates::

    {% url path.to.some_view arg1,arg2,name1=value1 %}

The first argument is a path to a view function in the format
``package.package.module.function``. Additional arguments are optional and
should be comma-separated values that will be used as positional and keyword
arguments in the URL. All arguments required by the URLconf should be present.

For example, suppose you have a view, ``app_views.client``, whose URLconf
takes a client ID (here, ``client()`` is a method inside the views file
``app_views.py``). The URLconf line might look like this::

    ('^client/(\d+)/$', 'app_views.client')

If this app's URLconf is included into the project's URLconf under a path
such as this::

    ('^clients/', include('project_name.app_name.urls'))

...then, in a template, you can create a link to this view like this::

    {% url app_views.client client.id %}

The template tag will output the string ``/clients/client/123/``.

widthratio
----------

For creating bar charts and such, this tag calculates the ratio of a given value
to a maximum value, and then applies that ratio to a constant.

For example::

    <img src="bar.gif" height="10" width="{% widthratio this_value max_value 100 %}" />

Above, if ``this_value`` is 175 and ``max_value`` is 200, the image in the
above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5
which is rounded up to 88).

with
----

Caches a complex variable under a simpler name. This is useful when accessing
an "expensive" method (e.g., one that hits the database) multiple times.

For example::

    {% with business.employees.count as total %}
        {{ total }} employee{{ total|pluralize }}
    {% endwith %}

The populated variable (in the example above, ``total``) is only available
between the ``{% with %}`` and ``{% endwith %}`` tags.

Built-in Filter Reference
=========================

add
---

Adds the argument to the value.

For example::

    {{ value|add:"2" }}

If ``value`` is ``4``, then the output will be ``6``.

addslashes
----------

Adds slashes before quotes. Useful for escaping strings in CSV, for example.

capfirst
--------

Capitalizes the first character of the value.

center
------

Centers the value in a field of a given width.

cut
---

Removes all values of arg from the given string.

For example::

    {{ value|cut:" "}}

If ``value`` is ``"String with spaces"``, the output will be ``"Stringwithspaces"``.

date
----

Formats a date according to the given format (same as the ``{% now %}`` tag).

For example::

    {{ value|date:"D d M Y" }}

If ``value`` is a ``datetime`` object (e.g., the result of
``datetime.datetime.now()``), the output will be the string
``'Wed 09 Jan 2008'``.

When used without a format string::

    {{ value|date }}

...the formatting string defined in the ``DATE_FORMAT`` setting will be
used.

default
-------

If value evaluates to ``False``, use given default. Otherwise, use the value.

For example::

    {{ value|default:"nothing" }}

If ``value`` is ``""`` (the empty string), the output will be ``nothing``.

default_if_none
---------------

If (and only if) value is ``None``, use given default. Otherwise, use the
value.

Note that if an empty string is given, the default value will *not* be used.
Use the ``default`` filter if you want to fallback for empty strings.

For example::

    {{ value|default_if_none:"nothing" }}

If ``value`` is ``None``, the output will be the string ``"nothing"``.

dictsort
--------

Takes a list of dictionaries and returns that list sorted by the key given in
the argument.

For example::

    {{ value|dictsort:"name" }}

If ``value`` is::

    [
        {'name': 'zed', 'age': 19},
        {'name': 'amy', 'age': 22},
        {'name': 'joe', 'age': 31},
    ]

then the output would be::

    [
        {'name': 'amy', 'age': 22},
        {'name': 'joe', 'age': 31},
        {'name': 'zed', 'age': 19},
    ]

dictsortreversed
----------------

Takes a list of dictionaries and returns that list sorted in reverse order by
the key given in the argument. This works exactly the same as the above filter,
but the returned value will be in reverse order.

divisibleby
-----------

Returns ``True`` if the value is divisible by the argument.

For example::

    {{ value|divisibleby:"3" }}

If ``value`` is ``21``, the output would be ``True``.

escape
------

Escapes a string's HTML. Specifically, it makes these replacements:

* ``<`` is converted to ``&lt;``
* ``>`` is converted to ``&gt;``
* ``'`` (single quote) is converted to ``&#39;``
* ``"`` (double quote) is converted to ``&quot;``
* ``&`` is converted to ``&amp;``

The escaping is only applied when the string is output, so it does not matter
where in a chained sequence of filters you put ``escape``: it will always be
applied as though it were the last filter. If you want escaping to be applied
immediately, use the ``force_escape`` filter.

Applying ``escape`` to a variable that would normally have auto-escaping
applied to the result will only result in one round of escaping being done. So
it is safe to use this function even in auto-escaping environments. If you want
multiple escaping passes to be applied, use the ``force_escape`` filter.

escapejs
--------

Escapes characters for use in JavaScript strings. This does *not* make the
string safe for use in HTML, but does protect you from syntax errors when using
templates to generate JavaScript/JSON.

filesizeformat
--------------

Format the value like a 'human-readable' file size (i.e. ``'13 KB'``,
``'4.1 MB'``, ``'102 bytes'``, etc).

For example::

    {{ value|filesizeformat }}

If ``value`` is 123456789, the output would be ``117.7 MB``.

first
-----

Returns the first item in a list.

For example::

    {{ value|first }}

If ``value`` is the list ``['a', 'b', 'c']``, the output will be ``'a'``.

fix_ampersands
--------------

Replaces ampersands with ``&amp;`` entities.

For example::

    {{ value|fix_ampersands }}

If ``value`` is ``Tom & Jerry``, the output will be ``Tom &amp; Jerry``.

floatformat
-----------

When used without an argument, rounds a floating-point number to one decimal
place -- but only if there's a decimal part to be displayed. For example:

============  ===========================  ========
``value``     Template                     Output
============  ===========================  ========
``34.23234``  ``{{ value|floatformat }}``  ``34.2``
``34.00000``  ``{{ value|floatformat }}``  ``34``
``34.26000``  ``{{ value|floatformat }}``  ``34.3``
============  ===========================  ========

If used with a numeric integer argument, ``floatformat`` rounds a number to
that many decimal places. For example:

============  =============================  ==========
``value``     Template                       Output
============  =============================  ==========
``34.23234``  ``{{ value|floatformat:3 }}``  ``34.232``
``34.00000``  ``{{ value|floatformat:3 }}``  ``34.000``
``34.26000``  ``{{ value|floatformat:3 }}``  ``34.260``
============  =============================  ==========

If the argument passed to ``floatformat`` is negative, it will round a number
to that many decimal places -- but only if there's a decimal part to be
displayed. For example:

============  ================================  ==========
``value``     Template                          Output
============  ================================  ==========
``34.23234``  ``{{ value|floatformat:"-3" }}``  ``34.232``
``34.00000``  ``{{ value|floatformat:"-3" }}``  ``34``
``34.26000``  ``{{ value|floatformat:"-3" }}``  ``34.260``
============  ================================  ==========

Using ``floatformat`` with no argument is equivalent to using ``floatformat``
with an argument of ``-1``.

force_escape
------------

Applies HTML escaping to a string (see the ``escape`` filter for details).
This filter is applied *immediately* and returns a new, escaped string. This
is useful in the rare cases where you need multiple escaping or want to apply
other filters to the escaped results. Normally, you want to use the ``escape``
filter.

get_digit
---------

Given a whole number, returns the requested digit, where 1 is the right-most
digit, 2 is the second-right-most digit, etc. Returns the original value for
invalid input (if input or argument is not an integer, or if argument is less
than 1). Otherwise, output is always an integer.

For example::

    {{ value|get_digit:"2" }}

If ``value`` is ``123456789``, the output will be ``8``.

iriencode
---------

Converts an IRI (Internationalized Resource Identifier) to a string that is
suitable for including in a URL. This is necessary if you're trying to use
strings containing non-ASCII characters in a URL.

It's safe to use this filter on a string that has already gone through the
``urlencode`` filter.

join
----

Joins a list with a string, like Python's ``str.join(list)``

For example::

    {{ value|join:" // " }}

If ``value`` is the list ``['a', 'b', 'c']``, the output will be the string
``"a // b // c"``.

last
----

Returns the last item in a list.

For example::

    {{ value|last }}

If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output will be the string
``"d"``.

length
------

Returns the length of the value. This works for both strings and lists.

For example::

    {{ value|length }}

If ``value`` is ``['a', 'b', 'c', 'd']``, the output will be ``4``.

length_is
---------

Returns ``True`` if the value's length is the argument, or ``False`` otherwise.

For example::

    {{ value|length_is:"4" }}

If ``value`` is ``['a', 'b', 'c', 'd']``, the output will be ``True``.

linebreaks
----------

Replaces line breaks in plain text with appropriate HTML; a single
newline becomes an HTML line break (``<br />``) and a new line
followed by a blank line becomes a paragraph break (``</p>``).

For example::

    {{ value|linebreaks }}

If ``value`` is ``Joel\nis a slug``, the output will be ``<p>Joel<br />is a
slug</p>``.

linebreaksbr
~~~~~~~~~~~~

Converts all newlines in a piece of plain text to HTML line breaks
(``<br />``).

linenumbers
-----------

Displays text with line numbers.

ljust
-----

Left-aligns the value in a field of a given width.

**Argument:** field size

lower
-----

Converts a string into all lowercase.

For example::

    {{ value|lower }}

If ``value`` is ``Still MAD At Yoko``, the output will be ``still mad at yoko``.

make_list
---------

Returns the value turned into a list. For an integer, it's a list of
digits. For a string, it's a list of characters.

For example::

    {{ value|make_list }}

If ``value`` is the string ``"Joel"``, the output would be the list
``[u'J', u'o', u'e', u'l']``. If ``value`` is ``123``, the output will be the
list ``[1, 2, 3]``.

phone2numeric
-------------

Converts a phone number (possibly containing letters) to its numerical
equivalent. For example, ``'800-COLLECT'`` will be converted to
``'800-2655328'``.

The input doesn't have to be a valid phone number. This will happily convert
any string.

pluralize
---------

Returns a plural suffix if the value is not 1. By default, this suffix is ``'s'``.

Example::

    You have {{ num_messages }} message{{ num_messages|pluralize }}.

For words that require a suffix other than ``'s'``, you can provide an alternate
suffix as a parameter to the filter.

Example::

    You have {{ num_walruses }} walrus{{ num_walrus|pluralize:"es" }}.

For words that don't pluralize by simple suffix, you can specify both a
singular and plural suffix, separated by a comma.

Example::

    You have {{ num_cherries }} cherr{{ num_cherries|pluralize:"y,ies" }}.

pprint
------

A wrapper around the Python standard library's ``pprint.pprint`` function --
for debugging, really.

random
------

Returns a random item from the given list.

For example::

    {{ value|random }}

If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output could be ``"b"``.

removetags
----------

Removes a space-separated list of [X]HTML tags from the output.

For example::

    {{ value|removetags:"b span"|safe }}

If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"`` the
output will be ``"Joel <button>is</button> a slug"``.

rjust
-----

Right-aligns the value in a field of a given width.

**Argument:** field size

safe
----

Marks a string as not requiring further HTML escaping prior to output. When
autoescaping is off, this filter has no effect.

safeseq
-------

Applies the ``safe`` filter to each element of a sequence.  Useful in
conjunction with other filters that operate on sequences, such as
``join``.  For example::

    {{ some_list|safeseq|join:", " }}

You couldn't use the ``safe`` filter directly in this case, as it would
first convert the variable into a string, rather than working with the
individual elements of the sequence.

slice
-----

Returns a slice of the list.

Uses the same syntax as Python's list slicing. See
http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice
for an introduction.

Example::

    {{ some_list|slice:":2" }}

slugify
-------

Converts to lowercase, removes non-word characters (only alphanumerics and
underscores are kept) and converts spaces to hyphens. Also strips leading and trailing
whitespace.

For example::

    {{ value|slugify }}

If ``value`` is ``"Joel is a slug"``, the output will be ``"joel-is-a-slug"``.

stringformat
------------

Formats the variable according to the argument, a string formatting specifier.
This specifier uses Python string formatting syntax, with the exception that
the leading "%" is dropped.

See http://docs.python.org/library/stdtypes.html#string-formatting-operations
for documentation of Python string formatting.

For example::

    {{ value|stringformat:"s" }}

If ``value`` is ``"Joel is a slug"``, the output will be ``"Joel is a slug"``.

striptags
---------

Strips all [X]HTML tags.

For example::

    {{ value|striptags }}

If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"``, the
output will be ``"Joel is a slug"``.

time
----

Formats a time according to the given format (same as the `now`_ tag).
The time filter will only accept parameters in the format string that relate
to the time of day, not the date (for obvious reasons). If you need to
format a date, use the `date`_ filter.

For example::

    {{ value|time:"H:i" }}

If ``value`` is equivalent to ``datetime.datetime.now()``, the output will be
the string ``"01:23"``.

When used without a format string::

    {{ value|time }}

...the formatting string defined in the ``TIME_FORMAT`` setting will be
used.

timesince
---------

Formats a date as the time since that date (e.g., "4 days, 6 hours").

Takes an optional argument that is a variable containing the date to use as
the comparison point (without the argument, the comparison point is *now*).
For example, if ``blog_date`` is a date instance representing midnight on 1
June 2006, and ``comment_date`` is a date instance for 08:00 on 1 June 2006,
then ``{{ blog_date|timesince:comment_date }}`` would return "8 hours".

Comparing offset-naive and offset-aware datetimes will return an empty string.

Minutes is the smallest unit used, and "0 minutes" will be returned for any
date that is in the future relative to the comparison point.

timeuntil
---------

Similar to ``timesince``, except that it measures the time from now until the
given date or datetime. For example, if today is 1 June 2006 and
``conference_date`` is a date instance holding 29 June 2006, then
``{{ conference_date|timeuntil }}`` will return "4 weeks".

Takes an optional argument that is a variable containing the date to use as
the comparison point (instead of *now*). If ``from_date`` contains 22 June
2006, then ``{{ conference_date|timeuntil:from_date }}`` will return "1 week".

Comparing offset-naive and offset-aware datetimes will return an empty string.

Minutes is the smallest unit used, and "0 minutes" will be returned for any
date that is in the past relative to the comparison point.

title
-----

Converts a string into titlecase.

truncatewords
-------------

Truncates a string after a certain number of words.

**Argument:** Number of words to truncate after

For example::

    {{ value|truncatewords:2 }}

If ``value`` is ``"Joel is a slug"``, the output will be ``"Joel is ..."``.

truncatewords_html
------------------

Similar to ``truncatewords``, except that it is aware of HTML tags. Any tags
that are opened in the string and not closed before the truncation point, are
closed immediately after the truncation.

This is less efficient than ``truncatewords``, so should only be used when it
is being passed HTML text.

unordered_list
--------------

Recursively takes a self-nested list and returns an HTML unordered list --
WITHOUT opening and closing <ul> tags.

The list is assumed to be in the proper format. For example, if ``var`` contains
``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then
``{{ var|unordered_list }}`` would return::

    <li>States
    <ul>
            <li>Kansas
            <ul>
                    <li>Lawrence</li>
                    <li>Topeka</li>
            </ul>
            </li>
            <li>Illinois</li>
    </ul>
    </li>

upper
-----

Converts a string into all uppercase.

For example::

    {{ value|upper }}

If ``value`` is ``"Joel is a slug"``, the output will be ``"JOEL IS A SLUG"``.

urlencode
---------

Escapes a value for use in a URL.

urlize
------

Converts URLs in plain text into clickable links.

Note that if ``urlize`` is applied to text that already contains HTML markup,
things won't work as expected. Apply this filter only to *plain* text.

For example::

    {{ value|urlize }}

If ``value`` is ``"Check out www.djangoproject.com"``, the output will be
``"Check out <a
href="http://www.djangoproject.com">www.djangoproject.com</a>"``.

urlizetrunc
-----------

Converts URLs into clickable links, truncating URLs longer than the given
character limit.

As with urlize_, this filter should only be applied to *plain* text.

**Argument:** Length to truncate URLs to

For example::

    {{ value|urlizetrunc:15 }}

If ``value`` is ``"Check out www.djangoproject.com"``, the output would be
``'Check out <a
href="http://www.djangoproject.com">www.djangopr...</a>'``.

wordcount
---------

Returns the number of words.

wordwrap
--------

Wraps words at specified line length.

**Argument:** number of characters at which to wrap the text

For example::

    {{ value|wordwrap:5 }}

If ``value`` is ``Joel is a slug``, the output would be::

    Joel
    is a
    slug

yesno
-----

Given a string mapping values for ``True``, ``False``, and (optionally) ``None``,
returns one of those strings according to the value (see Table F-4).

.. table:: Table E-4. Examples of the yesno Filter

    ==========  ======================  ==================================
    Value       Argument                Outputs
    ==========  ======================  ==================================
    ``True``    ``"yeah,no,maybe"``     ``yeah``
    ``False``   ``"yeah,no,maybe"``     ``no``
    ``None``    ``"yeah,no,maybe"``     ``maybe``
    ``None``    ``"yeah,no"``           ``"no"`` (converts None to False
                                        if no mapping for None is given)
    ==========  ======================  ==================================


================================================
FILE: Python/DjangoBook/appendixF.rst
================================================
====================================
Appendix F: The django-admin Utility
====================================

``django-admin.py`` is Django's command-line utility for administrative tasks.
This appendix explains its many powers.

You'll usually access ``django-admin.py`` through a project's ``manage.py``
wrapper. ``manage.py`` is automatically created in each Django project and is a
thin wrapper around ``django-admin.py``. It takes care of two things for you
before delegating to ``django-admin.py``:

* It puts your project's package on ``sys.path``.

* It sets the ``DJANGO_SETTINGS_MODULE`` environment variable so that it
  points to your project's ``settings.py`` file.

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 it from some place on your path, such as ``/usr/local/bin``.

Windows users, who do not have symlinking functionality available,
can copy ``django-admin.py`` to a location on their existing path or edit the
``PATH`` settings (under Settings ~TRA Control Panel ~TRA System ~TRA Advanced ~TRA
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 appendix use ``django-admin.py`` to
be consistent, but any example can use ``manage.py`` just as well.

Usage
=====

Here's how to use it::

    django-admin.py <subcommand> [options]
    manage.py <subcommand> [options]

``subcommand`` should be one of the subcommands listed in this appendix.
``options``, which is optional, should be zero or more of the options available
for the given subcommand.

Getting runtime help
--------------------

Run ``django-admin.py help`` to display a list of all available subcommands.
Run ``django-admin.py help <subcommand>`` to display a description of the
given subcommand and a list of its available options.

App names
---------

Many subcommands take a list of "app names." An "app name" is the basename of
the package containing your models. For example, if your
Download .txt
gitextract_7wf_t8i0/

├── Python/
│   └── DjangoBook/
│       ├── Makefile
│       ├── Procfile
│       ├── README.rst
│       ├── app.py
│       ├── appendixA.rst
│       ├── appendixB.rst
│       ├── appendixC.rst
│       ├── appendixD.rst
│       ├── appendixE.rst
│       ├── appendixF.rst
│       ├── appendixG.rst
│       ├── bin/
│       │   └── post_compile
│       ├── chapter01.rst
│       ├── chapter02.rst
│       ├── chapter03.rst
│       ├── chapter04.rst
│       ├── chapter05.rst
│       ├── chapter06.rst
│       ├── chapter07.rst
│       ├── chapter08.rst
│       ├── chapter09.rst
│       ├── chapter10.rst
│       ├── chapter11.rst
│       ├── chapter12.rst
│       ├── chapter13.rst
│       ├── chapter14.rst
│       ├── chapter15.rst
│       ├── chapter16.rst
│       ├── chapter17.rst
│       ├── chapter18.rst
│       ├── chapter19.rst
│       ├── chapter20.rst
│       ├── conf.py
│       ├── frontmatter.rst
│       ├── graphics/
│       │   ├── chapter03.graffle
│       │   └── chapter20.graffle
│       ├── index.rst
│       ├── introduction.rst
│       ├── license.rst
│       ├── requirements.txt
│       └── themes/
│           └── djangobook/
│               ├── layout.html
│               ├── page.html
│               ├── search.html
│               ├── static/
│               │   ├── djangobook.css
│               │   ├── grids-min.css
│               │   ├── pea.py
│               │   └── reset-min.css
│               └── theme.conf.txt
└── README.md
Download .txt
SYMBOL INDEX (16 symbols across 2 files)

FILE: Python/DjangoBook/app.py
  function redirect (line 12) | def redirect(to):

FILE: Python/DjangoBook/themes/djangobook/static/pea.py
  function justdomain (line 46) | def justdomain(url):
  function sortByValue (line 55) | def sortByValue(d):
  function tailLines (line 62) | def tailLines(filename,linesback):
  function timeSinceApacheDate (line 84) | def timeSinceApacheDate(apacheDate):
  function getDNS (line 92) | def getDNS(ip):
  function getLogLines (line 102) | def getLogLines(logfile):
  function getOverview (line 113) | def getOverview():
  function displayOverviewHTML (line 159) | def displayOverviewHTML(overview):
  function urldetails (line 199) | def urldetails(url, cgiloc):
  function ipdetails (line 215) | def ipdetails(ip, cgiloc):
  function header (line 249) | def header():
  function footer (line 323) | def footer(): print """
  function atomHeader (line 331) | def atomHeader():
  function atomSummary (line 343) | def atomSummary(overview):
  function atomFooter (line 359) | def atomFooter():
Condensed preview — 49 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,334K chars).
[
  {
    "path": "Python/DjangoBook/Makefile",
    "chars": 5592,
    "preview": "# Makefile for Sphinx documentation\n#\n\n# You can set these variables from the command line.\nSPHINXOPTS    =\nSPHINXBUILD "
  },
  {
    "path": "Python/DjangoBook/Procfile",
    "chars": 51,
    "preview": "web: gunicorn -kgevent -w4 -b0.0.0.0:$PORT app:app\n"
  },
  {
    "path": "Python/DjangoBook/README.rst",
    "chars": 487,
    "preview": "===============\nThe Django Book\n===============\n\nWelcome to the community edition of the Django Book!\n\nThis book was ori"
  },
  {
    "path": "Python/DjangoBook/app.py",
    "chars": 1362,
    "preview": "\"\"\"\nThe simplest possible app that can serve these Sphinx docs and issue\nredirects for the previous URLs.\n\"\"\"\n\nimport st"
  },
  {
    "path": "Python/DjangoBook/appendixA.rst",
    "chars": 33048,
    "preview": "======================================\nAppendix A: Model Definition Reference\n======================================\n\nCh"
  },
  {
    "path": "Python/DjangoBook/appendixB.rst",
    "chars": 52338,
    "preview": "==================================\nAppendix B: Database API Reference\n==================================\n\nDjango's datab"
  },
  {
    "path": "Python/DjangoBook/appendixC.rst",
    "chars": 30926,
    "preview": "==================================\nAppendix C: Generic View Reference\n==================================\n\nChapter 11 int"
  },
  {
    "path": "Python/DjangoBook/appendixD.rst",
    "chars": 30050,
    "preview": "====================\nAppendix D: Settings\n====================\n\nYour Django settings file contains all the configuration"
  },
  {
    "path": "Python/DjangoBook/appendixE.rst",
    "chars": 42427,
    "preview": "==============================================\nAppendix E: Built-in Template Tags and Filters\n=========================="
  },
  {
    "path": "Python/DjangoBook/appendixF.rst",
    "chars": 25439,
    "preview": "====================================\nAppendix F: The django-admin Utility\n====================================\n\n``django"
  },
  {
    "path": "Python/DjangoBook/appendixG.rst",
    "chars": 24165,
    "preview": "========================================\nAppendix G: Request and Response Objects\n======================================"
  },
  {
    "path": "Python/DjangoBook/bin/post_compile",
    "chars": 70,
    "preview": "#!/bin/bash\n\nsphinx-build -q -b html -d _build/doctrees . _build/html\n"
  },
  {
    "path": "Python/DjangoBook/chapter01.rst",
    "chars": 17212,
    "preview": "=================================\nChapter 1: Introduction to Django\n=================================\n\nThis book is abou"
  },
  {
    "path": "Python/DjangoBook/chapter02.rst",
    "chars": 22470,
    "preview": "==========================\nChapter 2: Getting Started\n==========================\n\nInstalling Django is a multi-step proc"
  },
  {
    "path": "Python/DjangoBook/chapter03.rst",
    "chars": 43167,
    "preview": "=============================\nChapter 3: Views and URLconfs\n=============================\n\nIn the previous chapter, we e"
  },
  {
    "path": "Python/DjangoBook/chapter04.rst",
    "chars": 64656,
    "preview": "====================\nChapter 4: Templates\n====================\n\nIn the previous chapter, you may have noticed something "
  },
  {
    "path": "Python/DjangoBook/chapter05.rst",
    "chars": 59059,
    "preview": "=================\nChapter 5: Models\n=================\n\nIn Chapter 3, we covered the fundamentals of building dynamic Web"
  },
  {
    "path": "Python/DjangoBook/chapter06.rst",
    "chars": 44390,
    "preview": "================================\nChapter 6: The Django Admin Site\n================================\n\nFor a certain class "
  },
  {
    "path": "Python/DjangoBook/chapter07.rst",
    "chars": 50040,
    "preview": "================\nChapter 7: Forms\n================\n\nHTML forms are the backbone of interactive Web sites, from the simpl"
  },
  {
    "path": "Python/DjangoBook/chapter08.rst",
    "chars": 42529,
    "preview": "======================================\nChapter 8: Advanced Views and URLconfs\n======================================\n\n.."
  },
  {
    "path": "Python/DjangoBook/chapter09.rst",
    "chars": 50670,
    "preview": "=============================\nChapter 9: Advanced Templates\n=============================\n\nAlthough most of your interac"
  },
  {
    "path": "Python/DjangoBook/chapter10.rst",
    "chars": 22465,
    "preview": "===========================\nChapter 10: Advanced Models\n===========================\n\nIn Chapter 5, we presented an intro"
  },
  {
    "path": "Python/DjangoBook/chapter11.rst",
    "chars": 20116,
    "preview": "=========================\nChapter 11: Generic Views\n=========================\n\nHere again is a recurring theme of this b"
  },
  {
    "path": "Python/DjangoBook/chapter12.rst",
    "chars": 45444,
    "preview": "============================\nChapter 12: Deploying Django\n============================\n\nThis chapter covers the last ess"
  },
  {
    "path": "Python/DjangoBook/chapter13.rst",
    "chars": 36562,
    "preview": "=======================================\nChapter 13: Generating Non-HTML Content\n=======================================\n"
  },
  {
    "path": "Python/DjangoBook/chapter14.rst",
    "chars": 52016,
    "preview": "=============================================\nChapter 14: Sessions, Users, and Registration\n============================"
  },
  {
    "path": "Python/DjangoBook/chapter15.rst",
    "chars": 31862,
    "preview": "===================\nChapter 15: Caching\n===================\n\nA fundamental trade-off in dynamic Web sites is, well, they"
  },
  {
    "path": "Python/DjangoBook/chapter16.rst",
    "chars": 39289,
    "preview": "==========================\nChapter 16: django.contrib\n==========================\n\nOne of the many strengths of Python is"
  },
  {
    "path": "Python/DjangoBook/chapter17.rst",
    "chars": 16970,
    "preview": "======================\nChapter 17: Middleware\n======================\n\nOn occasion, you'll need to run a piece of code on"
  },
  {
    "path": "Python/DjangoBook/chapter18.rst",
    "chars": 13612,
    "preview": "==============================================================\nChapter 18: Integrating with Legacy Databases and Applica"
  },
  {
    "path": "Python/DjangoBook/chapter19.rst",
    "chars": 39530,
    "preview": "================================\nChapter 19: Internationalization\n================================\n\nDjango was originall"
  },
  {
    "path": "Python/DjangoBook/chapter20.rst",
    "chars": 21899,
    "preview": "====================\nChapter 20: Security\n====================\n\nThe Internet can be a scary place.\n\nThese days, high-pro"
  },
  {
    "path": "Python/DjangoBook/conf.py",
    "chars": 1207,
    "preview": "# Basic project info\nproject = u'The Django Book'\ncopyright = u'Adrian Holovaty, Jacob Kaplan-Moss, et al.'\nversion = '2"
  },
  {
    "path": "Python/DjangoBook/frontmatter.rst",
    "chars": 4853,
    "preview": "===============\nAbout this book\n===============\n\nYou’re reading The Django Book, first published in December 2007 (and u"
  },
  {
    "path": "Python/DjangoBook/graphics/chapter03.graffle",
    "chars": 49005,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.c"
  },
  {
    "path": "Python/DjangoBook/graphics/chapter20.graffle",
    "chars": 161170,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.c"
  },
  {
    "path": "Python/DjangoBook/index.rst",
    "chars": 909,
    "preview": "===============\nThe Django Book\n===============\n\nWelcome to the online version of The Django Book, a free book about the"
  },
  {
    "path": "Python/DjangoBook/introduction.rst",
    "chars": 3601,
    "preview": "============\nIntroduction\n============\n\nIn the early days, Web developers wrote every page by hand. Updating a Web site\n"
  },
  {
    "path": "Python/DjangoBook/license.rst",
    "chars": 21023,
    "preview": "===================\nLicense & Copyright\n===================\n\nCopyright Adrian Holovaty, Jacob Kaplan-Moss, and contribut"
  },
  {
    "path": "Python/DjangoBook/requirements.txt",
    "chars": 163,
    "preview": "docutils==0.9.1\ngevent==0.13.8\ngreenlet==0.4.0\ngunicorn==0.14.6\nJinja2==2.6\nPygments==1.5\nresolver==0.2.1\nselector==0.9."
  },
  {
    "path": "Python/DjangoBook/themes/djangobook/layout.html",
    "chars": 1362,
    "preview": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n<html>\n  <head>\n    <meta htt"
  },
  {
    "path": "Python/DjangoBook/themes/djangobook/page.html",
    "chars": 540,
    "preview": "{% extends \"layout.html\" %}\n\n{% block title %}{{ title }}{% endblock %}\n\n{% macro nav() %}\n<div class=\"nav\">\n    {% if p"
  },
  {
    "path": "Python/DjangoBook/themes/djangobook/search.html",
    "chars": 6,
    "preview": "TODO!\n"
  },
  {
    "path": "Python/DjangoBook/themes/djangobook/static/djangobook.css",
    "chars": 5239,
    "preview": "/*** setup ***/\nbody { font:12px/1.5 Verdana,sans-serif; background:#092e20; color: white;}\n#bd { background:#487858; }\n"
  },
  {
    "path": "Python/DjangoBook/themes/djangobook/static/grids-min.css",
    "chars": 1920,
    "preview": "/* Copyright (c) 2006, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.net/"
  },
  {
    "path": "Python/DjangoBook/themes/djangobook/static/pea.py",
    "chars": 13208,
    "preview": "#!/usr/bin/env python\n\"\"\"peastat - simple live web stats\nhttp://www.throwingbeans.org/peastat/\n\ninstructions: \n1. config"
  },
  {
    "path": "Python/DjangoBook/themes/djangobook/static/reset-min.css",
    "chars": 535,
    "preview": "/* Copyright (c) 2006, Yahoo! Inc. All rights reserved. Code licensed under the BSD License:http://developer.yahoo.net/y"
  },
  {
    "path": "Python/DjangoBook/themes/djangobook/theme.conf.txt",
    "chars": 75,
    "preview": "[theme]\ninherit = none\nstylesheet = djangobook.css\npygments_style = sphinx\n"
  },
  {
    "path": "README.md",
    "chars": 98,
    "preview": "# programming-ebooks-to-help-you-code-better\n\nThis are some of  the eBooks I use to learn coding\n\n"
  }
]

About this extraction

This page contains the full source code of the peter-kimanzi/programming-ebooks-to-help-you-code-better GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 49 files (1.2 MB), approximately 316.8k tokens, and a symbol index with 16 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!