1
0
mirror of https://github.com/django/django.git synced 2025-07-04 17:59:13 +00:00

newforms-admin: Merged from trunk up to [7377].

git-svn-id: http://code.djangoproject.com/svn/django/branches/newforms-admin@7378 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Joseph Kocherhans 2008-03-29 07:40:20 +00:00
parent 1ed686986b
commit 7822a0639f
33 changed files with 1129 additions and 723 deletions

View File

@ -114,7 +114,7 @@ SERVER_EMAIL = 'root@localhost'
SEND_BROKEN_LINK_EMAILS = False
# Database connection info.
DATABASE_ENGINE = '' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'ado_mssql'.
DATABASE_ENGINE = '' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = '' # Or path to database file if using sqlite3.
DATABASE_USER = '' # Not used with sqlite3.
DATABASE_PASSWORD = '' # Not used with sqlite3.
@ -287,7 +287,7 @@ SESSION_COOKIE_PATH = '/' # The path of the sessio
SESSION_SAVE_EVERY_REQUEST = False # Whether to save the session data on every request.
SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Whether sessions expire when a user closes his browser.
SESSION_ENGINE = 'django.contrib.sessions.backends.db' # The module to store session data
SESSION_FILE_PATH = None # Directory to store session files if using the file session module. If set to None the backend will use a sensible default.
SESSION_FILE_PATH = None # Directory to store session files if using the file session module. If None, the backend will use a sensible default.
#########
# CACHE #

File diff suppressed because it is too large Load Diff

View File

@ -1,21 +1,17 @@
# translation of djangojs.po to español
# translation of djangojs.po to
# Catalan translation for the django-admin JS files.
# translation of djangojs.po to catalan
# This file is distributed under the same license as the Django package.
#
# Antoni Aloy <antoni.aloy@trespams.com>, 2007.
msgid ""
msgstr ""
"Project-Id-Version: Django\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2007-05-20 18:25+0200\n"
"PO-Revision-Date: 2008-01-22 19:39+0100\n"
"Last-Translator: Marc Garcia <marc.garcia@accopensys.com>\n"
"Language-Team: español <ca@li.org>\n"
"POT-Creation-Date: 2007-02-15 01:00+0200\n"
"PO-Revision-Date: 2008-03-25 18:54+0100\n"
"Last-Translator: Django Catalan Group <django-cat@googlegroups.com>\n"
"Language-Team: Catalan <ca@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: KBabel 1.11.4\n"
"X-Generator: VIM 7.1\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
#: contrib/admin/media/js/SelectFilter2.js:33

View File

@ -22,7 +22,7 @@ def paginator_number(cl,i):
elif i == cl.page_num:
return mark_safe(u'<span class="this-page">%d</span> ' % (i+1))
else:
return mark_safe(u'<a href="%s"%s>%d</a> ' % (cl.get_query_string({PAGE_VAR: i}), (i == cl.paginator.pages-1 and ' class="end"' or ''), i+1))
return mark_safe(u'<a href="%s"%s>%d</a> ' % (cl.get_query_string({PAGE_VAR: i}), (i == cl.paginator.num_pages-1 and ' class="end"' or ''), i+1))
paginator_number = register.simple_tag(paginator_number)
def pagination(cl):
@ -37,8 +37,8 @@ def pagination(cl):
# If there are 10 or fewer pages, display links to every page.
# Otherwise, do some fancy
if paginator.pages <= 10:
page_range = range(paginator.pages)
if paginator.num_pages <= 10:
page_range = range(paginator.num_pages)
else:
# Insert "smart" pagination links, so that there are always ON_ENDS
# links at either end of the list of pages, and there are always
@ -50,12 +50,12 @@ def pagination(cl):
page_range.extend(range(page_num - ON_EACH_SIDE, page_num + 1))
else:
page_range.extend(range(0, page_num + 1))
if page_num < (paginator.pages - ON_EACH_SIDE - ON_ENDS - 1):
if page_num < (paginator.num_pages - ON_EACH_SIDE - ON_ENDS - 1):
page_range.extend(range(page_num + 1, page_num + ON_EACH_SIDE + 1))
page_range.append(DOT)
page_range.extend(range(paginator.pages - ON_ENDS, paginator.pages))
page_range.extend(range(paginator.num_pages - ON_ENDS, paginator.num_pages))
else:
page_range.extend(range(page_num + 1, paginator.pages))
page_range.extend(range(page_num + 1, paginator.num_pages))
need_show_all_link = cl.can_show_all and not cl.show_all and cl.multi_page
return {

View File

@ -3,7 +3,7 @@ from django.contrib.admin.filterspecs import FilterSpec
from django.contrib.admin.options import IncorrectLookupParameters
from django.contrib.admin.views.decorators import staff_member_required
from django.views.decorators.cache import never_cache
from django.core.paginator import ObjectPaginator, InvalidPage
from django.core.paginator import QuerySetPaginator, InvalidPage
from django.shortcuts import render_to_response
from django.db import models
from django.db.models.query import handle_legacy_orderlist, QuerySet
@ -177,11 +177,11 @@ class ChangeList(object):
return mark_safe('?' + '&amp;'.join([u'%s=%s' % (k, v) for k, v in p.items()]).replace(' ', '%20'))
def get_results(self, request):
paginator = ObjectPaginator(self.query_set, self.list_per_page)
paginator = QuerySetPaginator(self.query_set, self.lookup_opts.admin.list_per_page)
# Get the number of objects, with admin filters applied.
try:
result_count = paginator.hits
result_count = paginator.count
# Naked except! Because we don't have any other way of validating
# "params". They might be invalid if the keyword arguments are
# incorrect, or if the values are not in the correct type (which would
@ -206,7 +206,7 @@ class ChangeList(object):
result_list = list(self.query_set)
else:
try:
result_list = paginator.get_page(self.page_num)
result_list = paginator.page(self.page_num+1).object_list
except InvalidPage:
result_list = ()

View File

@ -294,8 +294,14 @@ def sql_model_create(model, style, known_models=set()):
style.SQL_COLTYPE(models.IntegerField().db_type()) + ' ' + \
style.SQL_KEYWORD('NULL'))
for field_constraints in opts.unique_together:
table_output.append(style.SQL_KEYWORD('UNIQUE') + ' (%s)' % \
constraint_output = [style.SQL_KEYWORD('UNIQUE')]
constraint_output.append('(%s)' % \
", ".join([style.SQL_FIELD(qn(opts.get_field(f).column)) for f in field_constraints]))
if opts.db_tablespace and connection.features.supports_tablespaces \
and connection.features.autoindexes_primary_keys:
constraint_output.append(connection.ops.tablespace_sql(
opts.db_tablespace, inline=True))
table_output.append(' '.join(constraint_output))
full_statement = [style.SQL_KEYWORD('CREATE TABLE') + ' ' + style.SQL_TABLE(qn(opts.db_table)) + ' (']
for i, line in enumerate(table_output): # Combine and add commas.

View File

@ -173,7 +173,7 @@ class ObjectPaginator(Paginator):
if self._count is None:
try:
self._count = self.object_list.count()
except AttributeError:
except TypeError:
self._count = len(self.object_list)
return self._count
count = property(_get_count)

View File

@ -1,112 +0,0 @@
"""
ADO MSSQL database backend for Django.
Requires adodbapi 2.0.1: http://adodbapi.sourceforge.net/
"""
from django.db.backends import BaseDatabaseWrapper, BaseDatabaseFeatures, BaseDatabaseOperations, util
try:
import adodbapi as Database
except ImportError, e:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("Error loading adodbapi module: %s" % e)
import datetime
try:
import mx
except ImportError:
mx = None
DatabaseError = Database.DatabaseError
IntegrityError = Database.IntegrityError
# We need to use a special Cursor class because adodbapi expects question-mark
# param style, but Django expects "%s". This cursor converts question marks to
# format-string style.
class Cursor(Database.Cursor):
def executeHelper(self, operation, isStoredProcedureCall, parameters=None):
if parameters is not None and "%s" in operation:
operation = operation.replace("%s", "?")
Database.Cursor.executeHelper(self, operation, isStoredProcedureCall, parameters)
class Connection(Database.Connection):
def cursor(self):
return Cursor(self)
Database.Connection = Connection
origCVtoP = Database.convertVariantToPython
def variantToPython(variant, adType):
if type(variant) == bool and adType == 11:
return variant # bool not 1/0
res = origCVtoP(variant, adType)
if mx is not None and type(res) == mx.DateTime.mxDateTime.DateTimeType:
# Convert ms.DateTime objects to Python datetime.datetime objects.
tv = list(res.tuple()[:7])
tv[-2] = int(tv[-2])
return datetime.datetime(*tuple(tv))
if type(res) == float and str(res)[-2:] == ".0":
return int(res) # If float but int, then int.
return res
Database.convertVariantToPython = variantToPython
class DatabaseFeatures(BaseDatabaseFeatures):
supports_tablespaces = True
class DatabaseOperations(BaseDatabaseOperations):
def date_extract_sql(self, lookup_type, field_name):
return "DATEPART(%s, %s)" % (lookup_type, field_name)
def date_trunc_sql(self, lookup_type, field_name):
if lookup_type == 'year':
return "Convert(datetime, Convert(varchar, DATEPART(year, %s)) + '/01/01')" % field_name
if lookup_type == 'month':
return "Convert(datetime, Convert(varchar, DATEPART(year, %s)) + '/' + Convert(varchar, DATEPART(month, %s)) + '/01')" % (field_name, field_name)
if lookup_type == 'day':
return "Convert(datetime, Convert(varchar(12), %s))" % field_name
def deferrable_sql(self):
return " DEFERRABLE INITIALLY DEFERRED"
def last_insert_id(self, cursor, table_name, pk_name):
cursor.execute("SELECT %s FROM %s WHERE %s = @@IDENTITY" % (pk_name, table_name, pk_name))
return cursor.fetchone()[0]
def quote_name(self, name):
if name.startswith('[') and name.endswith(']'):
return name # Quoting once is enough.
return '[%s]' % name
def random_function_sql(self):
return 'RAND()'
def tablespace_sql(self, tablespace, inline=False):
return "ON %s" % self.quote_name(tablespace)
class DatabaseWrapper(BaseDatabaseWrapper):
features = DatabaseFeatures()
ops = DatabaseOperations()
operators = {
'exact': '= %s',
'iexact': 'LIKE %s',
'contains': 'LIKE %s',
'icontains': 'LIKE %s',
'gt': '> %s',
'gte': '>= %s',
'lt': '< %s',
'lte': '<= %s',
'startswith': 'LIKE %s',
'endswith': 'LIKE %s',
'istartswith': 'LIKE %s',
'iendswith': 'LIKE %s',
}
def _cursor(self, settings):
if self.connection is None:
if settings.DATABASE_NAME == '' or settings.DATABASE_USER == '':
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("You need to specify both DATABASE_NAME and DATABASE_USER in your Django settings file.")
if not settings.DATABASE_HOST:
settings.DATABASE_HOST = "127.0.0.1"
# TODO: Handle DATABASE_PORT.
conn_string = "PROVIDER=SQLOLEDB;DATA SOURCE=%s;UID=%s;PWD=%s;DATABASE=%s" % (settings.DATABASE_HOST, settings.DATABASE_USER, settings.DATABASE_PASSWORD, settings.DATABASE_NAME)
self.connection = Database.connect(conn_string)
return self.connection.cursor()

View File

@ -1,2 +0,0 @@
def runshell():
raise NotImplementedError

View File

@ -1,25 +0,0 @@
DATA_TYPES = {
'AutoField': 'int IDENTITY (1, 1)',
'BooleanField': 'bit',
'CharField': 'varchar(%(max_length)s)',
'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
'DateField': 'smalldatetime',
'DateTimeField': 'smalldatetime',
'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
'FileField': 'varchar(%(max_length)s)',
'FilePathField': 'varchar(%(max_length)s)',
'FloatField': 'double precision',
'ImageField': 'varchar(%(max_length)s)',
'IntegerField': 'int',
'IPAddressField': 'char(15)',
'NullBooleanField': 'bit',
'OneToOneField': 'int',
'PhoneNumberField': 'varchar(20)',
'PositiveIntegerField': 'int CONSTRAINT [CK_int_pos_%(column)s] CHECK ([%(column)s] > 0)',
'PositiveSmallIntegerField': 'smallint CONSTRAINT [CK_smallint_pos_%(column)s] CHECK ([%(column)s] > 0)',
'SlugField': 'varchar(%(max_length)s)',
'SmallIntegerField': 'smallint',
'TextField': 'text',
'TimeField': 'time',
'USStateField': 'varchar(2)',
}

View File

@ -1,13 +0,0 @@
def get_table_list(cursor):
raise NotImplementedError
def get_table_description(cursor, table_name):
raise NotImplementedError
def get_relations(cursor, table_name):
raise NotImplementedError
def get_indexes(cursor, table_name):
raise NotImplementedError
DATA_TYPES_REVERSE = {}

View File

@ -17,7 +17,8 @@ except ImportError, e:
version = Database.version_info
if (version < (1,2,1) or (version[:3] == (1, 2, 1) and
(len(version) < 5 or version[3] != 'final' or version[4] < 2))):
raise ImportError("MySQLdb-1.2.1p2 or newer is required; you have %s" % Database.__version__)
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("MySQLdb-1.2.1p2 or newer is required; you have %s" % Database.__version__)
from MySQLdb.converters import conversions
from MySQLdb.constants import FIELD_TYPE

View File

@ -508,7 +508,7 @@ class ForeignKey(RelatedField, Field):
if 'edit_inline_type' in kwargs:
import warnings
warnings.warn("edit_inline_type is deprecated. Use edit_inline instead.")
warnings.warn("edit_inline_type is deprecated. Use edit_inline instead.", DeprecationWarning)
kwargs['edit_inline'] = kwargs.pop('edit_inline_type')
kwargs['rel'] = ManyToOneRel(to, to_field,
@ -610,7 +610,7 @@ class OneToOneField(RelatedField, IntegerField):
if 'edit_inline_type' in kwargs:
import warnings
warnings.warn("edit_inline_type is deprecated. Use edit_inline instead.")
warnings.warn("edit_inline_type is deprecated. Use edit_inline instead.", DeprecationWarning)
kwargs['edit_inline'] = kwargs.pop('edit_inline_type')
kwargs['rel'] = OneToOneRel(to, to_field,

View File

@ -74,8 +74,8 @@ def object_list(request, queryset, paginate_by=None, page=None,
'page': page_obj.number,
'next': page_obj.next_page_number(),
'previous': page_obj.previous_page_number(),
'last_on_page': page_obj.start_index(),
'first_on_page': page_obj.end_index(),
'first_on_page': page_obj.start_index(),
'last_on_page': page_obj.end_index(),
'pages': paginator.num_pages,
'hits': paginator.count,
'page_range': paginator.page_range,

View File

@ -82,6 +82,17 @@ function interpolate(fmt, obj, named) {
}
"""
PluralIdx = r"""
function pluralidx(n) {
var v=%s;
if (typeof(v) == 'boolean') {
return v ? 1 : 0;
} else {
return v;
}
}
"""
def null_javascript_catalog(request, domain=None, packages=None):
"""
Returns "identity" versions of the JavaScript i18n functions -- i.e.,
@ -154,7 +165,7 @@ def javascript_catalog(request, domain='djangojs', packages=None):
# this should actually be a compiled function of a typical plural-form:
# Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
plural = [el.strip() for el in plural.split(';') if el.strip().startswith('plural=')][0].split('=',1)[1]
src.append('function pluralidx(n) {\n return %s;\n}\n' % plural)
src.append(PluralIdx % plural)
else:
src.append(SimplePlural)
csrc = []

68
docs/Makefile Normal file
View File

@ -0,0 +1,68 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d _build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html web htmlhelp latex changes linkcheck
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " web to make files usable by Sphinx.web"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " changes to make an overview over all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
clean:
-rm -rf _build/*
html:
mkdir -p _build/html _build/doctrees
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) _build/html
@echo
@echo "Build finished. The HTML pages are in _build/html."
web:
mkdir -p _build/web _build/doctrees
$(SPHINXBUILD) -b web $(ALLSPHINXOPTS) _build/web
@echo
@echo "Build finished; now you can run"
@echo " python -m sphinx.web _build/web"
@echo "to start the server."
htmlhelp:
mkdir -p _build/htmlhelp _build/doctrees
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) _build/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in _build/htmlhelp."
latex:
mkdir -p _build/latex _build/doctrees
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) _build/latex
@echo
@echo "Build finished; the LaTeX files are in _build/latex."
@echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
"run these through (pdf)latex."
changes:
mkdir -p _build/changes _build/doctrees
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) _build/changes
@echo
@echo "The overview file is in _build/changes."
linkcheck:
mkdir -p _build/linkcheck _build/doctrees
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) _build/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in _build/linkcheck/output.txt."

132
docs/conf.py Normal file
View File

@ -0,0 +1,132 @@
# -*- coding: utf-8 -*-
#
# Django documentation build configuration file, created by
# sphinx-quickstart on Thu Mar 27 09:06:53 2008.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleable (module imports are okay, they're removed automatically).
#
# All configuration values have a default value; values that are commented out
# serve to show the default value.
import sys
# If your extensions are in another directory, add it here.
#sys.path.append('some/directory')
# General configuration
# ---------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
#extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = []
# The suffix of source filenames.
source_suffix = '.txt'
# The master toctree document.
master_doc = 'index'
# General substitutions.
project = 'Django'
copyright = '2008, Django Software Foundation'
# The default replacements for |version| and |release|, also used in various
# other places throughout the built documents.
#
# The short X.Y version.
version = 'SVN'
# The full version, including alpha/beta/rc tags.
release = version
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
add_module_names = False
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# Options for HTML output
# -----------------------
# The style sheet to use for HTML and HTML Help pages. A file of that name
# must exist either in Sphinx' static/ path, or in one of the custom paths
# given in html_static_path.
html_style = 'default.css'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
html_use_smartypants = True
# Content template for the index page.
#html_index = ''
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_use_modindex = True
# If true, the reST sources are included in the HTML build as _sources/<name>.
html_copy_source = True
# Output file base name for HTML help builder.
htmlhelp_basename = 'Djangodoc'
# Options for LaTeX output
# ------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, document class [howto/manual]).
#latex_documents = []
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True

View File

@ -1306,9 +1306,6 @@ SQL equivalents::
Using raw strings (e.g., ``r'foo'`` instead of ``'foo'``) for passing in the
regular expression syntax is recommended.
Regular expression matching is not supported on the ``ado_mssql`` backend.
It will raise a ``NotImplementedError`` at runtime.
iregex
~~~~~~

View File

@ -789,7 +789,7 @@ JavaScript that uses strings from different applications.
You can make the view dynamic by putting the packages into the URL pattern::
urlpatterns = patterns('',
(r'^jsi18n/(?P<packages>\S+?)/$, 'django.views.i18n.javascript_catalog'),
(r'^jsi18n/(?P<packages>\S+?)/$', 'django.views.i18n.javascript_catalog'),
)
With this, you specify the packages as a list of package names delimited by '+'
@ -811,24 +811,47 @@ interface to access it::
document.write(gettext('this is to be translated'));
There even is a ``ungettext`` interface and a string interpolation function::
There is also an ``ngettext`` interface::
var object_cnt = 1 // or 0, or 2, or 3, ...
s = ngettext('literal for the singular case',
'literal for the plural case', object_cnt);
and even a string interpolation function::
function interpolate(fmt, obj, named);
The interpolation syntax is borrowed from Python, so the ``interpolate``
function supports both positional and named interpolation:
* Positional interpolation: ``obj`` contains a JavaScript Array object
whose elements values are then sequentially interpolated in their
corresponding ``fmt`` placeholders in the same order they appear.
For example::
fmts = ngettext('There is %s object. Remaining: %s',
'There are %s objects. Remaining: %s', 11);
s = interpolate(fmts, [11, 20]);
// s is 'There are 11 objects. Remaining: 20'
* Named interpolation: This mode is selected by passing the optional
boolean ``named`` parameter as true. ``obj`` contains a JavaScript
object or associative array. For example::
d = {
count: 10
total: 50
};
s = interpolate(ungettext('this is %(count)s object', 'this are %(count)s objects', d.count), d);
The ``interpolate`` function supports both positional interpolation and named
interpolation. So the above could have been written as::
fmts = ngettext('Total: %(total)s, there is %(count)s object',
'there are %(count)s of a total of %(total)s objects', d.count);
s = interpolate(fmts, d, true);
s = interpolate(ungettext('this is %s object', 'this are %s objects', 11), [11]);
The interpolation syntax is borrowed from Python. You shouldn't go over the top
with string interpolation, though: this is still JavaScript, so the code will
have to do repeated regular-expression substitutions. This isn't as fast as
string interpolation in Python, so keep it to those cases where you really
need it (for example, in conjunction with ``ungettext`` to produce proper
pluralizations).
You shouldn't go over the top with string interpolation, though: this is still
JavaScript, so the code has to make repeated regular-expression substitutions.
This isn't as fast as string interpolation in Python, so keep it to those
cases where you really need it (for example, in conjunction with ``ngettext``
to produce proper pluralizations).
Creating JavaScript translation catalogs
----------------------------------------

128
docs/index.txt Normal file
View File

@ -0,0 +1,128 @@
====================
Django Documentation
====================
The essential documentation
===========================
If you're new to Django, make sure to read the following documentation in
order.. The rest (in the "reference" section below) can be ready in any order as
you need various functionality.
.. toctree::
:maxdepth: 1
overview
install
tutorial01
tutorial02
tutorial03
tutorial04
faq
documentation
Reference
=========
.. toctree::
:maxdepth: 1
django-admin
model-api
db-api
transactions
templates
templates_python
newforms
modelforms
testing
sessions
cache
settings
url_dispatch
request_response
generic_views
authentication
shortcuts
unicode
pagination
serialization
i18n
middleware
custom_model_fields
databases
``django.contrib`` add-ons
--------------------------
.. toctree::
:maxdepth: 1
add_ons
contenttypes
csrf
databrowse
flatpages
form_preview
form_wizard
localflavor
redirects
sites
sitemaps
syndication_feeds
webdesign
Deployment
----------
.. toctree::
:maxdepth: 1
modpython
fastcgi
Solving specific problems
-------------------------
.. toctree::
:maxdepth: 1
apache_auth
static_files
email
legacy_databases
outputting_pdf
outputting_csv
Et cetera
---------
.. toctree::
:maxdepth: 1
design_philosophies
contributing
admin_css
api_stability
Release notes
-------------
.. toctree::
:maxdepth: 1
release_notes_0.96
release_notes_0.95
Also see the list of `backwards-incompatible changes`__ for changes made between
releases.
__ http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

View File

@ -172,11 +172,11 @@ Installing the development version
If you decide to use the latest development version of Django,
you'll want to pay close attention to `the development timeline`_,
and you'll want to keep an eye on `the list of
backwards-incompatible changes`_; this will help you stay on top
backwards-incompatible changes`_. This will help you stay on top
of any new features you might want to use, as well as any changes
you'll need to make to your code when updating your copy of Django
(for stable releases, any necessary changes are documented in the
release notes).
you'll need to make to your code when updating your copy of Django.
(For stable releases, any necessary changes are documented in the
release notes.)
.. _the development timeline: http://code.djangoproject.com/timeline
.. _the list of backwards-incompatible changes: http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges

View File

@ -236,7 +236,7 @@ works exactly the same way as any other ``newforms`` form. For
example, the ``is_valid()`` method is used to check for validity, the
``is_multipart()`` method is used to determine whether a form requires
multipart file upload (and hence whether ``request.FILES`` must be
passed to the form), etc.; see `the standard newforms documentation`_
passed to the form), etc. See `the standard newforms documentation`_
for more information.
.. _the standard newforms documentation: ../newforms/

View File

@ -143,14 +143,13 @@ All attributes except ``session`` should be considered read-only.
``urlconf``
Not defined by Django itself, but will be read if other code
(e.g., a custom middleware class) sets it; when present, this will
be used as the root URLConf for the current request, overriding
(e.g., a custom middleware class) sets it. When present, this will
be used as the root URLconf for the current request, overriding
the ``ROOT_URLCONF`` setting. See `How Django processes a
request`_ for details.
.. _How Django processes a request: ../url_dispatch/#how-django-processes-a-request
Methods
-------
@ -202,9 +201,9 @@ Methods
``is_ajax()``
**New in Django development version**
Returns ``True`` if the request was made via an XMLHttpRequest by checking
the ``HTTP_X_REQUESTED_WITH`` header for the string *'XMLHttpRequest'*. The
following major Javascript libraries all send this header:
Returns ``True`` if the request was made via an ``XMLHttpRequest``, by checking
the ``HTTP_X_REQUESTED_WITH`` header for the string ``'XMLHttpRequest'``. The
following major JavaScript libraries all send this header:
* jQuery
* Dojo
@ -213,8 +212,8 @@ Methods
* Prototype
* YUI
If you write your own XMLHttpRequest call (on the browser side), you will
have to set this header manually to use this method.
If you write your own XMLHttpRequest call (on the browser side), you'll
have to set this header manually if you want ``is_ajax()`` to work.
QueryDict objects
-----------------

View File

@ -279,7 +279,7 @@ Default: ``''`` (Empty string)
The database backend to use. The build-in database backends are
``'postgresql_psycopg2'``, ``'postgresql'``, ``'mysql'``, ``'mysql_old'``,
``'sqlite3'``, ``'oracle'``, or ``'ado_mssql'``.
``'sqlite3'`` and ``'oracle'``.
In the Django development version, you can use a database backend that doesn't
ship with Django by setting ``DATABASE_ENGINE`` to a fully-qualified path (i.e.

View File

@ -250,7 +250,7 @@ request to the URL ``/rss/beats/0613/``:
will be an empty list. In our example, ``len(bits) != 1`` and an
``ObjectDoesNotExist`` exception will be raised, so ``/rss/beats/`` will
generate a 404 page. But you can handle this case however you like. For
example you could generate a combined feed for all beats.
example, you could generate a combined feed for all beats.
* To generate the feed's ``<title>``, ``<link>`` and ``<description>``,
Django uses the ``title()``, ``link()`` and ``description()`` methods. In

View File

@ -80,7 +80,7 @@ read Python's official documentation for the details.
.. admonition:: What's a **docstring**?
A good explanation of docstrings (and some guidelines for using them
effectively) can be found in :PEP:`257`:
effectively) can be found in :pep:`257`:
A docstring is a string literal that occurs as the first statement in
a module, function, class, or method definition. Such a docstring

View File

@ -39,7 +39,7 @@ A quick rundown:
Django; it's just good Web development practice.
* ``forloop.counter`` indicates how many times the ``for`` tag has
gone through its loop; for more information, see `the
gone through its loop. For more information, see `the
documentation for the "for" tag`_.
.. _the documentation for the "for" tag: ../templates/#for

View File

@ -32,7 +32,7 @@ How Django processes a request
When a user requests a page from your Django-powered site, this is the
algorithm the system follows to determine which Python code to execute:
1. Django determines the root URLConf module to use; ordinarily
1. Django determines the root URLconf module to use. Ordinarily,
this is the value of the ``ROOT_URLCONF`` setting in your
`settings file`_, but if the incoming ``HttpRequest`` object
has an attribute called ``urlconf``, its value will be used in

View File

@ -1135,29 +1135,39 @@ u''
# FilePathField ###############################################################
>>> def fix_os_paths(x):
... if isinstance(x, basestring):
... return x.replace('\\', '/')
... elif isinstance(x, tuple):
... return tuple(fix_os_paths(list(x)))
... elif isinstance(x, list):
... return [fix_os_paths(y) for y in x]
... else:
... return x
...
>>> import os
>>> from django import newforms as forms
>>> path = forms.__file__
>>> path = os.path.dirname(path) + '/'
>>> path
>>> fix_os_paths(path)
'.../django/newforms/'
>>> f = forms.FilePathField(path=path)
>>> f.choices.sort()
>>> f.choices
>>> fix_os_paths(f.choices)
[('.../django/newforms/__init__.py', '__init__.py'), ('.../django/newforms/__init__.pyc', '__init__.pyc'), ('.../django/newforms/fields.py', 'fields.py'), ('.../django/newforms/fields.pyc', 'fields.pyc'), ('.../django/newforms/forms.py', 'forms.py'), ('.../django/newforms/forms.pyc', 'forms.pyc'), ('.../django/newforms/models.py', 'models.py'), ('.../django/newforms/models.pyc', 'models.pyc'), ('.../django/newforms/util.py', 'util.py'), ('.../django/newforms/util.pyc', 'util.pyc'), ('.../django/newforms/widgets.py', 'widgets.py'), ('.../django/newforms/widgets.pyc', 'widgets.pyc')]
>>> f.clean('fields.py')
Traceback (most recent call last):
...
ValidationError: [u'Select a valid choice. That choice is not one of the available choices.']
>>> f.clean(path + 'fields.py')
>>> fix_os_paths(f.clean(path + 'fields.py'))
u'.../django/newforms/fields.py'
>>> f = forms.FilePathField(path=path, match='^.*?\.py$')
>>> f.choices.sort()
>>> f.choices
>>> fix_os_paths(f.choices)
[('.../django/newforms/__init__.py', '__init__.py'), ('.../django/newforms/fields.py', 'fields.py'), ('.../django/newforms/forms.py', 'forms.py'), ('.../django/newforms/models.py', 'models.py'), ('.../django/newforms/util.py', 'util.py'), ('.../django/newforms/widgets.py', 'widgets.py')]
>>> f = forms.FilePathField(path=path, recursive=True, match='^.*?\.py$')
>>> f.choices.sort()
>>> f.choices
>>> fix_os_paths(f.choices)
[('.../django/newforms/__init__.py', '__init__.py'), ('.../django/newforms/extras/__init__.py', 'extras/__init__.py'), ('.../django/newforms/extras/widgets.py', 'extras/widgets.py'), ('.../django/newforms/fields.py', 'fields.py'), ('.../django/newforms/forms.py', 'forms.py'), ('.../django/newforms/models.py', 'models.py'), ('.../django/newforms/util.py', 'util.py'), ('.../django/newforms/widgets.py', 'widgets.py')]
# SplitDateTimeField ##########################################################

View File

@ -26,6 +26,9 @@ class Movie(models.Model):
movie_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=60)
class Party(models.Model):
when = models.DateField()
__test__ = {'API_TESTS': """
(NOTE: Part of the regression test here is merely parsing the model
declaration. The verbose_name, in particular, did not always work.)
@ -51,5 +54,19 @@ u''
>>> len(a4.article_text)
5000
# #659 regression test
>>> import datetime
>>> p = Party.objects.create(when = datetime.datetime(1999, 12, 31))
>>> p = Party.objects.create(when = datetime.datetime(1998, 12, 31))
>>> p = Party.objects.create(when = datetime.datetime(1999, 1, 1))
>>> [p.when for p in Party.objects.filter(when__month = 2)]
[]
>>> [p.when for p in Party.objects.filter(when__month = 1)]
[datetime.date(1999, 1, 1)]
>>> [p.when for p in Party.objects.filter(when__month = 12)]
[datetime.date(1999, 12, 31), datetime.date(1998, 12, 31)]
>>> [p.when for p in Party.objects.filter(when__year = 1998)]
[datetime.date(1998, 12, 31)]
"""
}