1
0
mirror of https://github.com/django/django.git synced 2025-10-31 09:41:08 +00:00

newforms-admin: Merged to [6612]

git-svn-id: http://code.djangoproject.com/svn/django/branches/newforms-admin@6613 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Joseph Kocherhans
2007-10-26 20:21:10 +00:00
parent 11b6e1eeb7
commit 1746760500
99 changed files with 10678 additions and 7982 deletions

View File

@@ -28,21 +28,21 @@ with the standard ``Auth*`` and ``Require`` directives::
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonAuthenHandler django.contrib.auth.handlers.modpython
</Location>
.. admonition:: Using the authentication handler with Apache 2.2
If you're using Apache 2.2, you'll need to take a couple extra steps.
You'll need to ensure that ``mod_auth_basic`` and ``mod_authz_user``
are loaded. These might be compiled statically into Apache, or you might
need to use ``LoadModule`` to load them dynamically (as shown in the
example at the bottom of this note).
You'll also need to insert configuration directives that prevent Apache
from trying to use other authentication modules. Depending on which other
authentication modules you have loaded, you might need one or more of
the following directives::
AuthBasicAuthoritative Off
AuthDefaultAuthoritative Off
AuthzLDAPAuthoritative Off
@@ -51,18 +51,18 @@ with the standard ``Auth*`` and ``Require`` directives::
AuthzGroupFileAuthoritative Off
AuthzOwnerAuthoritative Off
AuthzUserAuthoritative Off
A complete configuration, with differences between Apache 2.0 and
Apache 2.2 marked in bold, would look something like:
.. parsed-literal::
**LoadModule auth_basic_module modules/mod_auth_basic.so**
**LoadModule authz_user_module modules/mod_authz_user.so**
...
<Location /exmaple/>
<Location /example/>
AuthType Basic
AuthName "example.com"
**AuthBasicAuthoritative Off**
@@ -71,7 +71,7 @@ with the standard ``Auth*`` and ``Require`` directives::
SetEnv DJANGO_SETTINGS_MODULE mysite.settings
PythonAuthenHandler django.contrib.auth.handlers.modpython
</Location>
By default, the authentication handler will limit access to the ``/example/``
location to users marked as staff members. You can use a set of
``PythonOption`` directives to modify this behavior:

View File

@@ -119,8 +119,8 @@ in your database that is in the proper format that Django's database-cache
system expects.
Once you've created that database table, set your ``CACHE_BACKEND`` setting to
``"db://tablename/"``, where ``tablename`` is the name of the database table.
In this example, the cache table's name is ``my_cache_table``:
``"db://tablename"``, where ``tablename`` is the name of the database table.
In this example, the cache table's name is ``my_cache_table``::
CACHE_BACKEND = 'db://my_cache_table'
@@ -228,7 +228,7 @@ entire site. Just add ``'django.middleware.cache.CacheMiddleware'`` to your
'django.middleware.common.CommonMiddleware',
)
(The order of ``MIDDLEWARE_CLASSES`` matters. See "Order of MIDDLEWARE_CLASSES"
(The order of ``MIDDLEWARE_CLASSES`` matters. See `Order of MIDDLEWARE_CLASSES`_
below.)
Then, add the following required settings to your Django settings file:
@@ -288,6 +288,36 @@ Or, using Python 2.4's decorator syntax::
above example, the result of the ``slashdot_this()`` view will be cached for 15
minutes.
Template fragment caching
=========================
If you're after even more control, you can also cache template fragments using
the ``cache`` template tag. To give your template access to this tag, put ``{%
load cache %}`` near the top of your template.
The ``{% cache %}`` template tag caches the contents of the block for a given
amount of time. It takes at least two arguments: the cache timeout, in
seconds, and the name to give the cache fragment. For example::
{% load cache %}
{% cache 500 sidebar %}
.. sidebar ..
{% endcache %}
Sometimes you might want to cache multiple copies of a fragment depending on
some dynamic data that appears inside the fragment. For example you may want a
separate cached copy of the sidebar used in the previous example for every user
of your site. This can be easily achieved by passing additional arguments to
the ``{% cache %}`` template tag to uniquely identify the cache fragment::
{% load cache %}
{% cache 500 sidebar request.user.username %}
.. sidebar for logged in user ..
{% endcache %}
If you need more than one argument to identify the fragment that's fine, simply
pass as many arguments to ``{% cache %}`` as you need!
The low-level cache API
=======================
@@ -326,6 +356,15 @@ get() can take a ``default`` argument::
>>> cache.get('my_key', 'has expired')
'has expired'
To add a key only if it doesn't already exist, there is an add() method. It
takes the same parameters as set(), but will not attempt to update the cache
if the key specified is already present::
>>> cache.set('add_key', 'Initial value')
>>> cache.add('add_key', 'New value')
>>> cache.get('add_key')
'Initial value'
There's also a get_many() interface that only hits the cache once. get_many()
returns a dictionary with all the keys you asked for that actually exist in the
cache (and haven't expired)::
@@ -524,7 +563,7 @@ the value of the ``CACHE_MIDDLEWARE_SETTINGS`` setting. If you use a custom
``max_age`` in a ``cache_control`` decorator, the decorator will take
precedence, and the header values will be merged correctly.)
If you want to use headers to disable caching altogether,
If you want to use headers to disable caching altogether,
``django.views.decorators.never_cache`` is a view decorator that adds
headers to ensure the response won't be cached by browsers or other caches. Example::
@@ -556,8 +595,11 @@ within the ``MIDDLEWARE_CLASSES`` setting, because the cache middleware needs
to know which headers by which to vary the cache storage. Middleware always
adds something to the ``Vary`` response header when it can.
Put the ``CacheMiddleware`` after any middlewares that might add something to
the ``Vary`` header. The following middlewares do so:
Put the ``CacheMiddleware`` *before* any other middleware that might add
something to the ``Vary`` header (response middleware is applied in reverse
order). The following middleware modules do so:
* ``SessionMiddleware`` adds ``Cookie``
* ``GZipMiddleware`` adds ``Accept-Encoding``
* ``LocaleMiddleware`` adds ``Accept-Language``

View File

@@ -335,6 +335,10 @@ Please follow these coding standards when writing code for inclusion in Django:
* Unless otherwise specified, follow `PEP 8`_.
You could use a tool like `pep8.py`_ to check for some problems in this
area, but remember that PEP 8 is only a guide, so respect the style of
the surrounding code as a primary goal.
* Use four spaces for indentation.
* Use underscores, not camelCase, for variable, function and method names
@@ -924,5 +928,6 @@ requests for commit access are potential flame-war starters, and will be ignored
.. _`#django`: irc://irc.freenode.net/django
.. _list of tickets with patches: http://code.djangoproject.com/query?status=new&status=assigned&status=reopened&has_patch=1&order=priority
.. _PEP 8: http://www.python.org/peps/pep-0008.html
.. _pep8.py: http://svn.browsershots.org/trunk/devtools/pep8/pep8.py
.. _i18n branch: http://code.djangoproject.com/browser/django/branches/i18n
.. _`tags/releases`: http://code.djangoproject.com/browser/django/tags/releases

View File

@@ -76,6 +76,14 @@ the ``mysql`` backend.
If you are trying to use an older version of MySQL and the ``mysql_old``
backend, then 1.2.0 *might* work for you.
.. note::
If you see ``ImportError: cannot import name ImmutableSet`` when trying to
use Django, your MySQLdb installation may contain an outdated ``sets.py``
file that conflicts with the built-in module of the same name from Python
2.4 and later. To fix this, verify that you have installed MySQLdb version
1.2.1p2 or newer, then delete the ``sets.py`` file in the MySQLdb
directory that was left by an earlier version.
.. _MySQLdb: http://sourceforge.net/projects/mysql-python
Creating your database

View File

@@ -741,22 +741,25 @@ Customized actions
**New in Django development version**
If you want to add an action of your own to ``manage.py``, you can.
Simply add a ``management/commands`` directory to your application.
Each python module in that directory will be discovered and registered as
Applications can register their own actions with ``manage.py``. For example,
you might want to add a ``manage.py`` action for a Django app that you're
distributing.
To do this, just add a ``management/commands`` directory to your application.
Each Python module in that directory will be auto-discovered and registered as
a command that can be executed as an action when you run ``manage.py``::
/fancy_blog
blog/
__init__.py
models.py
/management
management/
__init__.py
/commands
commands/
__init__.py
explode.py
views.py
In this example, ``explode`` command will be made available to any project
In this example, the ``explode`` command will be made available to any project
that includes the ``fancy_blog`` application in ``settings.INSTALLED_APPS``.
The ``explode.py`` module has only one requirement -- it must define a class

View File

@@ -48,7 +48,7 @@ with the given URL with a site ID that corresponds to the SITE_ID_ setting.
If it finds a match, it follows this algorithm:
* If the flatpage has a custom template, it loads that template. Otherwise,
it loads the template ``flatpages/default``.
it loads the template ``flatpages/default.html``.
* It passes that template a single context variable, ``flatpage``, which is
the flatpage object. It uses RequestContext_ in rendering the template.

View File

@@ -456,10 +456,13 @@ otherwise, they'll be tacked together without whitespace!
.. admonition:: Mind your charset
When creating a ``.po`` file with your favorite text editor, first edit
When creating a PO file with your favorite text editor, first edit
the charset line (search for ``"CHARSET"``) and set it to the charset
you'll be using to edit the content. Generally, utf-8 should work for most
languages, but ``gettext`` should handle any charset you throw at it.
you'll be using to edit the content. Due to the way the ``gettext`` tools
work internally and because we want to allow non-ASCII source strings in
Django's core and your applications, you **must** use UTF-8 as the encoding
for your PO file (this means that everybody will be using the same
encoding, which is important when Django processes the PO files).
To reexamine all source code and templates for new translation strings and
update all message files for **all** languages, run this::

View File

@@ -63,7 +63,10 @@ installed.
* If you're using MySQL, you'll need MySQLdb_, version 1.2.1p2 or higher.
You will also want to read the database-specific notes for the `MySQL backend`_.
* If you're using SQLite, you'll need pysqlite_. Use version 2.0.3 or higher.
* If you're using SQLite and either Python 2.3 or Python 2.4, you'll need
pysqlite_. Use version 2.0.3 or higher. Python 2.5 ships with an sqlite
wrapper in the standard library, so you don't need to install anything extra
in that case.
* If you're using Oracle, you'll need cx_Oracle_, version 4.3.1 or higher.
You will also want to read the database-specific notes for the `Oracle backend`_.

View File

@@ -178,8 +178,9 @@ request, before Django decides which view to execute.
``process_request()`` should return either ``None`` or an ``HttpResponse``
object. If it returns ``None``, Django will continue processing this request,
executing any other middleware and, then, the appropriate view. If it returns
an ``HttpResponse`` object, Django won't bother calling ANY other middleware or
the appropriate view; it'll return that ``HttpResponse``.
an ``HttpResponse`` object, Django won't bother calling ANY other request,
view or exception middleware, or the appropriate view; it'll return that
``HttpResponse``. Response middleware is always called on every response.
process_view
------------
@@ -197,8 +198,9 @@ arguments that will be passed to the view. Neither ``view_args`` nor
return either ``None`` or an ``HttpResponse`` object. If it returns ``None``,
Django will continue processing this request, executing any other
``process_view()`` middleware and, then, the appropriate view. If it returns an
``HttpResponse`` object, Django won't bother calling ANY other middleware or
the appropriate view; it'll return that ``HttpResponse``.
``HttpResponse`` object, Django won't bother calling ANY other request, view
or exception middleware, or the appropriate view; it'll return that
``HttpResponse``. Response middleware is always called on every response.
process_response
----------------
@@ -236,7 +238,8 @@ Guidelines
* Feel free to look at Django's available middleware for examples. The
core Django middleware classes are in ``django/middleware/`` in the
Django distribution. The session middleware is in ``django/contrib/sessions``.
Django distribution. The session middleware is in
``django/contrib/sessions``.
* If you write a middleware component that you think would be useful to
other people, contribute to the community! Let us know, and we'll

View File

@@ -149,7 +149,7 @@ and in Django's validation.
Django veterans: Note that the argument is now called ``max_length`` to
provide consistency throughout Django. There is full legacy support for
the old ``maxlength`` argument, but ``max_length`` is preferred.
``CommaSeparatedIntegerField``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -678,7 +678,9 @@ set.
If ``True``, this field must be unique throughout the table.
This is enforced at the database level and at the Django admin-form level.
This is enforced at the database level and at the Django admin-form level. If
you try to add save a model with a duplicate value in a ``unique`` field, a
``django.db.IntegrityError`` will be raised by the model's ``save()`` method.
``unique_for_date``
~~~~~~~~~~~~~~~~~~~
@@ -1584,8 +1586,8 @@ Finally, note that in order to use ``list_display_links``, you must define
Set ``list_filter`` to activate filters in the right sidebar of the change list
page of the admin. This should be a list of field names, and each specified
field should be either a ``BooleanField``, ``CharField``, ``DateField``,
``DateTimeField``, ``IntegerField`` or ``ForeignKey``.
field should be either a ``BooleanField``, ``CharField``, ``DateField``,
``DateTimeField``, ``IntegerField`` or ``ForeignKey``.
This example, taken from the ``django.contrib.auth.models.User`` model, shows
how both ``list_display`` and ``list_filter`` work::

View File

@@ -87,17 +87,19 @@ lived under the ``weblog/`` directory, you would *also* need to add
**parent directories** of anything you import directly must be on the Python
path.
.. caution::
.. note::
If you're using Windows, remember that the path will contain backslashes.
This string is passed through Python's string parser twice, so you need to
escape each backslash **twice**::
If you're using Windows, it is still recommended that you use forward
slashes in the pathnames, even though Windows normally uses backslashes
for its native separator. Apache knows how to convert from the forward
slash format to the native format, so this approach is portable and easier
to read (it avoids tricky problems with having to double-escape
backslashes).
PythonPath "['c:\\\\path\\\\to\\\\project'] + sys.path"
This is valid even on a Windows system::
Or, use raw strings::
PythonPath "['c:/path/to/project'] + sys.path"
PythonPath "[r'c:\\path\\to\\project'] + sys.path"
You can also add directives such as ``PythonAutoReload Off`` for performance.
See the `mod_python documentation`_ for a full list of options.

View File

@@ -103,7 +103,7 @@ Start with this basic ``Form`` subclass, which we'll call ``ContactForm``::
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField()
cc_myself = forms.BooleanField(required=False)
A form is composed of ``Field`` objects. In this case, our form has four
fields: ``subject``, ``message``, ``sender`` and ``cc_myself``. We'll explain
@@ -863,6 +863,23 @@ classes::
<li>Instrument: <input type="text" name="instrument" /></li>
<li>Haircut type: <input type="text" name="haircut_type" /></li>
Prefixes for forms
------------------
You can put several Django forms inside one ``<form>`` tag. To give each
``Form`` its own namespace you need to use the ``prefix`` keyword argument::
>>> mother = PersonForm(prefix="mother")
>>> father = PersonForm(prefix="father")
>>> print mother.as_ul()
<li><label for="id_mother-first_name">First name:</label> <input type="text" name="mother-first_name" id="id_mother-first_name" /></li>
<li><label for="id_mother-last_name">Last name:</label> <input type="text" name="mother-last_name" id="id_mother-last_name" /></li>
>>> print father.as_ul()
<li><label for="id_father-first_name">First name:</label> <input type="text" name="father-first_name" id="id_father-first_name" /></li>
<li><label for="id_father-last_name">Last name:</label> <input type="text" name="father-last_name" id="id_father-last_name" /></li>
Fields
======
@@ -1046,7 +1063,7 @@ fields. We've specified ``auto_id=False`` to simplify the output::
... subject = forms.CharField(max_length=100, help_text='100 characters max.')
... message = forms.CharField()
... sender = forms.EmailField(help_text='A valid e-mail address, please.')
... cc_myself = forms.BooleanField()
... cc_myself = forms.BooleanField(required=False)
>>> f = HelpTextContactForm(auto_id=False)
>>> print f.as_table()
<tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" /><br />100 characters max.</td></tr>
@@ -1125,9 +1142,20 @@ For each field, we describe the default widget used if you don't specify
~~~~~~~~~~~~~~~~
* Default widget: ``CheckboxInput``
* Empty value: ``None``
* Empty value: ``False``
* Normalizes to: A Python ``True`` or ``False`` value.
* Validates nothing (i.e., it never raises a ``ValidationError``).
* Validates that the check box is checked (i.e. the value is ``True``) if
the field has ``required=True``.
**New in Django development version:** The empty value for a ``CheckboxInput``
(and hence the standard ``BooleanField``) has changed to return ``False``
instead of ``None`` in the development version.
.. note::
Since all ``Field`` subclasses have ``required=True`` by default, the
validation condition here is important. If you want to include a checkbox
in your form that can be either checked or unchecked, you must remember to
pass in ``required=False`` when creating the ``BooleanField``.
``CharField``
~~~~~~~~~~~~~
@@ -1135,7 +1163,8 @@ For each field, we describe the default widget used if you don't specify
* Default widget: ``TextInput``
* Empty value: ``''`` (an empty string)
* Normalizes to: A Unicode object.
* Validates nothing, unless ``max_length`` or ``min_length`` is provided.
* Validates ``max_length`` or ``min_length``, if they are provided.
Otherwise, all inputs are valid.
Has two optional arguments for validation, ``max_length`` and ``min_length``.
If provided, these arguments ensure that the string is at most or at least the
@@ -1175,7 +1204,7 @@ If no ``input_formats`` argument is provided, the default input formats are::
``DateTimeField``
~~~~~~~~~~~~~~~~~
* Default widget: ``TextInput``
* Default widget: ``DateTimeInput``
* Empty value: ``None``
* Normalizes to: A Python ``datetime.datetime`` object.
* Validates that the given value is either a ``datetime.datetime``,
@@ -1196,6 +1225,9 @@ If no ``input_formats`` argument is provided, the default input formats are::
'%m/%d/%y %H:%M', # '10/25/06 14:30'
'%m/%d/%y', # '10/25/06'
**New in Django development version:** The ``DateTimeField`` used to use a
``TextInput`` widget by default. This has now changed.
``DecimalField``
~~~~~~~~~~~~~~~~
@@ -1511,7 +1543,7 @@ like so::
subject = forms.CharField(max_length=100)
message = forms.CharField()
senders = MultiEmailField()
cc_myself = forms.BooleanField()
cc_myself = forms.BooleanField(required=False)
Widgets
=======
@@ -1532,6 +1564,7 @@ commonly used groups of widgets:
``MultipleHiddenInput`` Multiple ``<input type='hidden' ...``
instances.
``FileInput`` ``<input type='file' ...``
``DateTimeInput`` ``<input type='text' ...``
``Textarea`` ``<textarea>...</textarea>``
``CheckboxInput`` ``<input type='checkbox' ...``
``Select`` ``<select><option ...``
@@ -1545,6 +1578,9 @@ commonly used groups of widgets:
one for the Date, and one for the Time.
============================ ===========================================
**New in Django development version:** The ``DateTimeInput`` has been added
since the last release.
Specifying widgets
------------------
@@ -2036,7 +2072,7 @@ have a ``Message`` model that holds each contact submission. Something like::
subject = models.CharField(max_length=100)
message = models.TextField()
sender = models.EmailField()
cc_myself = models.BooleanField()
cc_myself = models.BooleanField(required=False)
You could use this model to create a form (using ``form_for_model()``). You
could also use existing ``Message`` instances to create a form for editing

View File

@@ -381,8 +381,8 @@ Methods
``mimetype``. Historically, the parameter was only called ``mimetype``,
but since this is actually the value included in the HTTP ``Content-Type``
header, it can also include the character set encoding, which makes it
more than just a MIME type specification. If ``mimetype`` is specifiedi
(not None), that value is used. Otherwise, ``content_type`` is used. If
more than just a MIME type specification. If ``mimetype`` is specified
(not None), that value is used. Otherwise, ``content_type`` is used. If
neither is given, the ``DEFAULT_CONTENT_TYPE`` setting is used.
``__setitem__(header, value)``

View File

@@ -172,7 +172,7 @@ of the case of the actual model class name.
ADMIN_FOR
---------
Default: ``()`` (Empty list)
Default: ``()`` (Empty tuple)
Used for admin-site settings modules, this should be a tuple of settings
modules (in the format ``'foo.bar.baz'``) for which this site is an admin.
@@ -475,7 +475,7 @@ FIXTURE_DIRS
Default: ``()`` (Empty tuple)
List of locations of the fixture data files, in search order. Note that
these paths should use Unix-style forward slashes, even on Windows. See
these paths should use Unix-style forward slashes, even on Windows. See
`Testing Django Applications`_.
.. _Testing Django Applications: ../testing/
@@ -578,6 +578,17 @@ 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.
LOCALE_PATHS
------------
Default: ``()`` (Empty tuple)
A list of directories where Django looks for translation files.
See the `internationalization docs section`_ explaining the variable and the
default behavior.
.. _internationalization docs section: ../i18n/#using-translations-in-your-own-projects
LOGIN_REDIRECT_URL
------------------
@@ -720,8 +731,8 @@ SERIALIZATION_MODULES
Default: Not defined.
A dictionary of modules containing serializer definitions (provided as
strings), keyed by a string identifier for that serialization type. For
A dictionary of modules containing serializer definitions (provided as
strings), keyed by a string identifier for that serialization type. For
example, to define a YAML serializer, use::
SERIALIZATION_MODULES = { 'yaml' : 'path.to.yaml_serializer' }
@@ -743,10 +754,10 @@ Default: ``django.contrib.sessions.backends.db``
Controls where Django stores session data. Valid values are:
* ``'django.contrib.sessions.backends.db'``
* ``'django.contrib.sessions.backends.file'``
* ``'django.contrib.sessions.backends.db'``
* ``'django.contrib.sessions.backends.file'``
* ``'django.contrib.sessions.backends.cache'``
See the `session docs`_ for more details.
SESSION_COOKIE_AGE
@@ -773,6 +784,18 @@ Default: ``'sessionid'``
The name of the cookie to use for sessions. This can be whatever you want.
See the `session docs`_.
SESSION_COOKIE_PATH
-------------------
**New in Django development version**
Default: ``'/'``
The path set on the session cookie. Should match the URL path of your Django
installation (or be parent of that path). This is useful if you have multiple
Django instances running under the same hostname; they can use different
cookie paths and each instance will only see its own session cookie.
SESSION_COOKIE_SECURE
---------------------

View File

@@ -547,6 +547,22 @@ This example illustrates all possible attributes and methods for a ``Feed`` clas
copyright = 'Copyright (c) 2007, Sally Smith' # Hard-coded copyright notice.
# TTL -- One of the following three is optional. The framework looks
# for them in this order. Ignored for Atom feeds.
def ttl(self, obj):
"""
Takes the object returned by get_object() and returns the feed's
TTL (Time to live) as a normal Python string.
"""
def ttl(self):
"""
Returns the feed's ttl as a normal Python string.
"""
ttl = 600 # Hard-coded Time to live.
# ITEMS -- One of the following three is required. The framework looks
# for them in this order.

View File

@@ -2,13 +2,35 @@
The Django template language: For template authors
==================================================
This document explains the language syntax of the Django template system. If
you're looking for a more technical perspective on how it works and how to
extend it, see `The Django template language: For Python programmers`_.
Django's template language is designed to strike a balance between power and
ease. It's designed to feel comfortable to those used to working with HTML. If
you have any exposure to other text-based template languages, such as Smarty_
or CheetahTemplate_, you should feel right at home with Django's templates.
.. admonition:: Philosophy
If you have a background in programming, or if you're used to languages
like PHP which mix programming code directly into HTML, you'll want to
bear in mind that the Django template system is not simply Python embedded
into HTML. This is by design: the template system is meant to express
presentation, not program logic.
The Django template system provides tags which function similarly to some
programming constructs -- an ``{% if %}`` tag for boolean tests, a ``{%
for %}`` tag for looping, etc. -- but these are not simply executed as the
corresponding Python code, and the template system will not execute
arbitrary Python expressions. Only the tags, filters and syntax listed
below are supported by default (although you can add `your own
extensions`_ to the template language as needed).
.. _`The Django template language: For Python programmers`: ../templates_python/
.. _Smarty: http://smarty.php.net/
.. _CheetahTemplate: http://www.cheetahtemplate.org/
.. _your own extensions: ../templates_python/#extending-the-template-system
Templates
=========
@@ -377,7 +399,7 @@ loop::
...
</tr>
{% endfor %}
Outside of a loop, give the values a unique name the first time you call it,
then use that name each successive time through::
@@ -385,16 +407,16 @@ then use that name each successive time through::
<tr class="{% cycle rowcolors %}">...</tr>
<tr class="{% cycle rowcolors %}">...</tr>
You can use any number of values, separated by spaces. Values enclosed in
single (') or double quotes (") are treated as string literals, while values
without quotes are assumed to refer to context variables.
You can use any number of values, separated by spaces. Values enclosed in
single (') or double quotes (") are treated as string literals, while values
without quotes are assumed to refer to context variables.
You can also separate values with commas::
{% cycle row1,row2,row3 %}
In this syntax, each value will be interpreted as literal text. The
comma-based syntax exists for backwards-compatibility, and should not be
In this syntax, each value will be interpreted as literal text. The
comma-based syntax exists for backwards-compatibility, and should not be
used for new projects.
debug
@@ -454,6 +476,11 @@ This is equivalent to::
{{ 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
~~~
@@ -472,13 +499,13 @@ 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 eachs sub-list into a set of known names. 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::
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.
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::
@@ -1438,12 +1465,3 @@ A collection of template tags that can be useful while designing a website,
such as a generator of Lorem Ipsum text. See the `webdesign documentation`_.
.. _webdesign documentation: ../webdesign/
Next steps
==========
Read the document `The Django template language: For Python programmers`_ if
you're interested in learning the template system from a technical
perspective -- how it works and how to extend it.
.. _The Django template language\: For Python programmers: ../templates_python/

View File

@@ -316,7 +316,7 @@ optional, third positional argument, ``processors``. In this example, the
}, [ip_address_processor])
return t.render(c)
Note::
.. note::
If you're using Django's ``render_to_response()`` shortcut to populate a
template with the contents of a dictionary, your template will be passed a
``Context`` instance by default (not a ``RequestContext``). To use a

View File

@@ -41,7 +41,7 @@ From the command line, ``cd`` into a directory where you'd like to store your
code, then run the command ``django-admin.py startproject mysite``. This
will create a ``mysite`` directory in your current directory.
.. admonition:: Max OS X permissions
.. admonition:: Mac OS X permissions
If you're using Mac OS X, you may see the message "permission
denied" when you try to run ``django-admin.py startproject``. This

View File

@@ -110,19 +110,22 @@ Conversion functions
The ``django.utils.encoding`` module contains a few functions that are handy
for converting back and forth between Unicode and bytestrings.
* ``smart_unicode(s, encoding='utf-8', errors='strict')`` converts its
input to a Unicode string. The ``encoding`` parameter specifies the input
encoding. (For example, Django uses this internally when processing form
input data, which might not be UTF-8 encoded.) The ``errors`` parameter
takes any of the values that are accepted by Python's ``unicode()``
function for its error handling.
* ``smart_unicode(s, encoding='utf-8', strings_only=False, errors='strict')``
converts its input to a Unicode string. The ``encoding`` parameter
specifies the input encoding. (For example, Django uses this internally
when processing form input data, which might not be UTF-8 encoded.) The
``strings_only`` parameter, if set to True, will result in Python
numbers, booleans and ``None`` not being converted to a string (they keep
their original types). The ``errors`` parameter takes any of the values
that are accepted by Python's ``unicode()`` function for its error
handling.
If you pass ``smart_unicode()`` an object that has a ``__unicode__``
method, it will use that method to do the conversion.
* ``force_unicode(s, encoding='utf-8', errors='strict')`` is identical to
``smart_unicode()`` in almost all cases. The difference is when the
first argument is a `lazy translation`_ instance. While
* ``force_unicode(s, encoding='utf-8', strings_only=False, errors='strict')``
is identical to ``smart_unicode()`` in almost all cases. The difference
is when the first argument is a `lazy translation`_ instance. While
``smart_unicode()`` preserves lazy translations, ``force_unicode()``
forces those objects to a Unicode string (causing the translation to
occur). Normally, you'll want to use ``smart_unicode()``. However,
@@ -132,11 +135,10 @@ for converting back and forth between Unicode and bytestrings.
* ``smart_str(s, encoding='utf-8', strings_only=False, errors='strict')``
is essentially the opposite of ``smart_unicode()``. It forces the first
argument to a bytestring. The ``strings_only`` parameter, if set to True,
will result in Python integers, booleans and ``None`` not being
converted to a string (they keep their original types). This is slightly
different semantics from Python's builtin ``str()`` function, but the
difference is needed in a few places within Django's internals.
argument to a bytestring. The ``strings_only`` parameter has the same
behaviour as for ``smart_unicode()`` and ``force_unicode()``. This is
slightly different semantics from Python's builtin ``str()`` function,
but the difference is needed in a few places within Django's internals.
Normally, you'll only need to use ``smart_unicode()``. Call it as early as
possible on any input data that might be either Unicode or a bytestring, and