Remove some left overs from recent Google App Engine 1.2.5 update.
--- a/thirdparty/google_appengine/lib/django/MANIFEST.in Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,10 +0,0 @@
-include AUTHORS
-include INSTALL
-include LICENSE
-recursive-include docs *
-recursive-include scripts *
-recursive-include django/conf/locale *
-recursive-include django/contrib/admin/templates *
-recursive-include django/contrib/admin/media *
-recursive-include django/contrib/comments/templates *
-recursive-include django/contrib/sitemaps/templates *
--- a/thirdparty/google_appengine/lib/django/django/contrib/flatpages/README.TXT Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,8 +0,0 @@
-This is an optional add-on app, flatpages.
-
-For full documentation, see either of these:
-
- * The file docs/flatpages.txt in the Django distribution
- * http://www.djangoproject.com/documentation/flatpages/ on the Web
-
-Both have identical content.
--- a/thirdparty/google_appengine/lib/django/django/contrib/formtools/templates/formtools/form.html Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,15 +0,0 @@
-{% extends "base.html" %}
-
-{% block content %}
-
-{% if form.errors %}<h1>Please correct the following errors</h1>{% else %}<h1>Submit</h1>{% endif %}
-
-<form action="" method="post">
-<table>
-{{ form }}
-</table>
-<input type="hidden" name="{{ stage_field }}" value="1" />
-<p><input type="submit" value="Preview" /></p>
-</form>
-
-{% endblock %}
--- a/thirdparty/google_appengine/lib/django/django/contrib/formtools/templates/formtools/preview.html Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,36 +0,0 @@
-{% extends "base.html" %}
-
-{% block content %}
-
-<h1>Preview your submission</h1>
-
-<table>
-{% for field in form %}
-<tr>
-<th>{{ field.label }}:</th>
-<td>{{ field.data|escape }}</td>
-</tr>
-{% endfor %}
-</table>
-
-<p>Security hash: {{ hash_value }}</p>
-
-<form action="" method="post">
-{% for field in form %}{{ field.as_hidden }}
-{% endfor %}
-<input type="hidden" name="{{ stage_field }}" value="2" />
-<input type="hidden" name="{{ hash_field }}" value="{{ hash_value }}" />
-<p><input type="submit" value="Submit" /></p>
-</form>
-
-<h1>Or edit it again</h1>
-
-<form action="" method="post">
-<table>
-{{ form }}
-</table>
-<input type="hidden" name="{{ stage_field }}" value="1" />
-<p><input type="submit" value="Preview" /></p>
-</form>
-
-{% endblock %}
--- a/thirdparty/google_appengine/lib/django/django/contrib/redirects/README.TXT Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,8 +0,0 @@
-This is an optional add-on app, redirects.
-
-For full documentation, see either of these:
-
- * The file django/docs/redirects.txt in the Django distribution
- * http://www.djangoproject.com/documentation/redirects/ on the Web
-
-Both have identical content.
\ No newline at end of file
--- a/thirdparty/google_appengine/lib/django/django/dispatch/license.txt Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,34 +0,0 @@
-PyDispatcher License
-
- Copyright (c) 2001-2003, Patrick K. O'Brien and Contributors
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
-
- Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the following
- disclaimer in the documentation and/or other materials
- provided with the distribution.
-
- The name of Patrick K. O'Brien, or the name of any Contributor,
- may not be used to endorse or promote products derived from this
- software without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
- OF THE POSSIBILITY OF SUCH DAMAGE.
-
--- a/thirdparty/google_appengine/lib/django/django/utils/simplejson/LICENSE.txt Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,20 +0,0 @@
-simplejson 1.5
-Copyright (c) 2006 Bob Ippolito
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of
-this software and associated documentation files (the "Software"), to deal in
-the Software without restriction, including without limitation the rights to
-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-of the Software, and to permit persons to whom the Software is furnished to do
-so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
--- a/thirdparty/google_appengine/lib/django/examples/hello/urls.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,10 +0,0 @@
-from django.conf.urls.defaults import *
-
-urlpatterns = patterns('examples.hello.views',
- (r'^html/$', 'hello_html'),
- (r'^text/$', 'hello_text'),
- (r'^write/$', 'hello_write'),
- (r'^metadata/$', 'metadata'),
- (r'^getdata/$', 'get_data'),
- (r'^postdata/$', 'post_data'),
-)
--- a/thirdparty/google_appengine/lib/django/examples/hello/views.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,55 +0,0 @@
-from django.http import HttpResponse
-from django.utils.html import escape
-
-def hello_html(request):
- "This view is a basic 'hello world' example in HTML."
- return HttpResponse('<h1>Hello, world.</h1>')
-
-def hello_text(request):
- "This view is a basic 'hello world' example in plain text."
- return HttpResponse('Hello, world.', mimetype='text/plain')
-
-def hello_write(request):
- "This view demonstrates how an HttpResponse object has a write() method."
- r = HttpResponse()
- r.write("<p>Here's a paragraph.</p>")
- r.write("<p>Here's another paragraph.</p>")
- return r
-
-def metadata(request):
- "This view demonstrates how to retrieve request metadata, such as HTTP headers."
- r = HttpResponse('<h1>All about you</h1>')
- r.write("<p>Here's all known metadata about your request, according to <code>request.META</code>:</p>")
- r.write('<table>')
- meta_items = request.META.items()
- meta_items.sort()
- for k, v in meta_items:
- r.write('<tr><th>%s</th><td>%r</td></tr>' % (k, v))
- r.write('</table>')
- return r
-
-def get_data(request):
- "This view demonstrates how to retrieve GET data."
- r = HttpResponse()
- if request.GET:
- r.write('<p>GET data found! Here it is:</p>')
- r.write('<ul>%s</ul>' % ''.join(['<li><strong>%s:</strong> %r</li>' % (escape(k), escape(v)) for k, v in request.GET.items()]))
- r.write('<form action="" method="get">')
- r.write('<p>First name: <input type="text" name="first_name"></p>')
- r.write('<p>Last name: <input type="text" name="last_name"></p>')
- r.write('<p><input type="submit" value="Submit"></p>')
- r.write('</form>')
- return r
-
-def post_data(request):
- "This view demonstrates how to retrieve POST data."
- r = HttpResponse()
- if request.POST:
- r.write('<p>POST data found! Here it is:</p>')
- r.write('<ul>%s</ul>' % ''.join(['<li><strong>%s:</strong> %r</li>' % (escape(k), escape(v)) for k, v in request.POST.items()]))
- r.write('<form action="" method="post">')
- r.write('<p>First name: <input type="text" name="first_name"></p>')
- r.write('<p>Last name: <input type="text" name="last_name"></p>')
- r.write('<p><input type="submit" value="Submit"></p>')
- r.write('</form>')
- return r
--- a/thirdparty/google_appengine/lib/django/examples/manage.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,11 +0,0 @@
-#!/usr/bin/env python
-from django.core.management import execute_manager
-try:
- import settings # Assumed to be in the same directory.
-except ImportError:
- import sys
- sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
- sys.exit(1)
-
-if __name__ == "__main__":
- execute_manager(settings)
--- a/thirdparty/google_appengine/lib/django/examples/settings.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,5 +0,0 @@
-# Django settings for the example project.
-
-DEBUG = True
-TEMPLATE_DEBUG = DEBUG
-ROOT_URLCONF = 'examples.urls'
--- a/thirdparty/google_appengine/lib/django/examples/urls.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,6 +0,0 @@
-from django.conf.urls.defaults import *
-
-urlpatterns = patterns('',
- (r'^$', 'examples.views.index'),
- (r'^hello/', include('examples.hello.urls')),
-)
--- a/thirdparty/google_appengine/lib/django/examples/views.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,12 +0,0 @@
-from django import http
-
-def index(request):
- r = http.HttpResponse('<h1>Django examples</h1><ul>')
- r.write('<li><a href="hello/html/">Hello world (HTML)</a></li>')
- r.write('<li><a href="hello/text/">Hello world (text)</a></li>')
- r.write('<li><a href="hello/write/">HttpResponse objects are file-like objects</a></li>')
- r.write('<li><a href="hello/metadata/">Displaying request metadata</a></li>')
- r.write('<li><a href="hello/getdata/">Displaying GET data</a></li>')
- r.write('<li><a href="hello/postdata/">Displaying POST data</a></li>')
- r.write('</ul>')
- return r
--- a/thirdparty/google_appengine/lib/django/extras/README.TXT Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,1 +0,0 @@
-This directory contains extra stuff that can improve your Django experience.
--- a/thirdparty/google_appengine/lib/django/extras/django_bash_completion Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,159 +0,0 @@
-# #########################################################################
-# This bash script adds tab-completion feature to django-admin.py and
-# manage.py.
-#
-# Testing it out without installing
-# =================================
-#
-# To test out the completion without "installing" this, just run this file
-# directly, like so:
-#
-# . ~/path/to/django_bash_completion
-#
-# Note: There's a dot ('.') at the beginning of that command.
-#
-# After you do that, tab completion will immediately be made available in your
-# current Bash shell. But it won't be available next time you log in.
-#
-# Installing
-# ==========
-#
-# To install this, point to this file from your .bash_profile, like so:
-#
-# . ~/path/to/django_bash_completion
-#
-# Do the same in your .bashrc if .bashrc doesn't invoke .bash_profile.
-#
-# Settings will take effect the next time you log in.
-#
-# Uninstalling
-# ============
-#
-# To uninstall, just remove the line from your .bash_profile and .bashrc.
-
-# Enable extended pattern matching operators.
-shopt -s extglob
-
-_django_completion()
-{
- local cur prev opts actions action_shell_opts action_runfcgi_opts
- COMPREPLY=()
- cur="${COMP_WORDS[COMP_CWORD]}"
- prev="${COMP_WORDS[COMP_CWORD-1]}"
-
- # Standalone options
- opts="--help --settings --pythonpath --version"
- # Actions
- actions="adminindex createcachetable dbshell diffsettings \
- inspectdb install reset runfcgi runserver \
- shell sql sqlall sqlclear sqlindexes sqlinitialdata \
- sqlreset sqlsequencereset startapp startproject \
- syncdb validate"
- # Action's options
- action_shell_opts="--plain"
- action_runfcgi_opts="host port socket method maxspare minspare maxchildren daemonize pidfile workdir"
-
- if [[ # django-admin.py, ./manage, manage.py
- ( ${COMP_CWORD} -eq 1 &&
- ( ${COMP_WORDS[0]} == django-admin.py ||
- ${COMP_WORDS[0]} == ./manage.py ||
- ${COMP_WORDS[0]} == manage.py ) )
- ||
- # python manage.py, /some/path/python manage.py (if manage.py exists)
- ( ${COMP_CWORD} -eq 2 &&
- ( $( basename ${COMP_WORDS[0]} ) == python?([1-9]\.[0-9]) ) &&
- ( $( basename ${COMP_WORDS[1]} ) == manage.py) &&
- ( -r ${COMP_WORDS[1]} ) )
- ||
- ( ${COMP_CWORD} -eq 2 &&
- ( $( basename ${COMP_WORDS[0]} ) == python?([1-9]\.[0-9]) ) &&
- ( $( basename ${COMP_WORDS[1]} ) == django-admin.py) &&
- ( -r ${COMP_WORDS[1]} ) ) ]] ; then
-
- case ${cur} in
- -*)
- COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
- action=$COMPREPLY
- return 0
- ;;
- *)
- COMPREPLY=( $(compgen -W "${actions}" -- ${cur}) )
- action=$COMPREPLY
- return 0
- ;;
- esac
- else
- case ${prev} in
- adminindex|install|reset| \
- sql|sqlall|sqlclear|sqlindexes| \
- sqlinitialdata|sqlreset|sqlsequencereset)
- # App completion
- settings=""
- # If settings.py in the PWD, use that
- if [ -e settings.py ] ; then
- settings="$PWD/settings.py"
- else
- # Use the ENV variable if it is set
- if [ $DJANGO_SETTINGS_MODULE ] ; then
- settings=$DJANGO_SETTINGS_MODULE
- fi
- fi
- # Couldn't find settings so return nothing
- if [ -z $settings ] ; then
- COMPREPLY=()
- # Otherwise inspect settings.py file
- else
- apps=`sed -n "/INSTALLED_APPS = (/,/)/p" $settings | \
- grep -v "django.contrib" |
- sed -n "s/^[ ]*'\(.*\.\)*\(.*\)'.*$/\2 /pg" | \
- tr -d "\n"`
- COMPREPLY=( $(compgen -W "${apps}" -- ${cur}) )
- fi
- return 0
- ;;
-
- createcachetable|dbshell|diffsettings| \
- inspectdb|runserver|startapp|startproject|syncdb| \
- validate)
- COMPREPLY=()
- return 0
- ;;
- shell)
- COMPREPLY=( $(compgen -W "$action_shell_opts" -- ${cur}) )
- return 0
- ;;
- runfcgi)
- COMPREPLY=( $(compgen -W "$action_runfcgi_opts" -- ${cur}) )
- return 0
- ;;
- host*|port*|socket*|method*|maxspare*|minspare*|maxchildren*|daemonize*|pidfile*|workdir*)
- if [ "$action" == "runfcgi" ] ; then
- COMPREPLY=( $(compgen -W "$action_runfcgi_opts" -- ${cur}) )
- return 0
- fi
- return 0
- ;;
- *)
- #COMPREPLY=( $(compgen -W "auth core" -- ${cur}) )
- COMPREPLY=()
- return 0
- ;;
- esac
- fi
-}
-
-complete -F _django_completion django-admin.py manage.py
-
-# Support for multiple interpreters.
-unset pythons
-if command -v whereis &>/dev/null; then
- python_interpreters=$(whereis python | cut -d " " -f 2-)
- for python in $python_interpreters; do
- pythons="${pythons} $(basename $python)"
- done
- pythons=$(echo $pythons | tr " " "\n" | sort -u | tr "\n" " ")
-else
- pythons=python
-fi
-
-complete -F _django_completion -o default $pythons
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/basic/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,367 +0,0 @@
-"""
-1. Bare-bones model
-
-This is a basic model with only two non-primary-key fields.
-"""
-
-from django.db import models
-
-class Article(models.Model):
- headline = models.CharField(maxlength=100, default='Default headline')
- pub_date = models.DateTimeField()
-
- class Meta:
- ordering = ('pub_date','headline')
-
- def __str__(self):
- return self.headline
-
-__test__ = {'API_TESTS': """
-# No articles are in the system yet.
->>> Article.objects.all()
-[]
-
-# Create an Article.
->>> from datetime import datetime
->>> a = Article(id=None, headline='Area man programs in Python', pub_date=datetime(2005, 7, 28))
-
-# Save it into the database. You have to call save() explicitly.
->>> a.save()
-
-# Now it has an ID. Note it's a long integer, as designated by the trailing "L".
->>> a.id
-1L
-
-# Access database columns via Python attributes.
->>> a.headline
-'Area man programs in Python'
->>> a.pub_date
-datetime.datetime(2005, 7, 28, 0, 0)
-
-# Change values by changing the attributes, then calling save().
->>> a.headline = 'Area woman programs in Python'
->>> a.save()
-
-# Article.objects.all() returns all the articles in the database.
->>> Article.objects.all()
-[<Article: Area woman programs in Python>]
-
-# Django provides a rich database lookup API.
->>> Article.objects.get(id__exact=1)
-<Article: Area woman programs in Python>
->>> Article.objects.get(headline__startswith='Area woman')
-<Article: Area woman programs in Python>
->>> Article.objects.get(pub_date__year=2005)
-<Article: Area woman programs in Python>
->>> Article.objects.get(pub_date__year=2005, pub_date__month=7)
-<Article: Area woman programs in Python>
->>> Article.objects.get(pub_date__year=2005, pub_date__month=7, pub_date__day=28)
-<Article: Area woman programs in Python>
-
-# The "__exact" lookup type can be omitted, as a shortcut.
->>> Article.objects.get(id=1)
-<Article: Area woman programs in Python>
->>> Article.objects.get(headline='Area woman programs in Python')
-<Article: Area woman programs in Python>
-
->>> Article.objects.filter(pub_date__year=2005)
-[<Article: Area woman programs in Python>]
->>> Article.objects.filter(pub_date__year=2004)
-[]
->>> Article.objects.filter(pub_date__year=2005, pub_date__month=7)
-[<Article: Area woman programs in Python>]
-
-# Django raises an Article.DoesNotExist exception for get() if the parameters
-# don't match any object.
->>> Article.objects.get(id__exact=2)
-Traceback (most recent call last):
- ...
-DoesNotExist: Article matching query does not exist.
-
->>> Article.objects.get(pub_date__year=2005, pub_date__month=8)
-Traceback (most recent call last):
- ...
-DoesNotExist: Article matching query does not exist.
-
-# Lookup by a primary key is the most common case, so Django provides a
-# shortcut for primary-key exact lookups.
-# The following is identical to articles.get(id=1).
->>> Article.objects.get(pk=1)
-<Article: Area woman programs in Python>
-
-# pk can be used as a shortcut for the primary key name in any query
->>> Article.objects.filter(pk__in=[1])
-[<Article: Area woman programs in Python>]
-
-# Model instances of the same type and same ID are considered equal.
->>> a = Article.objects.get(pk=1)
->>> b = Article.objects.get(pk=1)
->>> a == b
-True
-
-# You can initialize a model instance using positional arguments, which should
-# match the field order as defined in the model.
->>> a2 = Article(None, 'Second article', datetime(2005, 7, 29))
->>> a2.save()
->>> a2.id
-2L
->>> a2.headline
-'Second article'
->>> a2.pub_date
-datetime.datetime(2005, 7, 29, 0, 0)
-
-# ...or, you can use keyword arguments.
->>> a3 = Article(id=None, headline='Third article', pub_date=datetime(2005, 7, 30))
->>> a3.save()
->>> a3.id
-3L
->>> a3.headline
-'Third article'
->>> a3.pub_date
-datetime.datetime(2005, 7, 30, 0, 0)
-
-# You can also mix and match position and keyword arguments, but be sure not to
-# duplicate field information.
->>> a4 = Article(None, 'Fourth article', pub_date=datetime(2005, 7, 31))
->>> a4.save()
->>> a4.headline
-'Fourth article'
-
-# Don't use invalid keyword arguments.
->>> a5 = Article(id=None, headline='Invalid', pub_date=datetime(2005, 7, 31), foo='bar')
-Traceback (most recent call last):
- ...
-TypeError: 'foo' is an invalid keyword argument for this function
-
-# You can leave off the value for an AutoField when creating an object, because
-# it'll get filled in automatically when you save().
->>> a5 = Article(headline='Article 6', pub_date=datetime(2005, 7, 31))
->>> a5.save()
->>> a5.id
-5L
->>> a5.headline
-'Article 6'
-
-# If you leave off a field with "default" set, Django will use the default.
->>> a6 = Article(pub_date=datetime(2005, 7, 31))
->>> a6.save()
->>> a6.headline
-'Default headline'
-
-# For DateTimeFields, Django saves as much precision (in seconds) as you
-# give it.
->>> a7 = Article(headline='Article 7', pub_date=datetime(2005, 7, 31, 12, 30))
->>> a7.save()
->>> Article.objects.get(id__exact=7).pub_date
-datetime.datetime(2005, 7, 31, 12, 30)
-
->>> a8 = Article(headline='Article 8', pub_date=datetime(2005, 7, 31, 12, 30, 45))
->>> a8.save()
->>> Article.objects.get(id__exact=8).pub_date
-datetime.datetime(2005, 7, 31, 12, 30, 45)
->>> a8.id
-8L
-
-# Saving an object again doesn't create a new object -- it just saves the old one.
->>> a8.save()
->>> a8.id
-8L
->>> a8.headline = 'Updated article 8'
->>> a8.save()
->>> a8.id
-8L
-
->>> a7 == a8
-False
->>> a8 == Article.objects.get(id__exact=8)
-True
->>> a7 != a8
-True
->>> Article.objects.get(id__exact=8) != Article.objects.get(id__exact=7)
-True
->>> Article.objects.get(id__exact=8) == Article.objects.get(id__exact=7)
-False
-
-# dates() returns a list of available dates of the given scope for the given field.
->>> Article.objects.dates('pub_date', 'year')
-[datetime.datetime(2005, 1, 1, 0, 0)]
->>> Article.objects.dates('pub_date', 'month')
-[datetime.datetime(2005, 7, 1, 0, 0)]
->>> Article.objects.dates('pub_date', 'day')
-[datetime.datetime(2005, 7, 28, 0, 0), datetime.datetime(2005, 7, 29, 0, 0), datetime.datetime(2005, 7, 30, 0, 0), datetime.datetime(2005, 7, 31, 0, 0)]
->>> Article.objects.dates('pub_date', 'day', order='ASC')
-[datetime.datetime(2005, 7, 28, 0, 0), datetime.datetime(2005, 7, 29, 0, 0), datetime.datetime(2005, 7, 30, 0, 0), datetime.datetime(2005, 7, 31, 0, 0)]
->>> Article.objects.dates('pub_date', 'day', order='DESC')
-[datetime.datetime(2005, 7, 31, 0, 0), datetime.datetime(2005, 7, 30, 0, 0), datetime.datetime(2005, 7, 29, 0, 0), datetime.datetime(2005, 7, 28, 0, 0)]
-
-# dates() requires valid arguments.
-
->>> Article.objects.dates()
-Traceback (most recent call last):
- ...
-TypeError: dates() takes at least 3 arguments (1 given)
-
->>> Article.objects.dates('invalid_field', 'year')
-Traceback (most recent call last):
- ...
-FieldDoesNotExist: Article has no field named 'invalid_field'
-
->>> Article.objects.dates('pub_date', 'bad_kind')
-Traceback (most recent call last):
- ...
-AssertionError: 'kind' must be one of 'year', 'month' or 'day'.
-
->>> Article.objects.dates('pub_date', 'year', order='bad order')
-Traceback (most recent call last):
- ...
-AssertionError: 'order' must be either 'ASC' or 'DESC'.
-
-# Use iterator() with dates() to return a generator that lazily requests each
-# result one at a time, to save memory.
->>> for a in Article.objects.dates('pub_date', 'day', order='DESC').iterator():
-... print repr(a)
-datetime.datetime(2005, 7, 31, 0, 0)
-datetime.datetime(2005, 7, 30, 0, 0)
-datetime.datetime(2005, 7, 29, 0, 0)
-datetime.datetime(2005, 7, 28, 0, 0)
-
-# You can combine queries with & and |.
->>> s1 = Article.objects.filter(id__exact=1)
->>> s2 = Article.objects.filter(id__exact=2)
->>> s1 | s2
-[<Article: Area woman programs in Python>, <Article: Second article>]
->>> s1 & s2
-[]
-
-# You can get the number of objects like this:
->>> len(Article.objects.filter(id__exact=1))
-1
-
-# You can get items using index and slice notation.
->>> Article.objects.all()[0]
-<Article: Area woman programs in Python>
->>> Article.objects.all()[1:3]
-[<Article: Second article>, <Article: Third article>]
->>> s3 = Article.objects.filter(id__exact=3)
->>> (s1 | s2 | s3)[::2]
-[<Article: Area woman programs in Python>, <Article: Third article>]
-
-# Slices (without step) are lazy:
->>> Article.objects.all()[0:5].filter()
-[<Article: Area woman programs in Python>, <Article: Second article>, <Article: Third article>, <Article: Article 6>, <Article: Default headline>]
-
-# Slicing again works:
->>> Article.objects.all()[0:5][0:2]
-[<Article: Area woman programs in Python>, <Article: Second article>]
->>> Article.objects.all()[0:5][:2]
-[<Article: Area woman programs in Python>, <Article: Second article>]
->>> Article.objects.all()[0:5][4:]
-[<Article: Default headline>]
->>> Article.objects.all()[0:5][5:]
-[]
-
-# Some more tests!
->>> Article.objects.all()[2:][0:2]
-[<Article: Third article>, <Article: Article 6>]
->>> Article.objects.all()[2:][:2]
-[<Article: Third article>, <Article: Article 6>]
->>> Article.objects.all()[2:][2:3]
-[<Article: Default headline>]
-
-# Note that you can't use 'offset' without 'limit' (on some dbs), so this doesn't work:
->>> Article.objects.all()[2:]
-Traceback (most recent call last):
- ...
-AssertionError: 'offset' is not allowed without 'limit'
-
-# Also, once you have sliced you can't filter, re-order or combine
->>> Article.objects.all()[0:5].filter(id=1)
-Traceback (most recent call last):
- ...
-AssertionError: Cannot filter a query once a slice has been taken.
-
->>> Article.objects.all()[0:5].order_by('id')
-Traceback (most recent call last):
- ...
-AssertionError: Cannot reorder a query once a slice has been taken.
-
->>> Article.objects.all()[0:1] & Article.objects.all()[4:5]
-Traceback (most recent call last):
- ...
-AssertionError: Cannot combine queries once a slice has been taken.
-
-# Negative slices are not supported, due to database constraints.
-# (hint: inverting your ordering might do what you need).
->>> Article.objects.all()[-1]
-Traceback (most recent call last):
- ...
-AssertionError: Negative indexing is not supported.
->>> Article.objects.all()[0:-5]
-Traceback (most recent call last):
- ...
-AssertionError: Negative indexing is not supported.
-
-# An Article instance doesn't have access to the "objects" attribute.
-# That's only available on the class.
->>> a7.objects.all()
-Traceback (most recent call last):
- ...
-AttributeError: Manager isn't accessible via Article instances
-
->>> a7.objects
-Traceback (most recent call last):
- ...
-AttributeError: Manager isn't accessible via Article instances
-
-# Bulk delete test: How many objects before and after the delete?
->>> Article.objects.all()
-[<Article: Area woman programs in Python>, <Article: Second article>, <Article: Third article>, <Article: Article 6>, <Article: Default headline>, <Article: Fourth article>, <Article: Article 7>, <Article: Updated article 8>]
->>> Article.objects.filter(id__lte=4).delete()
->>> Article.objects.all()
-[<Article: Article 6>, <Article: Default headline>, <Article: Article 7>, <Article: Updated article 8>]
-"""}
-
-from django.conf import settings
-
-building_docs = getattr(settings, 'BUILDING_DOCS', False)
-
-if building_docs or settings.DATABASE_ENGINE == 'postgresql':
- __test__['API_TESTS'] += """
-# In PostgreSQL, microsecond-level precision is available.
->>> a9 = Article(headline='Article 9', pub_date=datetime(2005, 7, 31, 12, 30, 45, 180))
->>> a9.save()
->>> Article.objects.get(id__exact=9).pub_date
-datetime.datetime(2005, 7, 31, 12, 30, 45, 180)
-"""
-
-if building_docs or settings.DATABASE_ENGINE == 'mysql':
- __test__['API_TESTS'] += """
-# In MySQL, microsecond-level precision isn't available. You'll lose
-# microsecond-level precision once the data is saved.
->>> a9 = Article(headline='Article 9', pub_date=datetime(2005, 7, 31, 12, 30, 45, 180))
->>> a9.save()
->>> Article.objects.get(id__exact=9).pub_date
-datetime.datetime(2005, 7, 31, 12, 30, 45)
-"""
-
-__test__['API_TESTS'] += """
-
-# You can manually specify the primary key when creating a new object.
->>> a101 = Article(id=101, headline='Article 101', pub_date=datetime(2005, 7, 31, 12, 30, 45))
->>> a101.save()
->>> a101 = Article.objects.get(pk=101)
->>> a101.headline
-'Article 101'
-
-# You can create saved objects in a single step
->>> a10 = Article.objects.create(headline="Article 10", pub_date=datetime(2005, 7, 31, 12, 30, 45))
->>> Article.objects.get(headline="Article 10")
-<Article: Article 10>
-
-# Edge-case test: A year lookup should retrieve all objects in the given
-year, including Jan. 1 and Dec. 31.
->>> a11 = Article.objects.create(headline='Article 11', pub_date=datetime(2008, 1, 1))
->>> a12 = Article.objects.create(headline='Article 12', pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999))
->>> Article.objects.filter(pub_date__year=2008)
-[<Article: Article 11>, <Article: Article 12>]
-"""
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/choices/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,39 +0,0 @@
-"""
-21. Specifying 'choices' for a field
-
-Most fields take a ``choices`` parameter, which should be a tuple of tuples
-specifying which are the valid values for that field.
-
-For each field that has ``choices``, a model instance gets a
-``get_fieldname_display()`` method, where ``fieldname`` is the name of the
-field. This method returns the "human-readable" value of the field.
-"""
-
-from django.db import models
-
-GENDER_CHOICES = (
- ('M', 'Male'),
- ('F', 'Female'),
-)
-
-class Person(models.Model):
- name = models.CharField(maxlength=20)
- gender = models.CharField(maxlength=1, choices=GENDER_CHOICES)
-
- def __str__(self):
- return self.name
-
-__test__ = {'API_TESTS':"""
->>> a = Person(name='Adrian', gender='M')
->>> a.save()
->>> s = Person(name='Sara', gender='F')
->>> s.save()
->>> a.gender
-'M'
->>> s.gender
-'F'
->>> a.get_gender_display()
-'Male'
->>> s.get_gender_display()
-'Female'
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/custom_columns/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,105 +0,0 @@
-"""
-17. Custom column/table names
-
-If your database column name is different than your model attribute, use the
-``db_column`` parameter. Note that you'll use the field's name, not its column
-name, in API usage.
-
-If your database table name is different than your model name, use the
-``db_table`` Meta attribute. This has no effect on the API used to
-query the database.
-
-If you need to use a table name for a many-to-many relationship that differs
-from the default generated name, use the ``db_table`` parameter on the
-ManyToMany field. This has no effect on the API for querying the database.
-
-"""
-
-from django.db import models
-
-class Author(models.Model):
- first_name = models.CharField(maxlength=30, db_column='firstname')
- last_name = models.CharField(maxlength=30, db_column='last')
-
- def __str__(self):
- return '%s %s' % (self.first_name, self.last_name)
-
- class Meta:
- db_table = 'my_author_table'
- ordering = ('last_name','first_name')
-
-class Article(models.Model):
- headline = models.CharField(maxlength=100)
- authors = models.ManyToManyField(Author, db_table='my_m2m_table')
-
- def __str__(self):
- return self.headline
-
- class Meta:
- ordering = ('headline',)
-
-__test__ = {'API_TESTS':"""
-# Create a Author.
->>> a = Author(first_name='John', last_name='Smith')
->>> a.save()
-
->>> a.id
-1
-
-# Create another author
->>> a2 = Author(first_name='Peter', last_name='Jones')
->>> a2.save()
-
-# Create an article
->>> art = Article(headline='Django lets you build web apps easily')
->>> art.save()
->>> art.authors = [a, a2]
-
-# Although the table and column names on Author have been set to
-# custom values, nothing about using the Author model has changed...
-
-# Query the available authors
->>> Author.objects.all()
-[<Author: Peter Jones>, <Author: John Smith>]
-
->>> Author.objects.filter(first_name__exact='John')
-[<Author: John Smith>]
-
->>> Author.objects.get(first_name__exact='John')
-<Author: John Smith>
-
->>> Author.objects.filter(firstname__exact='John')
-Traceback (most recent call last):
- ...
-TypeError: Cannot resolve keyword 'firstname' into field
-
->>> a = Author.objects.get(last_name__exact='Smith')
->>> a.first_name
-'John'
->>> a.last_name
-'Smith'
->>> a.firstname
-Traceback (most recent call last):
- ...
-AttributeError: 'Author' object has no attribute 'firstname'
->>> a.last
-Traceback (most recent call last):
- ...
-AttributeError: 'Author' object has no attribute 'last'
-
-# Although the Article table uses a custom m2m table,
-# nothing about using the m2m relationship has changed...
-
-# Get all the authors for an article
->>> art.authors.all()
-[<Author: Peter Jones>, <Author: John Smith>]
-
-# Get the articles for an author
->>> a.article_set.all()
-[<Article: Django lets you build web apps easily>]
-
-# Query the authors across the m2m relation
->>> art.authors.filter(last_name='Jones')
-[<Author: Peter Jones>]
-
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/custom_managers/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,107 +0,0 @@
-"""
-23. Giving models a custom manager
-
-You can use a custom ``Manager`` in a particular model by extending the base
-``Manager`` class and instantiating your custom ``Manager`` in your model.
-
-There are two reasons you might want to customize a ``Manager``: to add extra
-``Manager`` methods, and/or to modify the initial ``QuerySet`` the ``Manager``
-returns.
-"""
-
-from django.db import models
-
-# An example of a custom manager called "objects".
-
-class PersonManager(models.Manager):
- def get_fun_people(self):
- return self.filter(fun=True)
-
-class Person(models.Model):
- first_name = models.CharField(maxlength=30)
- last_name = models.CharField(maxlength=30)
- fun = models.BooleanField()
- objects = PersonManager()
-
- def __str__(self):
- return "%s %s" % (self.first_name, self.last_name)
-
-# An example of a custom manager that sets get_query_set().
-
-class PublishedBookManager(models.Manager):
- def get_query_set(self):
- return super(PublishedBookManager, self).get_query_set().filter(is_published=True)
-
-class Book(models.Model):
- title = models.CharField(maxlength=50)
- author = models.CharField(maxlength=30)
- is_published = models.BooleanField()
- published_objects = PublishedBookManager()
- authors = models.ManyToManyField(Person, related_name='books')
-
- def __str__(self):
- return self.title
-
-# An example of providing multiple custom managers.
-
-class FastCarManager(models.Manager):
- def get_query_set(self):
- return super(FastCarManager, self).get_query_set().filter(top_speed__gt=150)
-
-class Car(models.Model):
- name = models.CharField(maxlength=10)
- mileage = models.IntegerField()
- top_speed = models.IntegerField(help_text="In miles per hour.")
- cars = models.Manager()
- fast_cars = FastCarManager()
-
- def __str__(self):
- return self.name
-
-__test__ = {'API_TESTS':"""
->>> p1 = Person(first_name='Bugs', last_name='Bunny', fun=True)
->>> p1.save()
->>> p2 = Person(first_name='Droopy', last_name='Dog', fun=False)
->>> p2.save()
->>> Person.objects.get_fun_people()
-[<Person: Bugs Bunny>]
-
-# The RelatedManager used on the 'books' descriptor extends the default manager
->>> from modeltests.custom_managers.models import PublishedBookManager
->>> isinstance(p2.books, PublishedBookManager)
-True
-
->>> b1 = Book(title='How to program', author='Rodney Dangerfield', is_published=True)
->>> b1.save()
->>> b2 = Book(title='How to be smart', author='Albert Einstein', is_published=False)
->>> b2.save()
-
-# The default manager, "objects", doesn't exist,
-# because a custom one was provided.
->>> Book.objects
-Traceback (most recent call last):
- ...
-AttributeError: type object 'Book' has no attribute 'objects'
-
-# The RelatedManager used on the 'authors' descriptor extends the default manager
->>> from modeltests.custom_managers.models import PersonManager
->>> isinstance(b2.authors, PersonManager)
-True
-
->>> Book.published_objects.all()
-[<Book: How to program>]
-
->>> c1 = Car(name='Corvette', mileage=21, top_speed=180)
->>> c1.save()
->>> c2 = Car(name='Neon', mileage=31, top_speed=100)
->>> c2.save()
->>> Car.cars.order_by('name')
-[<Car: Corvette>, <Car: Neon>]
->>> Car.fast_cars.all()
-[<Car: Corvette>]
-
-# Each model class gets a "_default_manager" attribute, which is a reference
-# to the first manager defined in the class. In this case, it's "cars".
->>> Car._default_manager.order_by('name')
-[<Car: Corvette>, <Car: Neon>]
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/custom_methods/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,58 +0,0 @@
-"""
-3. Giving models custom methods
-
-Any method you add to a model will be available to instances.
-"""
-
-from django.db import models
-import datetime
-
-class Article(models.Model):
- headline = models.CharField(maxlength=100)
- pub_date = models.DateField()
-
- def __str__(self):
- return self.headline
-
- def was_published_today(self):
- return self.pub_date == datetime.date.today()
-
- def articles_from_same_day_1(self):
- return Article.objects.filter(pub_date=self.pub_date).exclude(id=self.id)
-
- def articles_from_same_day_2(self):
- """
- Verbose version of get_articles_from_same_day_1, which does a custom
- database query for the sake of demonstration.
- """
- from django.db import connection
- cursor = connection.cursor()
- cursor.execute("""
- SELECT id, headline, pub_date
- FROM custom_methods_article
- WHERE pub_date = %s
- AND id != %s""", [str(self.pub_date), self.id])
- # The asterisk in "(*row)" tells Python to expand the list into
- # positional arguments to Article().
- return [self.__class__(*row) for row in cursor.fetchall()]
-
-__test__ = {'API_TESTS':"""
-# Create a couple of Articles.
->>> from datetime import date
->>> a = Article(id=None, headline='Area man programs in Python', pub_date=date(2005, 7, 27))
->>> a.save()
->>> b = Article(id=None, headline='Beatles reunite', pub_date=date(2005, 7, 27))
->>> b.save()
-
-# Test the custom methods.
->>> a.was_published_today()
-False
->>> a.articles_from_same_day_1()
-[<Article: Beatles reunite>]
->>> a.articles_from_same_day_2()
-[<Article: Beatles reunite>]
->>> b.articles_from_same_day_1()
-[<Article: Area man programs in Python>]
->>> b.articles_from_same_day_2()
-[<Article: Area man programs in Python>]
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/custom_pk/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,95 +0,0 @@
-"""
-14. Using a custom primary key
-
-By default, Django adds an ``"id"`` field to each model. But you can override
-this behavior by explicitly adding ``primary_key=True`` to a field.
-"""
-
-from django.db import models
-
-class Employee(models.Model):
- employee_code = models.CharField(maxlength=10, primary_key=True,
- db_column = 'code')
- first_name = models.CharField(maxlength=20)
- last_name = models.CharField(maxlength=20)
- class Meta:
- ordering = ('last_name', 'first_name')
-
- def __str__(self):
- return "%s %s" % (self.first_name, self.last_name)
-
-class Business(models.Model):
- name = models.CharField(maxlength=20, primary_key=True)
- employees = models.ManyToManyField(Employee)
- class Meta:
- verbose_name_plural = 'businesses'
-
- def __str__(self):
- return self.name
-
-__test__ = {'API_TESTS':"""
->>> dan = Employee(employee_code='ABC123', first_name='Dan', last_name='Jones')
->>> dan.save()
->>> Employee.objects.all()
-[<Employee: Dan Jones>]
-
->>> fran = Employee(employee_code='XYZ456', first_name='Fran', last_name='Bones')
->>> fran.save()
->>> Employee.objects.all()
-[<Employee: Fran Bones>, <Employee: Dan Jones>]
-
->>> Employee.objects.get(pk='ABC123')
-<Employee: Dan Jones>
->>> Employee.objects.get(pk='XYZ456')
-<Employee: Fran Bones>
->>> Employee.objects.get(pk='foo')
-Traceback (most recent call last):
- ...
-DoesNotExist: Employee matching query does not exist.
-
-# Use the name of the primary key, rather than pk.
->>> Employee.objects.get(employee_code__exact='ABC123')
-<Employee: Dan Jones>
-
-# pk can be used as a substitute for the primary key.
->>> Employee.objects.filter(pk__in=['ABC123','XYZ456'])
-[<Employee: Fran Bones>, <Employee: Dan Jones>]
-
-# Fran got married and changed her last name.
->>> fran = Employee.objects.get(pk='XYZ456')
->>> fran.last_name = 'Jones'
->>> fran.save()
->>> Employee.objects.filter(last_name__exact='Jones')
-[<Employee: Dan Jones>, <Employee: Fran Jones>]
->>> Employee.objects.in_bulk(['ABC123', 'XYZ456'])
-{'XYZ456': <Employee: Fran Jones>, 'ABC123': <Employee: Dan Jones>}
-
->>> b = Business(name='Sears')
->>> b.save()
->>> b.employees.add(dan, fran)
->>> b.employees.all()
-[<Employee: Dan Jones>, <Employee: Fran Jones>]
->>> fran.business_set.all()
-[<Business: Sears>]
->>> Business.objects.in_bulk(['Sears'])
-{'Sears': <Business: Sears>}
-
->>> Business.objects.filter(name__exact='Sears')
-[<Business: Sears>]
->>> Business.objects.filter(pk='Sears')
-[<Business: Sears>]
-
-# Queries across tables, involving primary key
->>> Employee.objects.filter(business__name__exact='Sears')
-[<Employee: Dan Jones>, <Employee: Fran Jones>]
->>> Employee.objects.filter(business__pk='Sears')
-[<Employee: Dan Jones>, <Employee: Fran Jones>]
-
->>> Business.objects.filter(employees__employee_code__exact='ABC123')
-[<Business: Sears>]
->>> Business.objects.filter(employees__pk='ABC123')
-[<Business: Sears>]
->>> Business.objects.filter(employees__first_name__startswith='Fran')
-[<Business: Sears>]
-
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/empty/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,26 +0,0 @@
-"""
-39. Empty model tests
-
-These test that things behave sensibly for the rare corner-case of a model with
-no fields.
-"""
-
-from django.db import models
-
-class Empty(models.Model):
- pass
-
-__test__ = {'API_TESTS':"""
->>> m = Empty()
->>> m.id
->>> m.save()
->>> m2 = Empty()
->>> m2.save()
->>> len(Empty.objects.all())
-2
->>> m.id is not None
-True
->>> existing = Empty(m.id)
->>> existing.save()
-
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/field_defaults/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,51 +0,0 @@
-"""
-32. Callable defaults
-
-You can pass callable objects as the ``default`` parameter to a field. When
-the object is created without an explicit value passed in, Django will call
-the method to determine the default value.
-
-This example uses ``datetime.datetime.now`` as the default for the ``pub_date``
-field.
-"""
-
-from django.db import models
-from datetime import datetime
-
-class Article(models.Model):
- headline = models.CharField(maxlength=100, default='Default headline')
- pub_date = models.DateTimeField(default=datetime.now)
-
- def __str__(self):
- return self.headline
-
-__test__ = {'API_TESTS':"""
->>> from datetime import datetime
-
-# No articles are in the system yet.
->>> Article.objects.all()
-[]
-
-# Create an Article.
->>> a = Article(id=None)
-
-# Grab the current datetime it should be very close to the default that just
-# got saved as a.pub_date
->>> now = datetime.now()
-
-# Save it into the database. You have to call save() explicitly.
->>> a.save()
-
-# Now it has an ID. Note it's a long integer, as designated by the trailing "L".
->>> a.id
-1L
-
-# Access database columns via Python attributes.
->>> a.headline
-'Default headline'
-
-# make sure the two dates are sufficiently close
->>> d = now - a.pub_date
->>> d.seconds < 5
-True
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/fixtures/__init__.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,2 +0,0 @@
-
-
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/fixtures/fixtures/fixture1.json Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,18 +0,0 @@
-[
- {
- "pk": "2",
- "model": "fixtures.article",
- "fields": {
- "headline": "Poker has no place on ESPN",
- "pub_date": "2006-06-16 12:00:00"
- }
- },
- {
- "pk": "3",
- "model": "fixtures.article",
- "fields": {
- "headline": "Time to reform copyright",
- "pub_date": "2006-06-16 13:00:00"
- }
- }
-]
\ No newline at end of file
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/fixtures/fixtures/fixture2.json Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,18 +0,0 @@
-[
- {
- "pk": "3",
- "model": "fixtures.article",
- "fields": {
- "headline": "Copyright is fine the way it is",
- "pub_date": "2006-06-16 14:00:00"
- }
- },
- {
- "pk": "4",
- "model": "fixtures.article",
- "fields": {
- "headline": "Django conquers world!",
- "pub_date": "2006-06-16 15:00:00"
- }
- }
-]
\ No newline at end of file
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/fixtures/fixtures/fixture2.xml Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<django-objects version="1.0">
- <object pk="2" model="fixtures.article">
- <field type="CharField" name="headline">Poker on TV is great!</field>
- <field type="DateTimeField" name="pub_date">2006-06-16 11:00:00</field>
- </object>
- <object pk="5" model="fixtures.article">
- <field type="CharField" name="headline">XML identified as leading cause of cancer</field>
- <field type="DateTimeField" name="pub_date">2006-06-16 16:00:00</field>
- </object>
-</django-objects>
\ No newline at end of file
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/fixtures/fixtures/fixture3.xml Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<django-objects version="1.0">
- <object pk="2" model="fixtures.article">
- <field type="CharField" name="headline">Poker on TV is great!</field>
- <field type="DateTimeField" name="pub_date">2006-06-16 11:00:00</field>
- </object>
- <object pk="5" model="fixtures.article">
- <field type="CharField" name="headline">XML identified as leading cause of cancer</field>
- <field type="DateTimeField" name="pub_date">2006-06-16 16:00:00</field>
- </object>
-</django-objects>
\ No newline at end of file
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/fixtures/fixtures/initial_data.json Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,10 +0,0 @@
-[
- {
- "pk": "1",
- "model": "fixtures.article",
- "fields": {
- "headline": "Python program becomes self aware",
- "pub_date": "2006-06-16 11:00:00"
- }
- }
-]
\ No newline at end of file
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/fixtures/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,88 +0,0 @@
-"""
-37. Fixtures.
-
-Fixtures are a way of loading data into the database in bulk. Fixure data
-can be stored in any serializable format (including JSON and XML). Fixtures
-are identified by name, and are stored in either a directory named 'fixtures'
-in the application directory, on in one of the directories named in the
-FIXTURE_DIRS setting.
-"""
-
-from django.db import models
-
-class Article(models.Model):
- headline = models.CharField(maxlength=100, default='Default headline')
- pub_date = models.DateTimeField()
-
- def __str__(self):
- return self.headline
-
- class Meta:
- ordering = ('-pub_date', 'headline')
-
-__test__ = {'API_TESTS': """
->>> from django.core import management
->>> from django.db.models import get_app
-
-# Reset the database representation of this app.
-# This will return the database to a clean initial state.
->>> management.flush(verbosity=0, interactive=False)
-
-# Syncdb introduces 1 initial data object from initial_data.json.
->>> Article.objects.all()
-[<Article: Python program becomes self aware>]
-
-# Load fixture 1. Single JSON file, with two objects.
->>> management.load_data(['fixture1.json'], verbosity=0)
->>> Article.objects.all()
-[<Article: Time to reform copyright>, <Article: Poker has no place on ESPN>, <Article: Python program becomes self aware>]
-
-# Load fixture 2. JSON file imported by default. Overwrites some existing objects
->>> management.load_data(['fixture2.json'], verbosity=0)
->>> Article.objects.all()
-[<Article: Django conquers world!>, <Article: Copyright is fine the way it is>, <Article: Poker has no place on ESPN>, <Article: Python program becomes self aware>]
-
-# Load fixture 3, XML format.
->>> management.load_data(['fixture3.xml'], verbosity=0)
->>> Article.objects.all()
-[<Article: XML identified as leading cause of cancer>, <Article: Django conquers world!>, <Article: Copyright is fine the way it is>, <Article: Poker on TV is great!>, <Article: Python program becomes self aware>]
-
-# Load a fixture that doesn't exist
->>> management.load_data(['unknown.json'], verbosity=0)
-
-# object list is unaffected
->>> Article.objects.all()
-[<Article: XML identified as leading cause of cancer>, <Article: Django conquers world!>, <Article: Copyright is fine the way it is>, <Article: Poker on TV is great!>, <Article: Python program becomes self aware>]
-
-# Reset the database representation of this app. This will delete all data.
->>> management.flush(verbosity=0, interactive=False)
->>> Article.objects.all()
-[<Article: Python program becomes self aware>]
-
-# Load fixture 1 again, using format discovery
->>> management.load_data(['fixture1'], verbosity=0)
->>> Article.objects.all()
-[<Article: Time to reform copyright>, <Article: Poker has no place on ESPN>, <Article: Python program becomes self aware>]
-
-# Try to load fixture 2 using format discovery; this will fail
-# because there are two fixture2's in the fixtures directory
->>> management.load_data(['fixture2'], verbosity=0) # doctest: +ELLIPSIS
-Multiple fixtures named 'fixture2' in '...fixtures'. Aborting.
-
->>> Article.objects.all()
-[<Article: Time to reform copyright>, <Article: Poker has no place on ESPN>, <Article: Python program becomes self aware>]
-
-# Dump the current contents of the database as a JSON fixture
->>> print management.dump_data(['fixtures'], format='json')
-[{"pk": "3", "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": "2", "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16 12:00:00"}}, {"pk": "1", "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11:00:00"}}]
-"""}
-
-from django.test import TestCase
-
-class SampleTestCase(TestCase):
- fixtures = ['fixture1.json', 'fixture2.json']
-
- def testClassFixtures(self):
- "Check that test case has installed 4 fixture objects"
- self.assertEqual(Article.objects.count(), 4)
- self.assertEquals(str(Article.objects.all()), "[<Article: Django conquers world!>, <Article: Copyright is fine the way it is>, <Article: Poker has no place on ESPN>, <Article: Python program becomes self aware>]")
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/generic_relations/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,134 +0,0 @@
-"""
-34. Generic relations
-
-Generic relations let an object have a foreign key to any object through a
-content-type/object-id field. A generic foreign key can point to any object,
-be it animal, vegetable, or mineral.
-
-The canonical example is tags (although this example implementation is *far*
-from complete).
-"""
-
-from django.db import models
-from django.contrib.contenttypes.models import ContentType
-
-class TaggedItem(models.Model):
- """A tag on an item."""
- tag = models.SlugField()
- content_type = models.ForeignKey(ContentType)
- object_id = models.PositiveIntegerField()
-
- content_object = models.GenericForeignKey()
-
- class Meta:
- ordering = ["tag"]
-
- def __str__(self):
- return self.tag
-
-class Animal(models.Model):
- common_name = models.CharField(maxlength=150)
- latin_name = models.CharField(maxlength=150)
-
- tags = models.GenericRelation(TaggedItem)
-
- def __str__(self):
- return self.common_name
-
-class Vegetable(models.Model):
- name = models.CharField(maxlength=150)
- is_yucky = models.BooleanField(default=True)
-
- tags = models.GenericRelation(TaggedItem)
-
- def __str__(self):
- return self.name
-
-class Mineral(models.Model):
- name = models.CharField(maxlength=150)
- hardness = models.PositiveSmallIntegerField()
-
- # note the lack of an explicit GenericRelation here...
-
- def __str__(self):
- return self.name
-
-__test__ = {'API_TESTS':"""
-# Create the world in 7 lines of code...
->>> lion = Animal(common_name="Lion", latin_name="Panthera leo")
->>> platypus = Animal(common_name="Platypus", latin_name="Ornithorhynchus anatinus")
->>> eggplant = Vegetable(name="Eggplant", is_yucky=True)
->>> bacon = Vegetable(name="Bacon", is_yucky=False)
->>> quartz = Mineral(name="Quartz", hardness=7)
->>> for o in (lion, platypus, eggplant, bacon, quartz):
-... o.save()
-
-# Objects with declared GenericRelations can be tagged directly -- the API
-# mimics the many-to-many API.
->>> bacon.tags.create(tag="fatty")
-<TaggedItem: fatty>
->>> bacon.tags.create(tag="salty")
-<TaggedItem: salty>
->>> lion.tags.create(tag="yellow")
-<TaggedItem: yellow>
->>> lion.tags.create(tag="hairy")
-<TaggedItem: hairy>
-
->>> lion.tags.all()
-[<TaggedItem: hairy>, <TaggedItem: yellow>]
->>> bacon.tags.all()
-[<TaggedItem: fatty>, <TaggedItem: salty>]
-
-# You can easily access the content object like a foreign key.
->>> t = TaggedItem.objects.get(tag="salty")
->>> t.content_object
-<Vegetable: Bacon>
-
-# Recall that the Mineral class doesn't have an explicit GenericRelation
-# defined. That's OK, because you can create TaggedItems explicitly.
->>> tag1 = TaggedItem(content_object=quartz, tag="shiny")
->>> tag2 = TaggedItem(content_object=quartz, tag="clearish")
->>> tag1.save()
->>> tag2.save()
-
-# However, excluding GenericRelations means your lookups have to be a bit more
-# explicit.
->>> from django.contrib.contenttypes.models import ContentType
->>> ctype = ContentType.objects.get_for_model(quartz)
->>> TaggedItem.objects.filter(content_type__pk=ctype.id, object_id=quartz.id)
-[<TaggedItem: clearish>, <TaggedItem: shiny>]
-
-# You can set a generic foreign key in the way you'd expect.
->>> tag1.content_object = platypus
->>> tag1.save()
->>> platypus.tags.all()
-[<TaggedItem: shiny>]
->>> TaggedItem.objects.filter(content_type__pk=ctype.id, object_id=quartz.id)
-[<TaggedItem: clearish>]
-
-# If you delete an object with an explicit Generic relation, the related
-# objects are deleted when the source object is deleted.
-# Original list of tags:
->>> [(t.tag, t.content_type, t.object_id) for t in TaggedItem.objects.all()]
-[('clearish', <ContentType: mineral>, 1), ('fatty', <ContentType: vegetable>, 2), ('hairy', <ContentType: animal>, 1), ('salty', <ContentType: vegetable>, 2), ('shiny', <ContentType: animal>, 2), ('yellow', <ContentType: animal>, 1)]
-
->>> lion.delete()
->>> [(t.tag, t.content_type, t.object_id) for t in TaggedItem.objects.all()]
-[('clearish', <ContentType: mineral>, 1), ('fatty', <ContentType: vegetable>, 2), ('salty', <ContentType: vegetable>, 2), ('shiny', <ContentType: animal>, 2)]
-
-# If Generic Relation is not explicitly defined, any related objects
-# remain after deletion of the source object.
->>> quartz.delete()
->>> [(t.tag, t.content_type, t.object_id) for t in TaggedItem.objects.all()]
-[('clearish', <ContentType: mineral>, 1), ('fatty', <ContentType: vegetable>, 2), ('salty', <ContentType: vegetable>, 2), ('shiny', <ContentType: animal>, 2)]
-
-# If you delete a tag, the objects using the tag are unaffected
-# (other than losing a tag)
->>> tag = TaggedItem.objects.get(id=1)
->>> tag.delete()
->>> bacon.tags.all()
-[<TaggedItem: salty>]
->>> [(t.tag, t.content_type, t.object_id) for t in TaggedItem.objects.all()]
-[('clearish', <ContentType: mineral>, 1), ('salty', <ContentType: vegetable>, 2), ('shiny', <ContentType: animal>, 2)]
-
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/get_latest/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,79 +0,0 @@
-"""
-8. get_latest_by
-
-Models can have a ``get_latest_by`` attribute, which should be set to the name
-of a DateField or DateTimeField. If ``get_latest_by`` exists, the model's
-manager will get a ``latest()`` method, which will return the latest object in
-the database according to that field. "Latest" means "having the date farthest
-into the future."
-"""
-
-from django.db import models
-
-class Article(models.Model):
- headline = models.CharField(maxlength=100)
- pub_date = models.DateField()
- expire_date = models.DateField()
- class Meta:
- get_latest_by = 'pub_date'
-
- def __str__(self):
- return self.headline
-
-class Person(models.Model):
- name = models.CharField(maxlength=30)
- birthday = models.DateField()
-
- # Note that this model doesn't have "get_latest_by" set.
-
- def __str__(self):
- return self.name
-
-__test__ = {'API_TESTS':"""
-# Because no Articles exist yet, latest() raises ArticleDoesNotExist.
->>> Article.objects.latest()
-Traceback (most recent call last):
- ...
-DoesNotExist: Article matching query does not exist.
-
-# Create a couple of Articles.
->>> from datetime import datetime
->>> a1 = Article(headline='Article 1', pub_date=datetime(2005, 7, 26), expire_date=datetime(2005, 9, 1))
->>> a1.save()
->>> a2 = Article(headline='Article 2', pub_date=datetime(2005, 7, 27), expire_date=datetime(2005, 7, 28))
->>> a2.save()
->>> a3 = Article(headline='Article 3', pub_date=datetime(2005, 7, 27), expire_date=datetime(2005, 8, 27))
->>> a3.save()
->>> a4 = Article(headline='Article 4', pub_date=datetime(2005, 7, 28), expire_date=datetime(2005, 7, 30))
->>> a4.save()
-
-# Get the latest Article.
->>> Article.objects.latest()
-<Article: Article 4>
-
-# Get the latest Article that matches certain filters.
->>> Article.objects.filter(pub_date__lt=datetime(2005, 7, 27)).latest()
-<Article: Article 1>
-
-# Pass a custom field name to latest() to change the field that's used to
-# determine the latest object.
->>> Article.objects.latest('expire_date')
-<Article: Article 1>
-
->>> Article.objects.filter(pub_date__gt=datetime(2005, 7, 26)).latest('expire_date')
-<Article: Article 3>
-
-# You can still use latest() with a model that doesn't have "get_latest_by"
-# set -- just pass in the field name manually.
->>> p1 = Person(name='Ralph', birthday=datetime(1950, 1, 1))
->>> p1.save()
->>> p2 = Person(name='Stephanie', birthday=datetime(1960, 2, 3))
->>> p2.save()
->>> Person.objects.latest()
-Traceback (most recent call last):
- ...
-AssertionError: latest() requires either a field_name parameter or 'get_latest_by' in the model
-
->>> Person.objects.latest('birthday')
-<Person: Stephanie>
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/get_object_or_404/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,86 +0,0 @@
-"""
-35. DB-API Shortcuts
-
-get_object_or_404 is a shortcut function to be used in view functions for
-performing a get() lookup and raising a Http404 exception if a DoesNotExist
-exception was rasied during the get() call.
-
-get_list_or_404 is a shortcut function to be used in view functions for
-performing a filter() lookup and raising a Http404 exception if a DoesNotExist
-exception was rasied during the filter() call.
-"""
-
-from django.db import models
-from django.http import Http404
-from django.shortcuts import get_object_or_404, get_list_or_404
-
-class Author(models.Model):
- name = models.CharField(maxlength=50)
-
- def __str__(self):
- return self.name
-
-class ArticleManager(models.Manager):
- def get_query_set(self):
- return super(ArticleManager, self).get_query_set().filter(authors__name__icontains='sir')
-
-class Article(models.Model):
- authors = models.ManyToManyField(Author)
- title = models.CharField(maxlength=50)
- objects = models.Manager()
- by_a_sir = ArticleManager()
-
- def __str__(self):
- return self.title
-
-__test__ = {'API_TESTS':"""
-# Create some Authors.
->>> a = Author.objects.create(name="Brave Sir Robin")
->>> a.save()
->>> a2 = Author.objects.create(name="Patsy")
->>> a2.save()
-
-# No Articles yet, so we should get a Http404 error.
->>> get_object_or_404(Article, title="Foo")
-Traceback (most recent call last):
-...
-Http404: No Article matches the given query.
-
-# Create an Article.
->>> article = Article.objects.create(title="Run away!")
->>> article.authors = [a, a2]
->>> article.save()
-
-# get_object_or_404 can be passed a Model to query.
->>> get_object_or_404(Article, title__contains="Run")
-<Article: Run away!>
-
-# We can also use the the Article manager through an Author object.
->>> get_object_or_404(a.article_set, title__contains="Run")
-<Article: Run away!>
-
-# No articles containing "Camelot". This should raise a Http404 error.
->>> get_object_or_404(a.article_set, title__contains="Camelot")
-Traceback (most recent call last):
-...
-Http404: No Article matches the given query.
-
-# Custom managers can be used too.
->>> get_object_or_404(Article.by_a_sir, title="Run away!")
-<Article: Run away!>
-
-# get_list_or_404 can be used to get lists of objects
->>> get_list_or_404(a.article_set, title__icontains='Run')
-[<Article: Run away!>]
-
-# Http404 is returned if the list is empty
->>> get_list_or_404(a.article_set, title__icontains='Shrubbery')
-Traceback (most recent call last):
-...
-Http404: No Article matches the given query.
-
-# Custom managers can be used too.
->>> get_list_or_404(Article.by_a_sir, title__icontains="Run")
-[<Article: Run away!>]
-
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/get_or_create/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,52 +0,0 @@
-"""
-33. get_or_create()
-
-get_or_create() does what it says: it tries to look up an object with the given
-parameters. If an object isn't found, it creates one with the given parameters.
-"""
-
-from django.db import models
-
-class Person(models.Model):
- first_name = models.CharField(maxlength=100)
- last_name = models.CharField(maxlength=100)
- birthday = models.DateField()
-
- def __str__(self):
- return '%s %s' % (self.first_name, self.last_name)
-
-__test__ = {'API_TESTS':"""
-# Acting as a divine being, create an Person.
->>> from datetime import date
->>> p = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9))
->>> p.save()
-
-# Only one Person is in the database at this point.
->>> Person.objects.count()
-1
-
-# get_or_create() a person with similar first names.
->>> p, created = Person.objects.get_or_create(first_name='John', last_name='Lennon', defaults={'birthday': date(1940, 10, 9)})
-
-# get_or_create() didn't have to create an object.
->>> created
-False
-
-# There's still only one Person in the database.
->>> Person.objects.count()
-1
-
-# get_or_create() a Person with a different name.
->>> p, created = Person.objects.get_or_create(first_name='George', last_name='Harrison', defaults={'birthday': date(1943, 2, 25)})
->>> created
-True
->>> Person.objects.count()
-2
-
-# If we execute the exact same statement, it won't create a Person.
->>> p, created = Person.objects.get_or_create(first_name='George', last_name='Harrison', defaults={'birthday': date(1943, 2, 25)})
->>> created
-False
->>> Person.objects.count()
-2
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/invalid_models/__init__.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,1 +0,0 @@
-
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/invalid_models/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,182 +0,0 @@
-"""
-26. Invalid models
-
-This example exists purely to point out errors in models.
-"""
-
-from django.db import models
-
-class FieldErrors(models.Model):
- charfield = models.CharField()
- floatfield = models.FloatField()
- filefield = models.FileField()
- prepopulate = models.CharField(maxlength=10, prepopulate_from='bad')
- choices = models.CharField(maxlength=10, choices='bad')
- choices2 = models.CharField(maxlength=10, choices=[(1,2,3),(1,2,3)])
- index = models.CharField(maxlength=10, db_index='bad')
-
-class Target(models.Model):
- tgt_safe = models.CharField(maxlength=10)
- clash1 = models.CharField(maxlength=10)
- clash2 = models.CharField(maxlength=10)
-
- clash1_set = models.CharField(maxlength=10)
-
-class Clash1(models.Model):
- src_safe = models.CharField(maxlength=10, core=True)
-
- foreign = models.ForeignKey(Target)
- m2m = models.ManyToManyField(Target)
-
-class Clash2(models.Model):
- src_safe = models.CharField(maxlength=10, core=True)
-
- foreign_1 = models.ForeignKey(Target, related_name='id')
- foreign_2 = models.ForeignKey(Target, related_name='src_safe')
-
- m2m_1 = models.ManyToManyField(Target, related_name='id')
- m2m_2 = models.ManyToManyField(Target, related_name='src_safe')
-
-class Target2(models.Model):
- clash3 = models.CharField(maxlength=10)
- foreign_tgt = models.ForeignKey(Target)
- clashforeign_set = models.ForeignKey(Target)
-
- m2m_tgt = models.ManyToManyField(Target)
- clashm2m_set = models.ManyToManyField(Target)
-
-class Clash3(models.Model):
- src_safe = models.CharField(maxlength=10, core=True)
-
- foreign_1 = models.ForeignKey(Target2, related_name='foreign_tgt')
- foreign_2 = models.ForeignKey(Target2, related_name='m2m_tgt')
-
- m2m_1 = models.ManyToManyField(Target2, related_name='foreign_tgt')
- m2m_2 = models.ManyToManyField(Target2, related_name='m2m_tgt')
-
-class ClashForeign(models.Model):
- foreign = models.ForeignKey(Target2)
-
-class ClashM2M(models.Model):
- m2m = models.ManyToManyField(Target2)
-
-class SelfClashForeign(models.Model):
- src_safe = models.CharField(maxlength=10, core=True)
- selfclashforeign = models.CharField(maxlength=10)
-
- selfclashforeign_set = models.ForeignKey("SelfClashForeign")
- foreign_1 = models.ForeignKey("SelfClashForeign", related_name='id')
- foreign_2 = models.ForeignKey("SelfClashForeign", related_name='src_safe')
-
-class ValidM2M(models.Model):
- src_safe = models.CharField(maxlength=10)
- validm2m = models.CharField(maxlength=10)
-
- # M2M fields are symmetrical by default. Symmetrical M2M fields
- # on self don't require a related accessor, so many potential
- # clashes are avoided.
- validm2m_set = models.ManyToManyField("ValidM2M")
-
- m2m_1 = models.ManyToManyField("ValidM2M", related_name='id')
- m2m_2 = models.ManyToManyField("ValidM2M", related_name='src_safe')
-
- m2m_3 = models.ManyToManyField('self')
- m2m_4 = models.ManyToManyField('self')
-
-class SelfClashM2M(models.Model):
- src_safe = models.CharField(maxlength=10)
- selfclashm2m = models.CharField(maxlength=10)
-
- # Non-symmetrical M2M fields _do_ have related accessors, so
- # there is potential for clashes.
- selfclashm2m_set = models.ManyToManyField("SelfClashM2M", symmetrical=False)
-
- m2m_1 = models.ManyToManyField("SelfClashM2M", related_name='id', symmetrical=False)
- m2m_2 = models.ManyToManyField("SelfClashM2M", related_name='src_safe', symmetrical=False)
-
- m2m_3 = models.ManyToManyField('self', symmetrical=False)
- m2m_4 = models.ManyToManyField('self', symmetrical=False)
-
-model_errors = """invalid_models.fielderrors: "charfield": CharFields require a "maxlength" attribute.
-invalid_models.fielderrors: "floatfield": FloatFields require a "decimal_places" attribute.
-invalid_models.fielderrors: "floatfield": FloatFields require a "max_digits" attribute.
-invalid_models.fielderrors: "filefield": FileFields require an "upload_to" attribute.
-invalid_models.fielderrors: "prepopulate": prepopulate_from should be a list or tuple.
-invalid_models.fielderrors: "choices": "choices" should be iterable (e.g., a tuple or list).
-invalid_models.fielderrors: "choices2": "choices" should be a sequence of two-tuples.
-invalid_models.fielderrors: "choices2": "choices" should be a sequence of two-tuples.
-invalid_models.fielderrors: "index": "db_index" should be either None, True or False.
-invalid_models.clash1: Accessor for field 'foreign' clashes with field 'Target.clash1_set'. Add a related_name argument to the definition for 'foreign'.
-invalid_models.clash1: Accessor for field 'foreign' clashes with related m2m field 'Target.clash1_set'. Add a related_name argument to the definition for 'foreign'.
-invalid_models.clash1: Reverse query name for field 'foreign' clashes with field 'Target.clash1'. Add a related_name argument to the definition for 'foreign'.
-invalid_models.clash1: Accessor for m2m field 'm2m' clashes with field 'Target.clash1_set'. Add a related_name argument to the definition for 'm2m'.
-invalid_models.clash1: Accessor for m2m field 'm2m' clashes with related field 'Target.clash1_set'. Add a related_name argument to the definition for 'm2m'.
-invalid_models.clash1: Reverse query name for m2m field 'm2m' clashes with field 'Target.clash1'. Add a related_name argument to the definition for 'm2m'.
-invalid_models.clash2: Accessor for field 'foreign_1' clashes with field 'Target.id'. Add a related_name argument to the definition for 'foreign_1'.
-invalid_models.clash2: Accessor for field 'foreign_1' clashes with related m2m field 'Target.id'. Add a related_name argument to the definition for 'foreign_1'.
-invalid_models.clash2: Reverse query name for field 'foreign_1' clashes with field 'Target.id'. Add a related_name argument to the definition for 'foreign_1'.
-invalid_models.clash2: Reverse query name for field 'foreign_1' clashes with related m2m field 'Target.id'. Add a related_name argument to the definition for 'foreign_1'.
-invalid_models.clash2: Accessor for field 'foreign_2' clashes with related m2m field 'Target.src_safe'. Add a related_name argument to the definition for 'foreign_2'.
-invalid_models.clash2: Reverse query name for field 'foreign_2' clashes with related m2m field 'Target.src_safe'. Add a related_name argument to the definition for 'foreign_2'.
-invalid_models.clash2: Accessor for m2m field 'm2m_1' clashes with field 'Target.id'. Add a related_name argument to the definition for 'm2m_1'.
-invalid_models.clash2: Accessor for m2m field 'm2m_1' clashes with related field 'Target.id'. Add a related_name argument to the definition for 'm2m_1'.
-invalid_models.clash2: Reverse query name for m2m field 'm2m_1' clashes with field 'Target.id'. Add a related_name argument to the definition for 'm2m_1'.
-invalid_models.clash2: Reverse query name for m2m field 'm2m_1' clashes with related field 'Target.id'. Add a related_name argument to the definition for 'm2m_1'.
-invalid_models.clash2: Accessor for m2m field 'm2m_2' clashes with related field 'Target.src_safe'. Add a related_name argument to the definition for 'm2m_2'.
-invalid_models.clash2: Reverse query name for m2m field 'm2m_2' clashes with related field 'Target.src_safe'. Add a related_name argument to the definition for 'm2m_2'.
-invalid_models.clash3: Accessor for field 'foreign_1' clashes with field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'foreign_1'.
-invalid_models.clash3: Accessor for field 'foreign_1' clashes with related m2m field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'foreign_1'.
-invalid_models.clash3: Reverse query name for field 'foreign_1' clashes with field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'foreign_1'.
-invalid_models.clash3: Reverse query name for field 'foreign_1' clashes with related m2m field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'foreign_1'.
-invalid_models.clash3: Accessor for field 'foreign_2' clashes with m2m field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'foreign_2'.
-invalid_models.clash3: Accessor for field 'foreign_2' clashes with related m2m field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'foreign_2'.
-invalid_models.clash3: Reverse query name for field 'foreign_2' clashes with m2m field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'foreign_2'.
-invalid_models.clash3: Reverse query name for field 'foreign_2' clashes with related m2m field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'foreign_2'.
-invalid_models.clash3: Accessor for m2m field 'm2m_1' clashes with field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'm2m_1'.
-invalid_models.clash3: Accessor for m2m field 'm2m_1' clashes with related field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'm2m_1'.
-invalid_models.clash3: Reverse query name for m2m field 'm2m_1' clashes with field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'm2m_1'.
-invalid_models.clash3: Reverse query name for m2m field 'm2m_1' clashes with related field 'Target2.foreign_tgt'. Add a related_name argument to the definition for 'm2m_1'.
-invalid_models.clash3: Accessor for m2m field 'm2m_2' clashes with m2m field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'm2m_2'.
-invalid_models.clash3: Accessor for m2m field 'm2m_2' clashes with related field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'm2m_2'.
-invalid_models.clash3: Reverse query name for m2m field 'm2m_2' clashes with m2m field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'm2m_2'.
-invalid_models.clash3: Reverse query name for m2m field 'm2m_2' clashes with related field 'Target2.m2m_tgt'. Add a related_name argument to the definition for 'm2m_2'.
-invalid_models.clashforeign: Accessor for field 'foreign' clashes with field 'Target2.clashforeign_set'. Add a related_name argument to the definition for 'foreign'.
-invalid_models.clashm2m: Accessor for m2m field 'm2m' clashes with m2m field 'Target2.clashm2m_set'. Add a related_name argument to the definition for 'm2m'.
-invalid_models.target2: Accessor for field 'foreign_tgt' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'foreign_tgt'.
-invalid_models.target2: Accessor for field 'foreign_tgt' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'foreign_tgt'.
-invalid_models.target2: Accessor for field 'foreign_tgt' clashes with related field 'Target.target2_set'. Add a related_name argument to the definition for 'foreign_tgt'.
-invalid_models.target2: Accessor for field 'clashforeign_set' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'clashforeign_set'.
-invalid_models.target2: Accessor for field 'clashforeign_set' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'clashforeign_set'.
-invalid_models.target2: Accessor for field 'clashforeign_set' clashes with related field 'Target.target2_set'. Add a related_name argument to the definition for 'clashforeign_set'.
-invalid_models.target2: Accessor for m2m field 'm2m_tgt' clashes with related field 'Target.target2_set'. Add a related_name argument to the definition for 'm2m_tgt'.
-invalid_models.target2: Accessor for m2m field 'm2m_tgt' clashes with related field 'Target.target2_set'. Add a related_name argument to the definition for 'm2m_tgt'.
-invalid_models.target2: Accessor for m2m field 'm2m_tgt' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'm2m_tgt'.
-invalid_models.target2: Accessor for m2m field 'm2m_tgt' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'm2m_tgt'.
-invalid_models.target2: Accessor for m2m field 'm2m_tgt' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'm2m_tgt'.
-invalid_models.target2: Accessor for m2m field 'clashm2m_set' clashes with related field 'Target.target2_set'. Add a related_name argument to the definition for 'clashm2m_set'.
-invalid_models.target2: Accessor for m2m field 'clashm2m_set' clashes with related field 'Target.target2_set'. Add a related_name argument to the definition for 'clashm2m_set'.
-invalid_models.target2: Accessor for m2m field 'clashm2m_set' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'clashm2m_set'.
-invalid_models.target2: Accessor for m2m field 'clashm2m_set' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'clashm2m_set'.
-invalid_models.target2: Accessor for m2m field 'clashm2m_set' clashes with related m2m field 'Target.target2_set'. Add a related_name argument to the definition for 'clashm2m_set'.
-invalid_models.selfclashforeign: Accessor for field 'selfclashforeign_set' clashes with field 'SelfClashForeign.selfclashforeign_set'. Add a related_name argument to the definition for 'selfclashforeign_set'.
-invalid_models.selfclashforeign: Reverse query name for field 'selfclashforeign_set' clashes with field 'SelfClashForeign.selfclashforeign'. Add a related_name argument to the definition for 'selfclashforeign_set'.
-invalid_models.selfclashforeign: Accessor for field 'foreign_1' clashes with field 'SelfClashForeign.id'. Add a related_name argument to the definition for 'foreign_1'.
-invalid_models.selfclashforeign: Reverse query name for field 'foreign_1' clashes with field 'SelfClashForeign.id'. Add a related_name argument to the definition for 'foreign_1'.
-invalid_models.selfclashforeign: Accessor for field 'foreign_2' clashes with field 'SelfClashForeign.src_safe'. Add a related_name argument to the definition for 'foreign_2'.
-invalid_models.selfclashforeign: Reverse query name for field 'foreign_2' clashes with field 'SelfClashForeign.src_safe'. Add a related_name argument to the definition for 'foreign_2'.
-invalid_models.selfclashm2m: Accessor for m2m field 'selfclashm2m_set' clashes with m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'selfclashm2m_set'.
-invalid_models.selfclashm2m: Reverse query name for m2m field 'selfclashm2m_set' clashes with field 'SelfClashM2M.selfclashm2m'. Add a related_name argument to the definition for 'selfclashm2m_set'.
-invalid_models.selfclashm2m: Accessor for m2m field 'selfclashm2m_set' clashes with related m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'selfclashm2m_set'.
-invalid_models.selfclashm2m: Accessor for m2m field 'm2m_1' clashes with field 'SelfClashM2M.id'. Add a related_name argument to the definition for 'm2m_1'.
-invalid_models.selfclashm2m: Accessor for m2m field 'm2m_2' clashes with field 'SelfClashM2M.src_safe'. Add a related_name argument to the definition for 'm2m_2'.
-invalid_models.selfclashm2m: Reverse query name for m2m field 'm2m_1' clashes with field 'SelfClashM2M.id'. Add a related_name argument to the definition for 'm2m_1'.
-invalid_models.selfclashm2m: Reverse query name for m2m field 'm2m_2' clashes with field 'SelfClashM2M.src_safe'. Add a related_name argument to the definition for 'm2m_2'.
-invalid_models.selfclashm2m: Accessor for m2m field 'm2m_3' clashes with m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'm2m_3'.
-invalid_models.selfclashm2m: Accessor for m2m field 'm2m_3' clashes with related m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'm2m_3'.
-invalid_models.selfclashm2m: Accessor for m2m field 'm2m_3' clashes with related m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'm2m_3'.
-invalid_models.selfclashm2m: Accessor for m2m field 'm2m_4' clashes with m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'm2m_4'.
-invalid_models.selfclashm2m: Accessor for m2m field 'm2m_4' clashes with related m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'm2m_4'.
-invalid_models.selfclashm2m: Accessor for m2m field 'm2m_4' clashes with related m2m field 'SelfClashM2M.selfclashm2m_set'. Add a related_name argument to the definition for 'm2m_4'.
-invalid_models.selfclashm2m: Reverse query name for m2m field 'm2m_3' clashes with field 'SelfClashM2M.selfclashm2m'. Add a related_name argument to the definition for 'm2m_3'.
-invalid_models.selfclashm2m: Reverse query name for m2m field 'm2m_4' clashes with field 'SelfClashM2M.selfclashm2m'. Add a related_name argument to the definition for 'm2m_4'.
-"""
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/lookup/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,233 +0,0 @@
-"""
-7. The lookup API
-
-This demonstrates features of the database API.
-"""
-
-from django.db import models
-
-class Article(models.Model):
- headline = models.CharField(maxlength=100)
- pub_date = models.DateTimeField()
- class Meta:
- ordering = ('-pub_date', 'headline')
-
- def __str__(self):
- return self.headline
-
-__test__ = {'API_TESTS':r"""
-# Create a couple of Articles.
->>> from datetime import datetime
->>> a1 = Article(headline='Article 1', pub_date=datetime(2005, 7, 26))
->>> a1.save()
->>> a2 = Article(headline='Article 2', pub_date=datetime(2005, 7, 27))
->>> a2.save()
->>> a3 = Article(headline='Article 3', pub_date=datetime(2005, 7, 27))
->>> a3.save()
->>> a4 = Article(headline='Article 4', pub_date=datetime(2005, 7, 28))
->>> a4.save()
->>> a5 = Article(headline='Article 5', pub_date=datetime(2005, 8, 1, 9, 0))
->>> a5.save()
->>> a6 = Article(headline='Article 6', pub_date=datetime(2005, 8, 1, 8, 0))
->>> a6.save()
->>> a7 = Article(headline='Article 7', pub_date=datetime(2005, 7, 27))
->>> a7.save()
-
-# Each QuerySet gets iterator(), which is a generator that "lazily" returns
-# results using database-level iteration.
->>> for a in Article.objects.iterator():
-... print a.headline
-Article 5
-Article 6
-Article 4
-Article 2
-Article 3
-Article 7
-Article 1
-
-# iterator() can be used on any QuerySet.
->>> for a in Article.objects.filter(headline__endswith='4').iterator():
-... print a.headline
-Article 4
-
-# count() returns the number of objects matching search criteria.
->>> Article.objects.count()
-7L
->>> Article.objects.filter(pub_date__exact=datetime(2005, 7, 27)).count()
-3L
->>> Article.objects.filter(headline__startswith='Blah blah').count()
-0L
-
-# count() should respect sliced query sets.
->>> articles = Article.objects.all()
->>> articles.count()
-7L
->>> articles[:4].count()
-4
->>> articles[1:100].count()
-6L
->>> articles[10:100].count()
-0
-
-# Date and date/time lookups can also be done with strings.
->>> Article.objects.filter(pub_date__exact='2005-07-27 00:00:00').count()
-3L
-
-# in_bulk() takes a list of IDs and returns a dictionary mapping IDs
-# to objects.
->>> Article.objects.in_bulk([1, 2])
-{1: <Article: Article 1>, 2: <Article: Article 2>}
->>> Article.objects.in_bulk([3])
-{3: <Article: Article 3>}
->>> Article.objects.in_bulk([1000])
-{}
->>> Article.objects.in_bulk([])
-{}
->>> Article.objects.in_bulk('foo')
-Traceback (most recent call last):
- ...
-AssertionError: in_bulk() must be provided with a list of IDs.
->>> Article.objects.in_bulk()
-Traceback (most recent call last):
- ...
-TypeError: in_bulk() takes exactly 2 arguments (1 given)
->>> Article.objects.in_bulk(headline__startswith='Blah')
-Traceback (most recent call last):
- ...
-TypeError: in_bulk() got an unexpected keyword argument 'headline__startswith'
-
-# values() returns a list of dictionaries instead of object instances -- and
-# you can specify which fields you want to retrieve.
->>> Article.objects.values('headline')
-[{'headline': 'Article 5'}, {'headline': 'Article 6'}, {'headline': 'Article 4'}, {'headline': 'Article 2'}, {'headline': 'Article 3'}, {'headline': 'Article 7'}, {'headline': 'Article 1'}]
->>> Article.objects.filter(pub_date__exact=datetime(2005, 7, 27)).values('id')
-[{'id': 2}, {'id': 3}, {'id': 7}]
->>> list(Article.objects.values('id', 'headline')) == [{'id': 5, 'headline': 'Article 5'}, {'id': 6, 'headline': 'Article 6'}, {'id': 4, 'headline': 'Article 4'}, {'id': 2, 'headline': 'Article 2'}, {'id': 3, 'headline': 'Article 3'}, {'id': 7, 'headline': 'Article 7'}, {'id': 1, 'headline': 'Article 1'}]
-True
-
->>> for d in Article.objects.values('id', 'headline'):
-... i = d.items()
-... i.sort()
-... i
-[('headline', 'Article 5'), ('id', 5)]
-[('headline', 'Article 6'), ('id', 6)]
-[('headline', 'Article 4'), ('id', 4)]
-[('headline', 'Article 2'), ('id', 2)]
-[('headline', 'Article 3'), ('id', 3)]
-[('headline', 'Article 7'), ('id', 7)]
-[('headline', 'Article 1'), ('id', 1)]
-
-# You can use values() with iterator() for memory savings, because iterator()
-# uses database-level iteration.
->>> for d in Article.objects.values('id', 'headline').iterator():
-... i = d.items()
-... i.sort()
-... i
-[('headline', 'Article 5'), ('id', 5)]
-[('headline', 'Article 6'), ('id', 6)]
-[('headline', 'Article 4'), ('id', 4)]
-[('headline', 'Article 2'), ('id', 2)]
-[('headline', 'Article 3'), ('id', 3)]
-[('headline', 'Article 7'), ('id', 7)]
-[('headline', 'Article 1'), ('id', 1)]
-
-# if you don't specify which fields, all are returned
->>> list(Article.objects.filter(id=5).values()) == [{'id': 5, 'headline': 'Article 5', 'pub_date': datetime(2005, 8, 1, 9, 0)}]
-True
-
-# Every DateField and DateTimeField creates get_next_by_FOO() and
-# get_previous_by_FOO() methods.
-# In the case of identical date values, these methods will use the ID as a
-# fallback check. This guarantees that no records are skipped or duplicated.
->>> a1.get_next_by_pub_date()
-<Article: Article 2>
->>> a2.get_next_by_pub_date()
-<Article: Article 3>
->>> a2.get_next_by_pub_date(headline__endswith='6')
-<Article: Article 6>
->>> a3.get_next_by_pub_date()
-<Article: Article 7>
->>> a4.get_next_by_pub_date()
-<Article: Article 6>
->>> a5.get_next_by_pub_date()
-Traceback (most recent call last):
- ...
-DoesNotExist: Article matching query does not exist.
->>> a6.get_next_by_pub_date()
-<Article: Article 5>
->>> a7.get_next_by_pub_date()
-<Article: Article 4>
-
->>> a7.get_previous_by_pub_date()
-<Article: Article 3>
->>> a6.get_previous_by_pub_date()
-<Article: Article 4>
->>> a5.get_previous_by_pub_date()
-<Article: Article 6>
->>> a4.get_previous_by_pub_date()
-<Article: Article 7>
->>> a3.get_previous_by_pub_date()
-<Article: Article 2>
->>> a2.get_previous_by_pub_date()
-<Article: Article 1>
-
-# Underscores and percent signs have special meaning in the underlying
-# SQL code, but Django handles the quoting of them automatically.
->>> a8 = Article(headline='Article_ with underscore', pub_date=datetime(2005, 11, 20))
->>> a8.save()
->>> Article.objects.filter(headline__startswith='Article')
-[<Article: Article_ with underscore>, <Article: Article 5>, <Article: Article 6>, <Article: Article 4>, <Article: Article 2>, <Article: Article 3>, <Article: Article 7>, <Article: Article 1>]
->>> Article.objects.filter(headline__startswith='Article_')
-[<Article: Article_ with underscore>]
-
->>> a9 = Article(headline='Article% with percent sign', pub_date=datetime(2005, 11, 21))
->>> a9.save()
->>> Article.objects.filter(headline__startswith='Article')
-[<Article: Article% with percent sign>, <Article: Article_ with underscore>, <Article: Article 5>, <Article: Article 6>, <Article: Article 4>, <Article: Article 2>, <Article: Article 3>, <Article: Article 7>, <Article: Article 1>]
->>> Article.objects.filter(headline__startswith='Article%')
-[<Article: Article% with percent sign>]
-
-# exclude() is the opposite of filter() when doing lookups:
->>> Article.objects.filter(headline__contains='Article').exclude(headline__contains='with')
-[<Article: Article 5>, <Article: Article 6>, <Article: Article 4>, <Article: Article 2>, <Article: Article 3>, <Article: Article 7>, <Article: Article 1>]
->>> Article.objects.exclude(headline__startswith="Article_")
-[<Article: Article% with percent sign>, <Article: Article 5>, <Article: Article 6>, <Article: Article 4>, <Article: Article 2>, <Article: Article 3>, <Article: Article 7>, <Article: Article 1>]
->>> Article.objects.exclude(headline="Article 7")
-[<Article: Article% with percent sign>, <Article: Article_ with underscore>, <Article: Article 5>, <Article: Article 6>, <Article: Article 4>, <Article: Article 2>, <Article: Article 3>, <Article: Article 1>]
-
-# Backslashes also have special meaning in the underlying SQL code, but Django
-# automatically quotes them appropriately.
->>> a10 = Article(headline='Article with \\ backslash', pub_date=datetime(2005, 11, 22))
->>> a10.save()
->>> Article.objects.filter(headline__contains='\\')
-[<Article: Article with \ backslash>]
-
-# none() returns an EmptyQuerySet that behaves like any other QuerySet object
->>> Article.objects.none()
-[]
->>> Article.objects.none().filter(headline__startswith='Article')
-[]
->>> Article.objects.none().count()
-0
->>> [article for article in Article.objects.none().iterator()]
-[]
-
-# using __in with an empty list should return an empty query set
->>> Article.objects.filter(id__in=[])
-[]
-
->>> Article.objects.exclude(id__in=[])
-[<Article: Article with \ backslash>, <Article: Article% with percent sign>, <Article: Article_ with underscore>, <Article: Article 5>, <Article: Article 6>, <Article: Article 4>, <Article: Article 2>, <Article: Article 3>, <Article: Article 7>, <Article: Article 1>]
-
-# Programming errors are pointed out with nice error messages
->>> Article.objects.filter(pub_date_year='2005').count()
-Traceback (most recent call last):
- ...
-TypeError: Cannot resolve keyword 'pub_date_year' into field
-
->>> Article.objects.filter(headline__starts='Article')
-Traceback (most recent call last):
- ...
-TypeError: Cannot resolve keyword 'headline__starts' into field
-
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/m2m_and_m2o/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,65 +0,0 @@
-"""
-29. Many-to-many and many-to-one relationships to the same table
-
-Make sure to set ``related_name`` if you use relationships to the same table.
-"""
-
-from django.db import models
-
-class User(models.Model):
- username = models.CharField(maxlength=20)
-
-class Issue(models.Model):
- num = models.IntegerField()
- cc = models.ManyToManyField(User, blank=True, related_name='test_issue_cc')
- client = models.ForeignKey(User, related_name='test_issue_client')
-
- def __str__(self):
- return str(self.num)
-
- class Meta:
- ordering = ('num',)
-
-
-__test__ = {'API_TESTS':"""
->>> Issue.objects.all()
-[]
->>> r = User(username='russell')
->>> r.save()
->>> g = User(username='gustav')
->>> g.save()
-
->>> i = Issue(num=1)
->>> i.client = r
->>> i.save()
-
->>> i2 = Issue(num=2)
->>> i2.client = r
->>> i2.save()
->>> i2.cc.add(r)
-
->>> i3 = Issue(num=3)
->>> i3.client = g
->>> i3.save()
->>> i3.cc.add(r)
-
->>> from django.db.models.query import Q
-
->>> Issue.objects.filter(client=r.id)
-[<Issue: 1>, <Issue: 2>]
->>> Issue.objects.filter(client=g.id)
-[<Issue: 3>]
->>> Issue.objects.filter(cc__id__exact=g.id)
-[]
->>> Issue.objects.filter(cc__id__exact=r.id)
-[<Issue: 2>, <Issue: 3>]
-
-# These queries combine results from the m2m and the m2o relationships.
-# They're three ways of saying the same thing.
->>> Issue.objects.filter(Q(cc__id__exact=r.id) | Q(client=r.id))
-[<Issue: 1>, <Issue: 2>, <Issue: 3>]
->>> Issue.objects.filter(cc__id__exact=r.id) | Issue.objects.filter(client=r.id)
-[<Issue: 1>, <Issue: 2>, <Issue: 3>]
->>> Issue.objects.filter(Q(client=r.id) | Q(cc__id__exact=r.id))
-[<Issue: 1>, <Issue: 2>, <Issue: 3>]
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/m2m_intermediary/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,68 +0,0 @@
-"""
-9. Many-to-many relationships via an intermediary table
-
-For many-to-many relationships that need extra fields on the intermediary
-table, use an intermediary model.
-
-In this example, an ``Article`` can have multiple ``Reporter``s, and each
-``Article``-``Reporter`` combination (a ``Writer``) has a ``position`` field,
-which specifies the ``Reporter``'s position for the given article (e.g. "Staff
-writer").
-"""
-
-from django.db import models
-
-class Reporter(models.Model):
- first_name = models.CharField(maxlength=30)
- last_name = models.CharField(maxlength=30)
-
- def __str__(self):
- return "%s %s" % (self.first_name, self.last_name)
-
-class Article(models.Model):
- headline = models.CharField(maxlength=100)
- pub_date = models.DateField()
-
- def __str__(self):
- return self.headline
-
-class Writer(models.Model):
- reporter = models.ForeignKey(Reporter)
- article = models.ForeignKey(Article)
- position = models.CharField(maxlength=100)
-
- def __str__(self):
- return '%s (%s)' % (self.reporter, self.position)
-
-__test__ = {'API_TESTS':"""
-# Create a few Reporters.
->>> r1 = Reporter(first_name='John', last_name='Smith')
->>> r1.save()
->>> r2 = Reporter(first_name='Jane', last_name='Doe')
->>> r2.save()
-
-# Create an Article.
->>> from datetime import datetime
->>> a = Article(headline='This is a test', pub_date=datetime(2005, 7, 27))
->>> a.save()
-
-# Create a few Writers.
->>> w1 = Writer(reporter=r1, article=a, position='Main writer')
->>> w1.save()
->>> w2 = Writer(reporter=r2, article=a, position='Contributor')
->>> w2.save()
-
-# Play around with the API.
->>> a.writer_set.select_related().order_by('-position')
-[<Writer: John Smith (Main writer)>, <Writer: Jane Doe (Contributor)>]
->>> w1.reporter
-<Reporter: John Smith>
->>> w2.reporter
-<Reporter: Jane Doe>
->>> w1.article
-<Article: This is a test>
->>> w2.article
-<Article: This is a test>
->>> r1.writer_set.all()
-[<Writer: John Smith (Main writer)>]
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/m2m_multiple/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,79 +0,0 @@
-"""
-20. Multiple many-to-many relationships between the same two tables
-
-In this example, an Article can have many Categories (as "primary") and many
-Categories (as "secondary").
-
-Set ``related_name`` to designate what the reverse relationship is called.
-"""
-
-from django.db import models
-
-class Category(models.Model):
- name = models.CharField(maxlength=20)
- class Meta:
- ordering = ('name',)
-
- def __str__(self):
- return self.name
-
-class Article(models.Model):
- headline = models.CharField(maxlength=50)
- pub_date = models.DateTimeField()
- primary_categories = models.ManyToManyField(Category, related_name='primary_article_set')
- secondary_categories = models.ManyToManyField(Category, related_name='secondary_article_set')
- class Meta:
- ordering = ('pub_date',)
-
- def __str__(self):
- return self.headline
-
-__test__ = {'API_TESTS':"""
->>> from datetime import datetime
-
->>> c1 = Category(name='Sports')
->>> c1.save()
->>> c2 = Category(name='News')
->>> c2.save()
->>> c3 = Category(name='Crime')
->>> c3.save()
->>> c4 = Category(name='Life')
->>> c4.save()
-
->>> a1 = Article(headline='Area man steals', pub_date=datetime(2005, 11, 27))
->>> a1.save()
->>> a1.primary_categories.add(c2, c3)
->>> a1.secondary_categories.add(c4)
-
->>> a2 = Article(headline='Area man runs', pub_date=datetime(2005, 11, 28))
->>> a2.save()
->>> a2.primary_categories.add(c1, c2)
->>> a2.secondary_categories.add(c4)
-
->>> a1.primary_categories.all()
-[<Category: Crime>, <Category: News>]
-
->>> a2.primary_categories.all()
-[<Category: News>, <Category: Sports>]
-
->>> a1.secondary_categories.all()
-[<Category: Life>]
-
-
->>> c1.primary_article_set.all()
-[<Article: Area man runs>]
->>> c1.secondary_article_set.all()
-[]
->>> c2.primary_article_set.all()
-[<Article: Area man steals>, <Article: Area man runs>]
->>> c2.secondary_article_set.all()
-[]
->>> c3.primary_article_set.all()
-[<Article: Area man steals>]
->>> c3.secondary_article_set.all()
-[]
->>> c4.primary_article_set.all()
-[]
->>> c4.secondary_article_set.all()
-[<Article: Area man steals>, <Article: Area man runs>]
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/m2m_recursive/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,192 +0,0 @@
-"""
-28. Many-to-many relationships between the same two tables
-
-In this example, A Person can have many friends, who are also people. Friendship is a
-symmetrical relationship - if I am your friend, you are my friend.
-
-A person can also have many idols - but while I may idolize you, you may not think
-the same of me. 'Idols' is an example of a non-symmetrical m2m field. Only recursive
-m2m fields may be non-symmetrical, and they are symmetrical by default.
-
-This test validates that the m2m table will create a mangled name for the m2m table if
-there will be a clash, and tests that symmetry is preserved where appropriate.
-"""
-
-from django.db import models
-
-class Person(models.Model):
- name = models.CharField(maxlength=20)
- friends = models.ManyToManyField('self')
- idols = models.ManyToManyField('self', symmetrical=False, related_name='stalkers')
-
- def __str__(self):
- return self.name
-
-__test__ = {'API_TESTS':"""
->>> a = Person(name='Anne')
->>> a.save()
->>> b = Person(name='Bill')
->>> b.save()
->>> c = Person(name='Chuck')
->>> c.save()
->>> d = Person(name='David')
->>> d.save()
-
-# Add some friends in the direction of field definition
-# Anne is friends with Bill and Chuck
->>> a.friends.add(b,c)
-
-# David is friends with Anne and Chuck - add in reverse direction
->>> d.friends.add(a,c)
-
-# Who is friends with Anne?
->>> a.friends.all()
-[<Person: Bill>, <Person: Chuck>, <Person: David>]
-
-# Who is friends with Bill?
->>> b.friends.all()
-[<Person: Anne>]
-
-# Who is friends with Chuck?
->>> c.friends.all()
-[<Person: Anne>, <Person: David>]
-
-# Who is friends with David?
->>> d.friends.all()
-[<Person: Anne>, <Person: Chuck>]
-
-# Bill is already friends with Anne - add Anne again, but in the reverse direction
->>> b.friends.add(a)
-
-# Who is friends with Anne?
->>> a.friends.all()
-[<Person: Bill>, <Person: Chuck>, <Person: David>]
-
-# Who is friends with Bill?
->>> b.friends.all()
-[<Person: Anne>]
-
-# Remove Anne from Bill's friends
->>> b.friends.remove(a)
-
-# Who is friends with Anne?
->>> a.friends.all()
-[<Person: Chuck>, <Person: David>]
-
-# Who is friends with Bill?
->>> b.friends.all()
-[]
-
-# Clear Anne's group of friends
->>> a.friends.clear()
-
-# Who is friends with Anne?
->>> a.friends.all()
-[]
-
-# Reverse relationships should also be gone
-# Who is friends with Chuck?
->>> c.friends.all()
-[<Person: David>]
-
-# Who is friends with David?
->>> d.friends.all()
-[<Person: Chuck>]
-
-
-# Add some idols in the direction of field definition
-# Anne idolizes Bill and Chuck
->>> a.idols.add(b,c)
-
-# Bill idolizes Anne right back
->>> b.idols.add(a)
-
-# David is idolized by Anne and Chuck - add in reverse direction
->>> d.stalkers.add(a,c)
-
-# Who are Anne's idols?
->>> a.idols.all()
-[<Person: Bill>, <Person: Chuck>, <Person: David>]
-
-# Who is stalking Anne?
->>> a.stalkers.all()
-[<Person: Bill>]
-
-# Who are Bill's idols?
->>> b.idols.all()
-[<Person: Anne>]
-
-# Who is stalking Bill?
->>> b.stalkers.all()
-[<Person: Anne>]
-
-# Who are Chuck's idols?
->>> c.idols.all()
-[<Person: David>]
-
-# Who is stalking Chuck?
->>> c.stalkers.all()
-[<Person: Anne>]
-
-# Who are David's idols?
->>> d.idols.all()
-[]
-
-# Who is stalking David
->>> d.stalkers.all()
-[<Person: Anne>, <Person: Chuck>]
-
-# Bill is already being stalked by Anne - add Anne again, but in the reverse direction
->>> b.stalkers.add(a)
-
-# Who are Anne's idols?
->>> a.idols.all()
-[<Person: Bill>, <Person: Chuck>, <Person: David>]
-
-# Who is stalking Anne?
-[<Person: Bill>]
-
-# Who are Bill's idols
->>> b.idols.all()
-[<Person: Anne>]
-
-# Who is stalking Bill?
->>> b.stalkers.all()
-[<Person: Anne>]
-
-# Remove Anne from Bill's list of stalkers
->>> b.stalkers.remove(a)
-
-# Who are Anne's idols?
->>> a.idols.all()
-[<Person: Chuck>, <Person: David>]
-
-# Who is stalking Anne?
->>> a.stalkers.all()
-[<Person: Bill>]
-
-# Who are Bill's idols?
->>> b.idols.all()
-[<Person: Anne>]
-
-# Who is stalking Bill?
->>> b.stalkers.all()
-[]
-
-# Clear Anne's group of idols
->>> a.idols.clear()
-
-# Who are Anne's idols
->>> a.idols.all()
-[]
-
-# Reverse relationships should also be gone
-# Who is stalking Chuck?
->>> c.stalkers.all()
-[]
-
-# Who is friends with David?
->>> d.stalkers.all()
-[<Person: Chuck>]
-
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/m2o_recursive/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,40 +0,0 @@
-"""
-11. Relating an object to itself, many-to-one
-
-To define a many-to-one relationship between a model and itself, use
-``ForeignKey('self')``.
-
-In this example, a ``Category`` is related to itself. That is, each
-``Category`` has a parent ``Category``.
-
-Set ``related_name`` to designate what the reverse relationship is called.
-"""
-
-from django.db import models
-
-class Category(models.Model):
- name = models.CharField(maxlength=20)
- parent = models.ForeignKey('self', null=True, related_name='child_set')
-
- def __str__(self):
- return self.name
-
-__test__ = {'API_TESTS':"""
-# Create a few Category objects.
->>> r = Category(id=None, name='Root category', parent=None)
->>> r.save()
->>> c = Category(id=None, name='Child category', parent=r)
->>> c.save()
-
->>> r.child_set.all()
-[<Category: Child category>]
->>> r.child_set.get(name__startswith='Child')
-<Category: Child category>
->>> print r.parent
-None
-
->>> c.child_set.all()
-[]
->>> c.parent
-<Category: Root category>
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/m2o_recursive2/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,43 +0,0 @@
-"""
-12. Relating a model to another model more than once
-
-In this example, a ``Person`` can have a ``mother`` and ``father`` -- both of
-which are other ``Person`` objects.
-
-Set ``related_name`` to designate what the reverse relationship is called.
-"""
-
-from django.db import models
-
-class Person(models.Model):
- full_name = models.CharField(maxlength=20)
- mother = models.ForeignKey('self', null=True, related_name='mothers_child_set')
- father = models.ForeignKey('self', null=True, related_name='fathers_child_set')
-
- def __str__(self):
- return self.full_name
-
-__test__ = {'API_TESTS':"""
-# Create two Person objects -- the mom and dad in our family.
->>> dad = Person(full_name='John Smith Senior', mother=None, father=None)
->>> dad.save()
->>> mom = Person(full_name='Jane Smith', mother=None, father=None)
->>> mom.save()
-
-# Give mom and dad a kid.
->>> kid = Person(full_name='John Smith Junior', mother=mom, father=dad)
->>> kid.save()
-
->>> kid.mother
-<Person: Jane Smith>
->>> kid.father
-<Person: John Smith Senior>
->>> dad.fathers_child_set.all()
-[<Person: John Smith Junior>]
->>> mom.mothers_child_set.all()
-[<Person: John Smith Junior>]
->>> kid.mothers_child_set.all()
-[]
->>> kid.fathers_child_set.all()
-[]
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/manipulators/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,91 +0,0 @@
-"""
-27. Default manipulators
-
-Each model gets an AddManipulator and ChangeManipulator by default.
-"""
-
-from django.db import models
-
-class Musician(models.Model):
- first_name = models.CharField(maxlength=30)
- last_name = models.CharField(maxlength=30)
-
- def __str__(self):
- return "%s %s" % (self.first_name, self.last_name)
-
-class Album(models.Model):
- name = models.CharField(maxlength=100)
- musician = models.ForeignKey(Musician)
- release_date = models.DateField(blank=True, null=True)
-
- def __str__(self):
- return self.name
-
-__test__ = {'API_TESTS':"""
->>> from django.utils.datastructures import MultiValueDict
-
-# Create a Musician object via the default AddManipulator.
->>> man = Musician.AddManipulator()
->>> data = MultiValueDict({'first_name': ['Ella'], 'last_name': ['Fitzgerald']})
-
->>> man.get_validation_errors(data)
-{}
->>> man.do_html2python(data)
->>> m1 = man.save(data)
-
-# Verify it worked.
->>> Musician.objects.all()
-[<Musician: Ella Fitzgerald>]
->>> [m1] == list(Musician.objects.all())
-True
-
-# Attempt to add a Musician without a first_name.
->>> man.get_validation_errors(MultiValueDict({'last_name': ['Blakey']}))
-{'first_name': ['This field is required.']}
-
-# Attempt to add a Musician without a first_name and last_name.
->>> man.get_validation_errors(MultiValueDict({}))
-{'first_name': ['This field is required.'], 'last_name': ['This field is required.']}
-
-# Attempt to create an Album without a name or musician.
->>> man = Album.AddManipulator()
->>> man.get_validation_errors(MultiValueDict({}))
-{'musician': ['This field is required.'], 'name': ['This field is required.']}
-
-# Attempt to create an Album with an invalid musician.
->>> man.get_validation_errors(MultiValueDict({'name': ['Sallies Fforth'], 'musician': ['foo']}))
-{'musician': ["Select a valid choice; 'foo' is not in ['', '1']."]}
-
-# Attempt to create an Album with an invalid release_date.
->>> man.get_validation_errors(MultiValueDict({'name': ['Sallies Fforth'], 'musician': ['1'], 'release_date': 'today'}))
-{'release_date': ['Enter a valid date in YYYY-MM-DD format.']}
-
-# Create an Album without a release_date (because it's optional).
->>> data = MultiValueDict({'name': ['Ella and Basie'], 'musician': ['1']})
->>> man.get_validation_errors(data)
-{}
->>> man.do_html2python(data)
->>> a1 = man.save(data)
-
-# Verify it worked.
->>> Album.objects.all()
-[<Album: Ella and Basie>]
->>> Album.objects.get().musician
-<Musician: Ella Fitzgerald>
-
-# Create an Album with a release_date.
->>> data = MultiValueDict({'name': ['Ultimate Ella'], 'musician': ['1'], 'release_date': ['2005-02-13']})
->>> man.get_validation_errors(data)
-{}
->>> man.do_html2python(data)
->>> a2 = man.save(data)
-
-# Verify it worked.
->>> Album.objects.order_by('name')
-[<Album: Ella and Basie>, <Album: Ultimate Ella>]
->>> a2 = Album.objects.get(pk=2)
->>> a2
-<Album: Ultimate Ella>
->>> a2.release_date
-datetime.date(2005, 2, 13)
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/many_to_many/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,258 +0,0 @@
-"""
-5. Many-to-many relationships
-
-To define a many-to-many relationship, use ManyToManyField().
-
-In this example, an article can be published in multiple publications,
-and a publication has multiple articles.
-"""
-
-from django.db import models
-
-class Publication(models.Model):
- title = models.CharField(maxlength=30)
-
- def __str__(self):
- return self.title
-
- class Meta:
- ordering = ('title',)
-
-class Article(models.Model):
- headline = models.CharField(maxlength=100)
- publications = models.ManyToManyField(Publication)
-
- def __str__(self):
- return self.headline
-
- class Meta:
- ordering = ('headline',)
-
-__test__ = {'API_TESTS':"""
-# Create a couple of Publications.
->>> p1 = Publication(id=None, title='The Python Journal')
->>> p1.save()
->>> p2 = Publication(id=None, title='Science News')
->>> p2.save()
->>> p3 = Publication(id=None, title='Science Weekly')
->>> p3.save()
-
-# Create an Article.
->>> a1 = Article(id=None, headline='Django lets you build Web apps easily')
->>> a1.save()
-
-# Associate the Article with a Publication.
->>> a1.publications.add(p1)
-
-# Create another Article, and set it to appear in both Publications.
->>> a2 = Article(id=None, headline='NASA uses Python')
->>> a2.save()
->>> a2.publications.add(p1, p2)
->>> a2.publications.add(p3)
-
-# Adding a second time is OK
->>> a2.publications.add(p3)
-
-# Add a Publication directly via publications.add by using keyword arguments.
->>> new_publication = a2.publications.create(title='Highlights for Children')
-
-# Article objects have access to their related Publication objects.
->>> a1.publications.all()
-[<Publication: The Python Journal>]
->>> a2.publications.all()
-[<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]
-
-# Publication objects have access to their related Article objects.
->>> p2.article_set.all()
-[<Article: NASA uses Python>]
->>> p1.article_set.all()
-[<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
->>> Publication.objects.get(id=4).article_set.all()
-[<Article: NASA uses Python>]
-
-# We can perform kwarg queries across m2m relationships
->>> Article.objects.filter(publications__id__exact=1)
-[<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
->>> Article.objects.filter(publications__pk=1)
-[<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
->>> Article.objects.filter(publications=1)
-[<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
->>> Article.objects.filter(publications=p1)
-[<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
-
->>> Article.objects.filter(publications__title__startswith="Science")
-[<Article: NASA uses Python>, <Article: NASA uses Python>]
-
->>> Article.objects.filter(publications__title__startswith="Science").distinct()
-[<Article: NASA uses Python>]
-
-# The count() function respects distinct() as well.
->>> Article.objects.filter(publications__title__startswith="Science").count()
-2
-
->>> Article.objects.filter(publications__title__startswith="Science").distinct().count()
-1
-
->>> Article.objects.filter(publications__in=[1,2]).distinct()
-[<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
->>> Article.objects.filter(publications__in=[1,p2]).distinct()
-[<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
->>> Article.objects.filter(publications__in=[p1,p2]).distinct()
-[<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
-
-# Reverse m2m queries are supported (i.e., starting at the table that doesn't
-# have a ManyToManyField).
->>> Publication.objects.filter(id__exact=1)
-[<Publication: The Python Journal>]
->>> Publication.objects.filter(pk=1)
-[<Publication: The Python Journal>]
-
->>> Publication.objects.filter(article__headline__startswith="NASA")
-[<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]
-
->>> Publication.objects.filter(article__id__exact=1)
-[<Publication: The Python Journal>]
->>> Publication.objects.filter(article__pk=1)
-[<Publication: The Python Journal>]
->>> Publication.objects.filter(article=1)
-[<Publication: The Python Journal>]
->>> Publication.objects.filter(article=a1)
-[<Publication: The Python Journal>]
-
->>> Publication.objects.filter(article__in=[1,2]).distinct()
-[<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]
->>> Publication.objects.filter(article__in=[1,a2]).distinct()
-[<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]
->>> Publication.objects.filter(article__in=[a1,a2]).distinct()
-[<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]
-
-# If we delete a Publication, its Articles won't be able to access it.
->>> p1.delete()
->>> Publication.objects.all()
-[<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>]
->>> a1 = Article.objects.get(pk=1)
->>> a1.publications.all()
-[]
-
-# If we delete an Article, its Publications won't be able to access it.
->>> a2.delete()
->>> Article.objects.all()
-[<Article: Django lets you build Web apps easily>]
->>> p2.article_set.all()
-[]
-
-# Adding via the 'other' end of an m2m
->>> a4 = Article(headline='NASA finds intelligent life on Earth')
->>> a4.save()
->>> p2.article_set.add(a4)
->>> p2.article_set.all()
-[<Article: NASA finds intelligent life on Earth>]
->>> a4.publications.all()
-[<Publication: Science News>]
-
-# Adding via the other end using keywords
->>> new_article = p2.article_set.create(headline='Oxygen-free diet works wonders')
->>> p2.article_set.all()
-[<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]
->>> a5 = p2.article_set.all()[1]
->>> a5.publications.all()
-[<Publication: Science News>]
-
-# Removing publication from an article:
->>> a4.publications.remove(p2)
->>> p2.article_set.all()
-[<Article: Oxygen-free diet works wonders>]
->>> a4.publications.all()
-[]
-
-# And from the other end
->>> p2.article_set.remove(a5)
->>> p2.article_set.all()
-[]
->>> a5.publications.all()
-[]
-
-# Relation sets can be assigned. Assignment clears any existing set members
->>> p2.article_set = [a4, a5]
->>> p2.article_set.all()
-[<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]
->>> a4.publications.all()
-[<Publication: Science News>]
->>> a4.publications = [p3]
->>> p2.article_set.all()
-[<Article: Oxygen-free diet works wonders>]
->>> a4.publications.all()
-[<Publication: Science Weekly>]
-
-# Relation sets can be cleared:
->>> p2.article_set.clear()
->>> p2.article_set.all()
-[]
->>> a4.publications.all()
-[<Publication: Science Weekly>]
-
-# And you can clear from the other end
->>> p2.article_set.add(a4, a5)
->>> p2.article_set.all()
-[<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]
->>> a4.publications.all()
-[<Publication: Science News>, <Publication: Science Weekly>]
->>> a4.publications.clear()
->>> a4.publications.all()
-[]
->>> p2.article_set.all()
-[<Article: Oxygen-free diet works wonders>]
-
-# Relation sets can also be set using primary key values
->>> p2.article_set = [a4.id, a5.id]
->>> p2.article_set.all()
-[<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]
->>> a4.publications.all()
-[<Publication: Science News>]
->>> a4.publications = [p3.id]
->>> p2.article_set.all()
-[<Article: Oxygen-free diet works wonders>]
->>> a4.publications.all()
-[<Publication: Science Weekly>]
-
-# Recreate the article and Publication we have deleted.
->>> p1 = Publication(id=None, title='The Python Journal')
->>> p1.save()
->>> a2 = Article(id=None, headline='NASA uses Python')
->>> a2.save()
->>> a2.publications.add(p1, p2, p3)
-
-# Bulk delete some Publications - references to deleted publications should go
->>> Publication.objects.filter(title__startswith='Science').delete()
->>> Publication.objects.all()
-[<Publication: Highlights for Children>, <Publication: The Python Journal>]
->>> Article.objects.all()
-[<Article: Django lets you build Web apps easily>, <Article: NASA finds intelligent life on Earth>, <Article: NASA uses Python>, <Article: Oxygen-free diet works wonders>]
->>> a2.publications.all()
-[<Publication: The Python Journal>]
-
-# Bulk delete some articles - references to deleted objects should go
->>> q = Article.objects.filter(headline__startswith='Django')
->>> print q
-[<Article: Django lets you build Web apps easily>]
->>> q.delete()
-
-# After the delete, the QuerySet cache needs to be cleared, and the referenced objects should be gone
->>> print q
-[]
->>> p1.article_set.all()
-[<Article: NASA uses Python>]
-
-# An alternate to calling clear() is to assign the empty set
->>> p1.article_set = []
->>> p1.article_set.all()
-[]
-
->>> a2.publications = [p1, new_publication]
->>> a2.publications.all()
-[<Publication: Highlights for Children>, <Publication: The Python Journal>]
->>> a2.publications = []
->>> a2.publications.all()
-[]
-
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/many_to_one/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,266 +0,0 @@
-"""
-4. Many-to-one relationships
-
-To define a many-to-one relationship, use ``ForeignKey()`` .
-"""
-
-from django.db import models
-
-class Reporter(models.Model):
- first_name = models.CharField(maxlength=30)
- last_name = models.CharField(maxlength=30)
- email = models.EmailField()
-
- def __str__(self):
- return "%s %s" % (self.first_name, self.last_name)
-
-class Article(models.Model):
- headline = models.CharField(maxlength=100)
- pub_date = models.DateField()
- reporter = models.ForeignKey(Reporter)
-
- def __str__(self):
- return self.headline
-
- class Meta:
- ordering = ('headline',)
-
-__test__ = {'API_TESTS':"""
-# Create a few Reporters.
->>> r = Reporter(first_name='John', last_name='Smith', email='john@example.com')
->>> r.save()
-
->>> r2 = Reporter(first_name='Paul', last_name='Jones', email='paul@example.com')
->>> r2.save()
-
-# Create an Article.
->>> from datetime import datetime
->>> a = Article(id=None, headline="This is a test", pub_date=datetime(2005, 7, 27), reporter=r)
->>> a.save()
-
->>> a.reporter.id
-1
-
->>> a.reporter
-<Reporter: John Smith>
-
-# Article objects have access to their related Reporter objects.
->>> r = a.reporter
->>> r.first_name, r.last_name
-('John', 'Smith')
-
-# Create an Article via the Reporter object.
->>> new_article = r.article_set.create(headline="John's second story", pub_date=datetime(2005, 7, 29))
->>> new_article
-<Article: John's second story>
->>> new_article.reporter.id
-1
-
-# Create a new article, and add it to the article set.
->>> new_article2 = Article(headline="Paul's story", pub_date=datetime(2006, 1, 17))
->>> r.article_set.add(new_article2)
->>> new_article2.reporter.id
-1
->>> r.article_set.all()
-[<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]
-
-# Add the same article to a different article set - check that it moves.
->>> r2.article_set.add(new_article2)
->>> new_article2.reporter.id
-2
->>> r.article_set.all()
-[<Article: John's second story>, <Article: This is a test>]
->>> r2.article_set.all()
-[<Article: Paul's story>]
-
-# Assign the article to the reporter directly using the descriptor
->>> new_article2.reporter = r
->>> new_article2.save()
->>> new_article2.reporter
-<Reporter: John Smith>
->>> new_article2.reporter.id
-1
->>> r.article_set.all()
-[<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]
->>> r2.article_set.all()
-[]
-
-# Set the article back again using set descriptor.
->>> r2.article_set = [new_article, new_article2]
->>> r.article_set.all()
-[<Article: This is a test>]
->>> r2.article_set.all()
-[<Article: John's second story>, <Article: Paul's story>]
-
-# Funny case - assignment notation can only go so far; because the
-# ForeignKey cannot be null, existing members of the set must remain
->>> r.article_set = [new_article]
->>> r.article_set.all()
-[<Article: John's second story>, <Article: This is a test>]
->>> r2.article_set.all()
-[<Article: Paul's story>]
-
-# Reporter cannot be null - there should not be a clear or remove method
->>> hasattr(r2.article_set, 'remove')
-False
->>> hasattr(r2.article_set, 'clear')
-False
-
-# Reporter objects have access to their related Article objects.
->>> r.article_set.all()
-[<Article: John's second story>, <Article: This is a test>]
-
->>> r.article_set.filter(headline__startswith='This')
-[<Article: This is a test>]
-
->>> r.article_set.count()
-2
-
->>> r2.article_set.count()
-1
-
-# Get articles by id
->>> Article.objects.filter(id__exact=1)
-[<Article: This is a test>]
->>> Article.objects.filter(pk=1)
-[<Article: This is a test>]
-
-# Query on an article property
->>> Article.objects.filter(headline__startswith='This')
-[<Article: This is a test>]
-
-# The API automatically follows relationships as far as you need.
-# Use double underscores to separate relationships.
-# This works as many levels deep as you want. There's no limit.
-# Find all Articles for any Reporter whose first name is "John".
->>> Article.objects.filter(reporter__first_name__exact='John')
-[<Article: John's second story>, <Article: This is a test>]
-
-# Check that implied __exact also works
->>> Article.objects.filter(reporter__first_name='John')
-[<Article: John's second story>, <Article: This is a test>]
-
-# Query twice over the related field.
->>> Article.objects.filter(reporter__first_name__exact='John', reporter__last_name__exact='Smith')
-[<Article: John's second story>, <Article: This is a test>]
-
-# The underlying query only makes one join when a related table is referenced twice.
->>> query = Article.objects.filter(reporter__first_name__exact='John', reporter__last_name__exact='Smith')
->>> null, sql, null = query._get_sql_clause()
->>> sql.count('INNER JOIN')
-1
-
-# The automatically joined table has a predictable name.
->>> Article.objects.filter(reporter__first_name__exact='John').extra(where=["many_to_one_article__reporter.last_name='Smith'"])
-[<Article: John's second story>, <Article: This is a test>]
-
-# Find all Articles for the Reporter whose ID is 1.
-# Use direct ID check, pk check, and object comparison
->>> Article.objects.filter(reporter__id__exact=1)
-[<Article: John's second story>, <Article: This is a test>]
->>> Article.objects.filter(reporter__pk=1)
-[<Article: John's second story>, <Article: This is a test>]
->>> Article.objects.filter(reporter=1)
-[<Article: John's second story>, <Article: This is a test>]
->>> Article.objects.filter(reporter=r)
-[<Article: John's second story>, <Article: This is a test>]
-
->>> Article.objects.filter(reporter__in=[1,2]).distinct()
-[<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]
->>> Article.objects.filter(reporter__in=[r,r2]).distinct()
-[<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]
-
-# You need two underscores between "reporter" and "id" -- not one.
->>> Article.objects.filter(reporter_id__exact=1)
-Traceback (most recent call last):
- ...
-TypeError: Cannot resolve keyword 'reporter_id' into field
-
-# You need to specify a comparison clause
->>> Article.objects.filter(reporter_id=1)
-Traceback (most recent call last):
- ...
-TypeError: Cannot resolve keyword 'reporter_id' into field
-
-# You can also instantiate an Article by passing
-# the Reporter's ID instead of a Reporter object.
->>> a3 = Article(id=None, headline="This is a test", pub_date=datetime(2005, 7, 27), reporter_id=r.id)
->>> a3.save()
->>> a3.reporter.id
-1
->>> a3.reporter
-<Reporter: John Smith>
-
-# Similarly, the reporter ID can be a string.
->>> a4 = Article(id=None, headline="This is a test", pub_date=datetime(2005, 7, 27), reporter_id="1")
->>> a4.save()
->>> a4.reporter
-<Reporter: John Smith>
-
-# Reporters can be queried
->>> Reporter.objects.filter(id__exact=1)
-[<Reporter: John Smith>]
->>> Reporter.objects.filter(pk=1)
-[<Reporter: John Smith>]
->>> Reporter.objects.filter(first_name__startswith='John')
-[<Reporter: John Smith>]
-
-# Reporters can query in opposite direction of ForeignKey definition
->>> Reporter.objects.filter(article__id__exact=1)
-[<Reporter: John Smith>]
->>> Reporter.objects.filter(article__pk=1)
-[<Reporter: John Smith>]
->>> Reporter.objects.filter(article=1)
-[<Reporter: John Smith>]
->>> Reporter.objects.filter(article=a)
-[<Reporter: John Smith>]
-
->>> Reporter.objects.filter(article__in=[1,4]).distinct()
-[<Reporter: John Smith>]
->>> Reporter.objects.filter(article__in=[1,a3]).distinct()
-[<Reporter: John Smith>]
->>> Reporter.objects.filter(article__in=[a,a3]).distinct()
-[<Reporter: John Smith>]
-
->>> Reporter.objects.filter(article__headline__startswith='This')
-[<Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>]
->>> Reporter.objects.filter(article__headline__startswith='This').distinct()
-[<Reporter: John Smith>]
-
-# Counting in the opposite direction works in conjunction with distinct()
->>> Reporter.objects.filter(article__headline__startswith='This').count()
-3
->>> Reporter.objects.filter(article__headline__startswith='This').distinct().count()
-1
-
-# Queries can go round in circles.
->>> Reporter.objects.filter(article__reporter__first_name__startswith='John')
-[<Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>]
->>> Reporter.objects.filter(article__reporter__first_name__startswith='John').distinct()
-[<Reporter: John Smith>]
->>> Reporter.objects.filter(article__reporter__exact=r).distinct()
-[<Reporter: John Smith>]
-
-# Check that implied __exact also works
->>> Reporter.objects.filter(article__reporter=r).distinct()
-[<Reporter: John Smith>]
-
-# If you delete a reporter, his articles will be deleted.
->>> Article.objects.all()
-[<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>, <Article: This is a test>, <Article: This is a test>]
->>> Reporter.objects.order_by('first_name')
-[<Reporter: John Smith>, <Reporter: Paul Jones>]
->>> r2.delete()
->>> Article.objects.all()
-[<Article: John's second story>, <Article: This is a test>, <Article: This is a test>, <Article: This is a test>]
->>> Reporter.objects.order_by('first_name')
-[<Reporter: John Smith>]
-
-# Deletes using a join in the query
->>> Reporter.objects.filter(article__headline__startswith='This').delete()
->>> Reporter.objects.all()
-[]
->>> Article.objects.all()
-[]
-
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/many_to_one_null/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,124 +0,0 @@
-"""
-16. Many-to-one relationships that can be null
-
-To define a many-to-one relationship that can have a null foreign key, use
-``ForeignKey()`` with ``null=True`` .
-"""
-
-from django.db import models
-
-class Reporter(models.Model):
- name = models.CharField(maxlength=30)
-
- def __str__(self):
- return self.name
-
-class Article(models.Model):
- headline = models.CharField(maxlength=100)
- reporter = models.ForeignKey(Reporter, null=True)
-
- class Meta:
- ordering = ('headline',)
-
- def __str__(self):
- return self.headline
-
-__test__ = {'API_TESTS':"""
-# Create a Reporter.
->>> r = Reporter(name='John Smith')
->>> r.save()
-
-# Create an Article.
->>> a = Article(headline="First", reporter=r)
->>> a.save()
-
->>> a.reporter.id
-1
-
->>> a.reporter
-<Reporter: John Smith>
-
-# Article objects have access to their related Reporter objects.
->>> r = a.reporter
-
-# Create an Article via the Reporter object.
->>> a2 = r.article_set.create(headline="Second")
->>> a2
-<Article: Second>
->>> a2.reporter.id
-1
-
-# Reporter objects have access to their related Article objects.
->>> r.article_set.all()
-[<Article: First>, <Article: Second>]
->>> r.article_set.filter(headline__startswith='Fir')
-[<Article: First>]
->>> r.article_set.count()
-2
-
-# Create an Article with no Reporter by passing "reporter=None".
->>> a3 = Article(headline="Third", reporter=None)
->>> a3.save()
->>> a3.id
-3
->>> print a3.reporter
-None
-
-# Need to reget a3 to refresh the cache
->>> a3 = Article.objects.get(pk=3)
->>> print a3.reporter.id
-Traceback (most recent call last):
- ...
-AttributeError: 'NoneType' object has no attribute 'id'
-
-# Accessing an article's 'reporter' attribute returns None
-# if the reporter is set to None.
->>> print a3.reporter
-None
-
-# To retrieve the articles with no reporters set, use "reporter__isnull=True".
->>> Article.objects.filter(reporter__isnull=True)
-[<Article: Third>]
-
-# Set the reporter for the Third article
->>> r.article_set.add(a3)
->>> r.article_set.all()
-[<Article: First>, <Article: Second>, <Article: Third>]
-
-# Remove an article from the set, and check that it was removed.
->>> r.article_set.remove(a3)
->>> r.article_set.all()
-[<Article: First>, <Article: Second>]
->>> Article.objects.filter(reporter__isnull=True)
-[<Article: Third>]
-
-# Create another article and reporter
->>> r2 = Reporter(name='Paul Jones')
->>> r2.save()
->>> a4 = r2.article_set.create(headline='Fourth')
->>> r2.article_set.all()
-[<Article: Fourth>]
-
-# Try to remove a4 from a set it does not belong to
->>> r.article_set.remove(a4)
-Traceback (most recent call last):
-...
-DoesNotExist: <Article: Fourth> is not related to <Reporter: John Smith>.
-
->>> r2.article_set.all()
-[<Article: Fourth>]
-
-# Use descriptor assignment to allocate ForeignKey. Null is legal, so
-# existing members of set that are not in the assignment set are set null
->>> r2.article_set = [a2, a3]
->>> r2.article_set.all()
-[<Article: Second>, <Article: Third>]
-
-# Clear the rest of the set
->>> r.article_set.clear()
->>> r.article_set.all()
-[]
->>> Article.objects.filter(reporter__isnull=True)
-[<Article: First>, <Article: Fourth>]
-
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/model_forms/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,464 +0,0 @@
-"""
-36. Generating HTML forms from models
-
-Django provides shortcuts for creating Form objects from a model class and a
-model instance.
-
-The function django.newforms.form_for_model() takes a model class and returns
-a Form that is tied to the model. This Form works just like any other Form,
-with one additional method: save(). The save() method creates an instance
-of the model and returns that newly created instance. It saves the instance to
-the database if save(commit=True), which is default. If you pass
-commit=False, then you'll get the object without committing the changes to the
-database.
-
-The function django.newforms.form_for_instance() takes a model instance and
-returns a Form that is tied to the instance. This form works just like any
-other Form, with one additional method: save(). The save()
-method updates the model instance. It also takes a commit=True parameter.
-
-The function django.newforms.save_instance() takes a bound form instance and a
-model instance and saves the form's clean_data into the instance. It also takes
-a commit=True parameter.
-"""
-
-from django.db import models
-
-class Category(models.Model):
- name = models.CharField(maxlength=20)
- url = models.CharField('The URL', maxlength=40)
-
- def __str__(self):
- return self.name
-
-class Writer(models.Model):
- name = models.CharField(maxlength=50, help_text='Use both first and last names.')
-
- def __str__(self):
- return self.name
-
-class Article(models.Model):
- headline = models.CharField(maxlength=50)
- pub_date = models.DateField()
- created = models.DateField(editable=False)
- writer = models.ForeignKey(Writer)
- article = models.TextField()
- categories = models.ManyToManyField(Category, blank=True)
-
- def save(self):
- import datetime
- if not self.id:
- self.created = datetime.date.today()
- return super(Article, self).save()
-
- def __str__(self):
- return self.headline
-
-class PhoneNumber(models.Model):
- phone = models.PhoneNumberField()
- description = models.CharField(maxlength=20)
-
- def __str__(self):
- return self.phone
-
-__test__ = {'API_TESTS': """
->>> from django.newforms import form_for_model, form_for_instance, save_instance, BaseForm, Form, CharField
->>> import datetime
-
->>> Category.objects.all()
-[]
-
->>> CategoryForm = form_for_model(Category)
->>> f = CategoryForm()
->>> print f
-<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="20" /></td></tr>
-<tr><th><label for="id_url">The URL:</label></th><td><input id="id_url" type="text" name="url" maxlength="40" /></td></tr>
->>> print f.as_ul()
-<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" maxlength="20" /></li>
-<li><label for="id_url">The URL:</label> <input id="id_url" type="text" name="url" maxlength="40" /></li>
->>> print f['name']
-<input id="id_name" type="text" name="name" maxlength="20" />
-
->>> f = CategoryForm(auto_id=False)
->>> print f.as_ul()
-<li>Name: <input type="text" name="name" maxlength="20" /></li>
-<li>The URL: <input type="text" name="url" maxlength="40" /></li>
-
->>> f = CategoryForm({'name': 'Entertainment', 'url': 'entertainment'})
->>> f.is_valid()
-True
->>> f.clean_data
-{'url': u'entertainment', 'name': u'Entertainment'}
->>> obj = f.save()
->>> obj
-<Category: Entertainment>
->>> Category.objects.all()
-[<Category: Entertainment>]
-
->>> f = CategoryForm({'name': "It's a test", 'url': 'test'})
->>> f.is_valid()
-True
->>> f.clean_data
-{'url': u'test', 'name': u"It's a test"}
->>> obj = f.save()
->>> obj
-<Category: It's a test>
->>> Category.objects.all()
-[<Category: Entertainment>, <Category: It's a test>]
-
-If you call save() with commit=False, then it will return an object that
-hasn't yet been saved to the database. In this case, it's up to you to call
-save() on the resulting model instance.
->>> f = CategoryForm({'name': 'Third test', 'url': 'third'})
->>> f.is_valid()
-True
->>> f.clean_data
-{'url': u'third', 'name': u'Third test'}
->>> obj = f.save(commit=False)
->>> obj
-<Category: Third test>
->>> Category.objects.all()
-[<Category: Entertainment>, <Category: It's a test>]
->>> obj.save()
->>> Category.objects.all()
-[<Category: Entertainment>, <Category: It's a test>, <Category: Third test>]
-
-If you call save() with invalid data, you'll get a ValueError.
->>> f = CategoryForm({'name': '', 'url': 'foo'})
->>> f.errors
-{'name': [u'This field is required.']}
->>> f.clean_data
-Traceback (most recent call last):
-...
-AttributeError: 'CategoryForm' object has no attribute 'clean_data'
->>> f.save()
-Traceback (most recent call last):
-...
-ValueError: The Category could not be created because the data didn't validate.
->>> f = CategoryForm({'name': '', 'url': 'foo'})
->>> f.save()
-Traceback (most recent call last):
-...
-ValueError: The Category could not be created because the data didn't validate.
-
-Create a couple of Writers.
->>> w = Writer(name='Mike Royko')
->>> w.save()
->>> w = Writer(name='Bob Woodward')
->>> w.save()
-
-ManyToManyFields are represented by a MultipleChoiceField, and ForeignKeys are
-represented by a ChoiceField.
->>> ArticleForm = form_for_model(Article)
->>> f = ArticleForm(auto_id=False)
->>> print f
-<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" /></td></tr>
-<tr><th>Pub date:</th><td><input type="text" name="pub_date" /></td></tr>
-<tr><th>Writer:</th><td><select name="writer">
-<option value="" selected="selected">---------</option>
-<option value="1">Mike Royko</option>
-<option value="2">Bob Woodward</option>
-</select></td></tr>
-<tr><th>Article:</th><td><textarea name="article"></textarea></td></tr>
-<tr><th>Categories:</th><td><select multiple="multiple" name="categories">
-<option value="1">Entertainment</option>
-<option value="2">It's a test</option>
-<option value="3">Third test</option>
-</select><br /> Hold down "Control", or "Command" on a Mac, to select more than one.</td></tr>
-
-You can pass a custom Form class to form_for_model. Make sure it's a
-subclass of BaseForm, not Form.
->>> class CustomForm(BaseForm):
-... def say_hello(self):
-... print 'hello'
->>> CategoryForm = form_for_model(Category, form=CustomForm)
->>> f = CategoryForm()
->>> f.say_hello()
-hello
-
-Use form_for_instance to create a Form from a model instance. The difference
-between this Form and one created via form_for_model is that the object's
-current values are inserted as 'initial' data in each Field.
->>> w = Writer.objects.get(name='Mike Royko')
->>> RoykoForm = form_for_instance(w)
->>> f = RoykoForm(auto_id=False)
->>> print f
-<tr><th>Name:</th><td><input type="text" name="name" value="Mike Royko" maxlength="50" /><br />Use both first and last names.</td></tr>
-
->>> art = Article(headline='Test article', pub_date=datetime.date(1988, 1, 4), writer=w, article='Hello.')
->>> art.save()
->>> art.id
-1
->>> TestArticleForm = form_for_instance(art)
->>> f = TestArticleForm(auto_id=False)
->>> print f.as_ul()
-<li>Headline: <input type="text" name="headline" value="Test article" maxlength="50" /></li>
-<li>Pub date: <input type="text" name="pub_date" value="1988-01-04" /></li>
-<li>Writer: <select name="writer">
-<option value="">---------</option>
-<option value="1" selected="selected">Mike Royko</option>
-<option value="2">Bob Woodward</option>
-</select></li>
-<li>Article: <textarea name="article">Hello.</textarea></li>
-<li>Categories: <select multiple="multiple" name="categories">
-<option value="1">Entertainment</option>
-<option value="2">It's a test</option>
-<option value="3">Third test</option>
-</select> Hold down "Control", or "Command" on a Mac, to select more than one.</li>
->>> f = TestArticleForm({'headline': u'New headline', 'pub_date': u'1988-01-04', 'writer': u'1', 'article': 'Hello.'})
->>> f.is_valid()
-True
->>> new_art = f.save()
->>> new_art.id
-1
->>> new_art = Article.objects.get(id=1)
->>> new_art.headline
-'New headline'
-
-Add some categories and test the many-to-many form output.
->>> new_art.categories.all()
-[]
->>> new_art.categories.add(Category.objects.get(name='Entertainment'))
->>> new_art.categories.all()
-[<Category: Entertainment>]
->>> TestArticleForm = form_for_instance(new_art)
->>> f = TestArticleForm(auto_id=False)
->>> print f.as_ul()
-<li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" /></li>
-<li>Pub date: <input type="text" name="pub_date" value="1988-01-04" /></li>
-<li>Writer: <select name="writer">
-<option value="">---------</option>
-<option value="1" selected="selected">Mike Royko</option>
-<option value="2">Bob Woodward</option>
-</select></li>
-<li>Article: <textarea name="article">Hello.</textarea></li>
-<li>Categories: <select multiple="multiple" name="categories">
-<option value="1" selected="selected">Entertainment</option>
-<option value="2">It's a test</option>
-<option value="3">Third test</option>
-</select> Hold down "Control", or "Command" on a Mac, to select more than one.</li>
-
->>> f = TestArticleForm({'headline': u'New headline', 'pub_date': u'1988-01-04',
-... 'writer': u'1', 'article': u'Hello.', 'categories': [u'1', u'2']})
->>> new_art = f.save()
->>> new_art.id
-1
->>> new_art = Article.objects.get(id=1)
->>> new_art.categories.all()
-[<Category: Entertainment>, <Category: It's a test>]
-
-Now, submit form data with no categories. This deletes the existing categories.
->>> f = TestArticleForm({'headline': u'New headline', 'pub_date': u'1988-01-04',
-... 'writer': u'1', 'article': u'Hello.'})
->>> new_art = f.save()
->>> new_art.id
-1
->>> new_art = Article.objects.get(id=1)
->>> new_art.categories.all()
-[]
-
-Create a new article, with categories, via the form.
->>> ArticleForm = form_for_model(Article)
->>> f = ArticleForm({'headline': u'The walrus was Paul', 'pub_date': u'1967-11-01',
-... 'writer': u'1', 'article': u'Test.', 'categories': [u'1', u'2']})
->>> new_art = f.save()
->>> new_art.id
-2
->>> new_art = Article.objects.get(id=2)
->>> new_art.categories.all()
-[<Category: Entertainment>, <Category: It's a test>]
-
-Create a new article, with no categories, via the form.
->>> ArticleForm = form_for_model(Article)
->>> f = ArticleForm({'headline': u'The walrus was Paul', 'pub_date': u'1967-11-01',
-... 'writer': u'1', 'article': u'Test.'})
->>> new_art = f.save()
->>> new_art.id
-3
->>> new_art = Article.objects.get(id=3)
->>> new_art.categories.all()
-[]
-
-Here, we define a custom Form. Because it happens to have the same fields as
-the Category model, we can use save_instance() to apply its changes to an
-existing Category instance.
->>> class ShortCategory(Form):
-... name = CharField(max_length=5)
-... url = CharField(max_length=3)
->>> cat = Category.objects.get(name='Third test')
->>> cat
-<Category: Third test>
->>> cat.id
-3
->>> sc = ShortCategory({'name': 'Third', 'url': '3rd'})
->>> save_instance(sc, cat)
-<Category: Third>
->>> Category.objects.get(id=3)
-<Category: Third>
-
-Here, we demonstrate that choices for a ForeignKey ChoiceField are determined
-at runtime, based on the data in the database when the form is displayed, not
-the data in the database when the form is instantiated.
->>> ArticleForm = form_for_model(Article)
->>> f = ArticleForm(auto_id=False)
->>> print f.as_ul()
-<li>Headline: <input type="text" name="headline" maxlength="50" /></li>
-<li>Pub date: <input type="text" name="pub_date" /></li>
-<li>Writer: <select name="writer">
-<option value="" selected="selected">---------</option>
-<option value="1">Mike Royko</option>
-<option value="2">Bob Woodward</option>
-</select></li>
-<li>Article: <textarea name="article"></textarea></li>
-<li>Categories: <select multiple="multiple" name="categories">
-<option value="1">Entertainment</option>
-<option value="2">It's a test</option>
-<option value="3">Third</option>
-</select> Hold down "Control", or "Command" on a Mac, to select more than one.</li>
->>> Category.objects.create(name='Fourth', url='4th')
-<Category: Fourth>
->>> Writer.objects.create(name='Carl Bernstein')
-<Writer: Carl Bernstein>
->>> print f.as_ul()
-<li>Headline: <input type="text" name="headline" maxlength="50" /></li>
-<li>Pub date: <input type="text" name="pub_date" /></li>
-<li>Writer: <select name="writer">
-<option value="" selected="selected">---------</option>
-<option value="1">Mike Royko</option>
-<option value="2">Bob Woodward</option>
-<option value="3">Carl Bernstein</option>
-</select></li>
-<li>Article: <textarea name="article"></textarea></li>
-<li>Categories: <select multiple="multiple" name="categories">
-<option value="1">Entertainment</option>
-<option value="2">It's a test</option>
-<option value="3">Third</option>
-<option value="4">Fourth</option>
-</select> Hold down "Control", or "Command" on a Mac, to select more than one.</li>
-
-# ModelChoiceField ############################################################
-
->>> from django.newforms import ModelChoiceField, ModelMultipleChoiceField
-
->>> f = ModelChoiceField(Category.objects.all())
->>> f.clean('')
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean(None)
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean(0)
-Traceback (most recent call last):
-...
-ValidationError: [u'Select a valid choice. That choice is not one of the available choices.']
->>> f.clean(3)
-<Category: Third>
->>> f.clean(2)
-<Category: It's a test>
-
-# Add a Category object *after* the ModelChoiceField has already been
-# instantiated. This proves clean() checks the database during clean() rather
-# than caching it at time of instantiation.
->>> Category.objects.create(name='Fifth', url='5th')
-<Category: Fifth>
->>> f.clean(5)
-<Category: Fifth>
-
-# Delete a Category object *after* the ModelChoiceField has already been
-# instantiated. This proves clean() checks the database during clean() rather
-# than caching it at time of instantiation.
->>> Category.objects.get(url='5th').delete()
->>> f.clean(5)
-Traceback (most recent call last):
-...
-ValidationError: [u'Select a valid choice. That choice is not one of the available choices.']
-
->>> f = ModelChoiceField(Category.objects.filter(pk=1), required=False)
->>> print f.clean('')
-None
->>> f.clean('')
->>> f.clean('1')
-<Category: Entertainment>
->>> f.clean('100')
-Traceback (most recent call last):
-...
-ValidationError: [u'Select a valid choice. That choice is not one of the available choices.']
-
-# ModelMultipleChoiceField ####################################################
-
->>> f = ModelMultipleChoiceField(Category.objects.all())
->>> f.clean(None)
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean([])
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean([1])
-[<Category: Entertainment>]
->>> f.clean([2])
-[<Category: It's a test>]
->>> f.clean(['1'])
-[<Category: Entertainment>]
->>> f.clean(['1', '2'])
-[<Category: Entertainment>, <Category: It's a test>]
->>> f.clean([1, '2'])
-[<Category: Entertainment>, <Category: It's a test>]
->>> f.clean((1, '2'))
-[<Category: Entertainment>, <Category: It's a test>]
->>> f.clean(['100'])
-Traceback (most recent call last):
-...
-ValidationError: [u'Select a valid choice. 100 is not one of the available choices.']
->>> f.clean('hello')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a list of values.']
-
-# Add a Category object *after* the ModelChoiceField has already been
-# instantiated. This proves clean() checks the database during clean() rather
-# than caching it at time of instantiation.
->>> Category.objects.create(id=6, name='Sixth', url='6th')
-<Category: Sixth>
->>> f.clean([6])
-[<Category: Sixth>]
-
-# Delete a Category object *after* the ModelChoiceField has already been
-# instantiated. This proves clean() checks the database during clean() rather
-# than caching it at time of instantiation.
->>> Category.objects.get(url='6th').delete()
->>> f.clean([6])
-Traceback (most recent call last):
-...
-ValidationError: [u'Select a valid choice. 6 is not one of the available choices.']
-
->>> f = ModelMultipleChoiceField(Category.objects.all(), required=False)
->>> f.clean([])
-[]
->>> f.clean(())
-[]
->>> f.clean(['10'])
-Traceback (most recent call last):
-...
-ValidationError: [u'Select a valid choice. 10 is not one of the available choices.']
->>> f.clean(['3', '10'])
-Traceback (most recent call last):
-...
-ValidationError: [u'Select a valid choice. 10 is not one of the available choices.']
->>> f.clean(['1', '10'])
-Traceback (most recent call last):
-...
-ValidationError: [u'Select a valid choice. 10 is not one of the available choices.']
-
-# PhoneNumberField ############################################################
-
->>> PhoneNumberForm = form_for_model(PhoneNumber)
->>> f = PhoneNumberForm({'phone': '(312) 555-1212', 'description': 'Assistance'})
->>> f.is_valid()
-True
->>> f.clean_data
-{'phone': u'312-555-1212', 'description': u'Assistance'}
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/model_inheritance/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,53 +0,0 @@
-"""
-XX. Model inheritance
-
-Model inheritance isn't yet supported.
-"""
-
-from django.db import models
-
-class Place(models.Model):
- name = models.CharField(maxlength=50)
- address = models.CharField(maxlength=80)
-
- def __str__(self):
- return "%s the place" % self.name
-
-class Restaurant(Place):
- serves_hot_dogs = models.BooleanField()
- serves_pizza = models.BooleanField()
-
- def __str__(self):
- return "%s the restaurant" % self.name
-
-class ItalianRestaurant(Restaurant):
- serves_gnocchi = models.BooleanField()
-
- def __str__(self):
- return "%s the italian restaurant" % self.name
-
-__test__ = {'API_TESTS':"""
-# Make sure Restaurant has the right fields in the right order.
->>> [f.name for f in Restaurant._meta.fields]
-['id', 'name', 'address', 'serves_hot_dogs', 'serves_pizza']
-
-# Make sure ItalianRestaurant has the right fields in the right order.
->>> [f.name for f in ItalianRestaurant._meta.fields]
-['id', 'name', 'address', 'serves_hot_dogs', 'serves_pizza', 'serves_gnocchi']
-
-# Create a couple of Places.
->>> p1 = Place(name='Master Shakes', address='666 W. Jersey')
->>> p1.save()
->>> p2 = Place(name='Ace Hardware', address='1013 N. Ashland')
->>> p2.save()
-
-# Test constructor for Restaurant.
->>> r = Restaurant(name='Demon Dogs', address='944 W. Fullerton', serves_hot_dogs=True, serves_pizza=False)
->>> r.save()
-
-# Test the constructor for ItalianRestaurant.
->>> ir = ItalianRestaurant(name='Ristorante Miron', address='1234 W. Elm', serves_hot_dogs=False, serves_pizza=False, serves_gnocchi=True)
->>> ir.save()
-
-
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/mutually_referential/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,32 +0,0 @@
-"""
-24. Mutually referential many-to-one relationships
-
-To define a many-to-one relationship, use ``ForeignKey()`` .
-"""
-
-from django.db.models import *
-
-class Parent(Model):
- name = CharField(maxlength=100, core=True)
- bestchild = ForeignKey("Child", null=True, related_name="favoured_by")
-
-class Child(Model):
- name = CharField(maxlength=100)
- parent = ForeignKey(Parent)
-
-__test__ = {'API_TESTS':"""
-# Create a Parent
->>> q = Parent(name='Elizabeth')
->>> q.save()
-
-# Create some children
->>> c = q.child_set.create(name='Charles')
->>> e = q.child_set.create(name='Edward')
-
-# Set the best child
->>> q.bestchild = c
->>> q.save()
-
->>> q.delete()
-
-"""}
\ No newline at end of file
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/one_to_one/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,168 +0,0 @@
-"""
-10. One-to-one relationships
-
-To define a one-to-one relationship, use ``OneToOneField()``.
-
-In this example, a ``Place`` optionally can be a ``Restaurant``.
-"""
-
-from django.db import models
-
-class Place(models.Model):
- name = models.CharField(maxlength=50)
- address = models.CharField(maxlength=80)
-
- def __str__(self):
- return "%s the place" % self.name
-
-class Restaurant(models.Model):
- place = models.OneToOneField(Place)
- serves_hot_dogs = models.BooleanField()
- serves_pizza = models.BooleanField()
-
- def __str__(self):
- return "%s the restaurant" % self.place.name
-
-class Waiter(models.Model):
- restaurant = models.ForeignKey(Restaurant)
- name = models.CharField(maxlength=50)
-
- def __str__(self):
- return "%s the waiter at %s" % (self.name, self.restaurant)
-
-class ManualPrimaryKey(models.Model):
- primary_key = models.CharField(maxlength=10, primary_key=True)
- name = models.CharField(maxlength = 50)
-
-class RelatedModel(models.Model):
- link = models.OneToOneField(ManualPrimaryKey)
- name = models.CharField(maxlength = 50)
-
-__test__ = {'API_TESTS':"""
-# Create a couple of Places.
->>> p1 = Place(name='Demon Dogs', address='944 W. Fullerton')
->>> p1.save()
->>> p2 = Place(name='Ace Hardware', address='1013 N. Ashland')
->>> p2.save()
-
-# Create a Restaurant. Pass the ID of the "parent" object as this object's ID.
->>> r = Restaurant(place=p1, serves_hot_dogs=True, serves_pizza=False)
->>> r.save()
-
-# A Restaurant can access its place.
->>> r.place
-<Place: Demon Dogs the place>
-
-# A Place can access its restaurant, if available.
->>> p1.restaurant
-<Restaurant: Demon Dogs the restaurant>
-
-# p2 doesn't have an associated restaurant.
->>> p2.restaurant
-Traceback (most recent call last):
- ...
-DoesNotExist: Restaurant matching query does not exist.
-
-# Set the place using assignment notation. Because place is the primary key on Restaurant,
-# the save will create a new restaurant
->>> r.place = p2
->>> r.save()
->>> p2.restaurant
-<Restaurant: Ace Hardware the restaurant>
->>> r.place
-<Place: Ace Hardware the place>
-
-# Set the place back again, using assignment in the reverse direction
-# Need to reget restaurant object first, because the reverse set
-# can't update the existing restaurant instance
->>> p1.restaurant = r
->>> r.save()
->>> p1.restaurant
-<Restaurant: Demon Dogs the restaurant>
-
->>> r = Restaurant.objects.get(pk=1)
->>> r.place
-<Place: Demon Dogs the place>
-
-# Restaurant.objects.all() just returns the Restaurants, not the Places.
-# Note that there are two restaurants - Ace Hardware the Restaurant was created
-# in the call to r.place = p2. This means there are multiple restaurants referencing
-# a single place...
->>> Restaurant.objects.all()
-[<Restaurant: Demon Dogs the restaurant>, <Restaurant: Ace Hardware the restaurant>]
-
-# Place.objects.all() returns all Places, regardless of whether they have
-# Restaurants.
->>> Place.objects.order_by('name')
-[<Place: Ace Hardware the place>, <Place: Demon Dogs the place>]
-
->>> Restaurant.objects.get(place__id__exact=1)
-<Restaurant: Demon Dogs the restaurant>
->>> Restaurant.objects.get(pk=1)
-<Restaurant: Demon Dogs the restaurant>
->>> Restaurant.objects.get(place__exact=1)
-<Restaurant: Demon Dogs the restaurant>
->>> Restaurant.objects.get(place__exact=p1)
-<Restaurant: Demon Dogs the restaurant>
->>> Restaurant.objects.get(place=1)
-<Restaurant: Demon Dogs the restaurant>
->>> Restaurant.objects.get(place=p1)
-<Restaurant: Demon Dogs the restaurant>
->>> Restaurant.objects.get(place__pk=1)
-<Restaurant: Demon Dogs the restaurant>
->>> Restaurant.objects.get(place__name__startswith="Demon")
-<Restaurant: Demon Dogs the restaurant>
-
->>> Place.objects.get(id__exact=1)
-<Place: Demon Dogs the place>
->>> Place.objects.get(pk=1)
-<Place: Demon Dogs the place>
->>> Place.objects.get(restaurant__place__exact=1)
-<Place: Demon Dogs the place>
->>> Place.objects.get(restaurant__place__exact=p1)
-<Place: Demon Dogs the place>
->>> Place.objects.get(restaurant__pk=1)
-<Place: Demon Dogs the place>
->>> Place.objects.get(restaurant=1)
-<Place: Demon Dogs the place>
->>> Place.objects.get(restaurant=r)
-<Place: Demon Dogs the place>
->>> Place.objects.get(restaurant__exact=1)
-<Place: Demon Dogs the place>
->>> Place.objects.get(restaurant__exact=r)
-<Place: Demon Dogs the place>
-
-# Add a Waiter to the Restaurant.
->>> w = r.waiter_set.create(name='Joe')
->>> w.save()
->>> w
-<Waiter: Joe the waiter at Demon Dogs the restaurant>
-
-# Query the waiters
->>> Waiter.objects.filter(restaurant__place__pk=1)
-[<Waiter: Joe the waiter at Demon Dogs the restaurant>]
->>> Waiter.objects.filter(restaurant__place__exact=1)
-[<Waiter: Joe the waiter at Demon Dogs the restaurant>]
->>> Waiter.objects.filter(restaurant__place__exact=p1)
-[<Waiter: Joe the waiter at Demon Dogs the restaurant>]
->>> Waiter.objects.filter(restaurant__pk=1)
-[<Waiter: Joe the waiter at Demon Dogs the restaurant>]
->>> Waiter.objects.filter(id__exact=1)
-[<Waiter: Joe the waiter at Demon Dogs the restaurant>]
->>> Waiter.objects.filter(pk=1)
-[<Waiter: Joe the waiter at Demon Dogs the restaurant>]
->>> Waiter.objects.filter(restaurant=1)
-[<Waiter: Joe the waiter at Demon Dogs the restaurant>]
->>> Waiter.objects.filter(restaurant=r)
-[<Waiter: Joe the waiter at Demon Dogs the restaurant>]
-
-# Delete the restaurant; the waiter should also be removed
->>> r = Restaurant.objects.get(pk=1)
->>> r.delete()
-
-# One-to-one fields still work if you create your own primary key
->>> o1 = ManualPrimaryKey(primary_key="abc123", name="primary")
->>> o1.save()
->>> o2 = RelatedModel(link=o1, name="secondary")
->>> o2.save()
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/or_lookups/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,119 +0,0 @@
-"""
-19. OR lookups
-
-To perform an OR lookup, or a lookup that combines ANDs and ORs,
-combine QuerySet objects using & and | operators.
-
-Alternatively, use positional arguments, and pass one or more expressions
-of clauses using the variable ``django.db.models.Q`` (or any object with
-a get_sql method).
-
-
-"""
-
-from django.db import models
-
-class Article(models.Model):
- headline = models.CharField(maxlength=50)
- pub_date = models.DateTimeField()
-
- class Meta:
- ordering = ('pub_date',)
-
- def __str__(self):
- return self.headline
-
-__test__ = {'API_TESTS':"""
->>> from datetime import datetime
->>> from django.db.models import Q
-
->>> a1 = Article(headline='Hello', pub_date=datetime(2005, 11, 27))
->>> a1.save()
-
->>> a2 = Article(headline='Goodbye', pub_date=datetime(2005, 11, 28))
->>> a2.save()
-
->>> a3 = Article(headline='Hello and goodbye', pub_date=datetime(2005, 11, 29))
->>> a3.save()
-
->>> Article.objects.filter(headline__startswith='Hello') | Article.objects.filter(headline__startswith='Goodbye')
-[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]
-
->>> Article.objects.filter(Q(headline__startswith='Hello') | Q(headline__startswith='Goodbye'))
-[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]
-
->>> Article.objects.filter(Q(headline__startswith='Hello') & Q(headline__startswith='Goodbye'))
-[]
-
-# You can shorten this syntax with code like the following,
-# which is especially useful if building the query in stages:
->>> articles = Article.objects.all()
->>> articles.filter(headline__startswith='Hello') & articles.filter(headline__startswith='Goodbye')
-[]
-
->>> articles.filter(headline__startswith='Hello') & articles.filter(headline__contains='bye')
-[<Article: Hello and goodbye>]
-
->>> Article.objects.filter(Q(headline__contains='bye'), headline__startswith='Hello')
-[<Article: Hello and goodbye>]
-
->>> Article.objects.filter(headline__contains='Hello') | Article.objects.filter(headline__contains='bye')
-[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]
-
->>> Article.objects.filter(headline__iexact='Hello') | Article.objects.filter(headline__contains='ood')
-[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]
-
->>> Article.objects.filter(Q(pk=1) | Q(pk=2))
-[<Article: Hello>, <Article: Goodbye>]
-
->>> Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))
-[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]
-
-# You could also use "in" to accomplish the same as above.
->>> Article.objects.filter(pk__in=[1,2,3])
-[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]
-
->>> Article.objects.filter(pk__in=[1,2,3,4])
-[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]
-
-# Passing "in" an empty list returns no results ...
->>> Article.objects.filter(pk__in=[])
-[]
-
-# ... but can return results if we OR it with another query.
->>> Article.objects.filter(Q(pk__in=[]) | Q(headline__icontains='goodbye'))
-[<Article: Goodbye>, <Article: Hello and goodbye>]
-
-# Q arg objects are ANDed
->>> Article.objects.filter(Q(headline__startswith='Hello'), Q(headline__contains='bye'))
-[<Article: Hello and goodbye>]
-
-# Q arg AND order is irrelevant
->>> Article.objects.filter(Q(headline__contains='bye'), headline__startswith='Hello')
-[<Article: Hello and goodbye>]
-
-# Try some arg queries with operations other than get_list
->>> Article.objects.get(Q(headline__startswith='Hello'), Q(headline__contains='bye'))
-<Article: Hello and goodbye>
-
->>> Article.objects.filter(Q(headline__startswith='Hello') | Q(headline__contains='bye')).count()
-3
-
->>> list(Article.objects.filter(Q(headline__startswith='Hello'), Q(headline__contains='bye')).values())
-[{'headline': 'Hello and goodbye', 'pub_date': datetime.datetime(2005, 11, 29, 0, 0), 'id': 3}]
-
->>> Article.objects.filter(Q(headline__startswith='Hello')).in_bulk([1,2])
-{1: <Article: Hello>}
-
-# Demonstrating exclude with a Q object
->>> Article.objects.exclude(Q(headline__startswith='Hello'))
-[<Article: Goodbye>]
-
-# The 'complex_filter' method supports framework features such as
-# 'limit_choices_to' which normally take a single dictionary of lookup arguments
-# but need to support arbitrary queries via Q objects too.
->>> Article.objects.complex_filter({'pk': 1})
-[<Article: Hello>]
->>> Article.objects.complex_filter(Q(pk=1) | Q(pk=2))
-[<Article: Hello>, <Article: Goodbye>]
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/ordering/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,67 +0,0 @@
-"""
-6. Specifying ordering
-
-Specify default ordering for a model using the ``ordering`` attribute, which
-should be a list or tuple of field names. This tells Django how to order the
-results of ``get_list()`` and other similar functions.
-
-If a field name in ``ordering`` starts with a hyphen, that field will be
-ordered in descending order. Otherwise, it'll be ordered in ascending order.
-The special-case field name ``"?"`` specifies random order.
-
-The ordering attribute is not required. If you leave it off, ordering will be
-undefined -- not random, just undefined.
-"""
-
-from django.db import models
-
-class Article(models.Model):
- headline = models.CharField(maxlength=100)
- pub_date = models.DateTimeField()
- class Meta:
- ordering = ('-pub_date', 'headline')
-
- def __str__(self):
- return self.headline
-
-__test__ = {'API_TESTS':"""
-# Create a couple of Articles.
->>> from datetime import datetime
->>> a1 = Article(headline='Article 1', pub_date=datetime(2005, 7, 26))
->>> a1.save()
->>> a2 = Article(headline='Article 2', pub_date=datetime(2005, 7, 27))
->>> a2.save()
->>> a3 = Article(headline='Article 3', pub_date=datetime(2005, 7, 27))
->>> a3.save()
->>> a4 = Article(headline='Article 4', pub_date=datetime(2005, 7, 28))
->>> a4.save()
-
-# By default, Article.objects.all() orders by pub_date descending, then
-# headline ascending.
->>> Article.objects.all()
-[<Article: Article 4>, <Article: Article 2>, <Article: Article 3>, <Article: Article 1>]
-
-# Override ordering with order_by, which is in the same format as the ordering
-# attribute in models.
->>> Article.objects.order_by('headline')
-[<Article: Article 1>, <Article: Article 2>, <Article: Article 3>, <Article: Article 4>]
->>> Article.objects.order_by('pub_date', '-headline')
-[<Article: Article 1>, <Article: Article 3>, <Article: Article 2>, <Article: Article 4>]
-
-# Use the 'stop' part of slicing notation to limit the results.
->>> Article.objects.order_by('headline')[:2]
-[<Article: Article 1>, <Article: Article 2>]
-
-# Use the 'stop' and 'start' parts of slicing notation to offset the result list.
->>> Article.objects.order_by('headline')[1:3]
-[<Article: Article 2>, <Article: Article 3>]
-
-# Getting a single item should work too:
->>> Article.objects.all()[0]
-<Article: Article 4>
-
-# Use '?' to order randomly. (We're using [...] in the output to indicate we
-# don't know what order the output will be in.
->>> Article.objects.order_by('?')
-[...]
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/pagination/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,80 +0,0 @@
-"""
-30. Object pagination
-
-Django provides a framework for paginating a list of objects in a few lines
-of code. This is often useful for dividing search results or long lists of
-objects into easily readable pages.
-"""
-
-from django.db import models
-
-class Article(models.Model):
- headline = models.CharField(maxlength=100, default='Default headline')
- pub_date = models.DateTimeField()
-
- def __str__(self):
- return self.headline
-
-__test__ = {'API_TESTS':"""
-# prepare a list of objects for pagination
->>> from datetime import datetime
->>> for x in range(1, 10):
-... a = Article(headline='Article %s' % x, pub_date=datetime(2005, 7, 29))
-... a.save()
-
-# create a basic paginator, 5 articles per page
->>> from django.core.paginator import ObjectPaginator, InvalidPage
->>> paginator = ObjectPaginator(Article.objects.all(), 5)
-
-# the paginator knows how many hits and pages it contains
->>> paginator.hits
-9
-
->>> paginator.pages
-2
-
-# get the first page (zero-based)
->>> paginator.get_page(0)
-[<Article: Article 1>, <Article: Article 2>, <Article: Article 3>, <Article: Article 4>, <Article: Article 5>]
-
-# get the second page
->>> paginator.get_page(1)
-[<Article: Article 6>, <Article: Article 7>, <Article: Article 8>, <Article: Article 9>]
-
-# does the first page have a next or previous page?
->>> paginator.has_next_page(0)
-True
-
->>> paginator.has_previous_page(0)
-False
-
-# check the second page
->>> paginator.has_next_page(1)
-False
-
->>> paginator.has_previous_page(1)
-True
-
->>> paginator.first_on_page(0)
-1
->>> paginator.first_on_page(1)
-6
->>> paginator.last_on_page(0)
-5
->>> paginator.last_on_page(1)
-9
-
-# Add a few more records to test out the orphans feature.
->>> for x in range(10, 13):
-... Article(headline="Article %s" % x, pub_date=datetime(2006, 10, 6)).save()
-
-# With orphans set to 3 and 10 items per page, we should get all 12 items on a single page:
->>> paginator = ObjectPaginator(Article.objects.all(), 10, orphans=3)
->>> paginator.pages
-1
-
-# With orphans only set to 1, we should get two pages:
->>> paginator = ObjectPaginator(Article.objects.all(), 10, orphans=1)
->>> paginator.pages
-2
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/properties/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,40 +0,0 @@
-"""
-22. Using properties on models
-
-Use properties on models just like on any other Python object.
-"""
-
-from django.db import models
-
-class Person(models.Model):
- first_name = models.CharField(maxlength=30)
- last_name = models.CharField(maxlength=30)
-
- def _get_full_name(self):
- return "%s %s" % (self.first_name, self.last_name)
-
- def _set_full_name(self, combined_name):
- self.first_name, self.last_name = combined_name.split(' ', 1)
-
- full_name = property(_get_full_name)
-
- full_name_2 = property(_get_full_name, _set_full_name)
-
-__test__ = {'API_TESTS':"""
->>> a = Person(first_name='John', last_name='Lennon')
->>> a.save()
->>> a.full_name
-'John Lennon'
-
-# The "full_name" property hasn't provided a "set" method.
->>> a.full_name = 'Paul McCartney'
-Traceback (most recent call last):
- ...
-AttributeError: can't set attribute
-
-# But "full_name_2" has, and it can be used to initialise the class.
->>> a2 = Person(full_name_2 = 'Paul McCartney')
->>> a2.save()
->>> a2.first_name
-'Paul'
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/reserved_names/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,56 +0,0 @@
-"""
-18. Using SQL reserved names
-
-Need to use a reserved SQL name as a column name or table name? Need to include
-a hyphen in a column or table name? No problem. Django quotes names
-appropriately behind the scenes, so your database won't complain about
-reserved-name usage.
-"""
-
-from django.db import models
-
-class Thing(models.Model):
- when = models.CharField(maxlength=1, primary_key=True)
- join = models.CharField(maxlength=1)
- like = models.CharField(maxlength=1)
- drop = models.CharField(maxlength=1)
- alter = models.CharField(maxlength=1)
- having = models.CharField(maxlength=1)
- where = models.DateField(maxlength=1)
- has_hyphen = models.CharField(maxlength=1, db_column='has-hyphen')
- class Meta:
- db_table = 'select'
-
- def __str__(self):
- return self.when
-
-__test__ = {'API_TESTS':"""
->>> import datetime
->>> day1 = datetime.date(2005, 1, 1)
->>> day2 = datetime.date(2006, 2, 2)
->>> t = Thing(when='a', join='b', like='c', drop='d', alter='e', having='f', where=day1, has_hyphen='h')
->>> t.save()
->>> print t.when
-a
-
->>> u = Thing(when='h', join='i', like='j', drop='k', alter='l', having='m', where=day2)
->>> u.save()
->>> print u.when
-h
-
->>> Thing.objects.order_by('when')
-[<Thing: a>, <Thing: h>]
->>> v = Thing.objects.get(pk='a')
->>> print v.join
-b
->>> print v.where
-2005-01-01
->>> Thing.objects.order_by('select.when')
-[<Thing: a>, <Thing: h>]
-
->>> Thing.objects.dates('where', 'year')
-[datetime.datetime(2005, 1, 1, 0, 0), datetime.datetime(2006, 1, 1, 0, 0)]
-
->>> Thing.objects.filter(where__month=1)
-[<Thing: a>]
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/reverse_lookup/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,59 +0,0 @@
-"""
-25. Reverse lookups
-
-This demonstrates the reverse lookup features of the database API.
-"""
-
-from django.db import models
-
-class User(models.Model):
- name = models.CharField(maxlength=200)
-
- def __str__(self):
- return self.name
-
-class Poll(models.Model):
- question = models.CharField(maxlength=200)
- creator = models.ForeignKey(User)
-
- def __str__(self):
- return self.question
-
-class Choice(models.Model):
- name = models.CharField(maxlength=100)
- poll = models.ForeignKey(Poll, related_name="poll_choice")
- related_poll = models.ForeignKey(Poll, related_name="related_choice")
-
- def __str(self):
- return self.name
-
-__test__ = {'API_TESTS':"""
->>> john = User(name="John Doe")
->>> john.save()
->>> jim = User(name="Jim Bo")
->>> jim.save()
->>> first_poll = Poll(question="What's the first question?", creator=john)
->>> first_poll.save()
->>> second_poll = Poll(question="What's the second question?", creator=jim)
->>> second_poll.save()
->>> new_choice = Choice(poll=first_poll, related_poll=second_poll, name="This is the answer.")
->>> new_choice.save()
-
->>> # Reverse lookups by field name:
->>> User.objects.get(poll__question__exact="What's the first question?")
-<User: John Doe>
->>> User.objects.get(poll__question__exact="What's the second question?")
-<User: Jim Bo>
-
->>> # Reverse lookups by related_name:
->>> Poll.objects.get(poll_choice__name__exact="This is the answer.")
-<Poll: What's the first question?>
->>> Poll.objects.get(related_choice__name__exact="This is the answer.")
-<Poll: What's the second question?>
-
->>> # If a related_name is given you can't use the field name instead:
->>> Poll.objects.get(choice__name__exact="This is the answer")
-Traceback (most recent call last):
- ...
-TypeError: Cannot resolve keyword 'choice' into field
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/save_delete_hooks/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,42 +0,0 @@
-"""
-13. Adding hooks before/after saving and deleting
-
-To execute arbitrary code around ``save()`` and ``delete()``, just subclass
-the methods.
-"""
-
-from django.db import models
-
-class Person(models.Model):
- first_name = models.CharField(maxlength=20)
- last_name = models.CharField(maxlength=20)
-
- def __str__(self):
- return "%s %s" % (self.first_name, self.last_name)
-
- def save(self):
- print "Before save"
- super(Person, self).save() # Call the "real" save() method
- print "After save"
-
- def delete(self):
- print "Before deletion"
- super(Person, self).delete() # Call the "real" delete() method
- print "After deletion"
-
-__test__ = {'API_TESTS':"""
->>> p1 = Person(first_name='John', last_name='Smith')
->>> p1.save()
-Before save
-After save
-
->>> Person.objects.all()
-[<Person: John Smith>]
-
->>> p1.delete()
-Before deletion
-After deletion
-
->>> Person.objects.all()
-[]
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/select_related/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,152 +0,0 @@
-"""
-40. Tests for select_related()
-
-``select_related()`` follows all relationships and pre-caches any foreign key
-values so that complex trees can be fetched in a single query. However, this
-isn't always a good idea, so the ``depth`` argument control how many "levels"
-the select-related behavior will traverse.
-"""
-
-from django.db import models
-
-# Who remembers high school biology?
-
-class Domain(models.Model):
- name = models.CharField(maxlength=50)
- def __str__(self):
- return self.name
-
-class Kingdom(models.Model):
- name = models.CharField(maxlength=50)
- domain = models.ForeignKey(Domain)
- def __str__(self):
- return self.name
-
-class Phylum(models.Model):
- name = models.CharField(maxlength=50)
- kingdom = models.ForeignKey(Kingdom)
- def __str__(self):
- return self.name
-
-class Klass(models.Model):
- name = models.CharField(maxlength=50)
- phylum = models.ForeignKey(Phylum)
- def __str__(self):
- return self.name
-
-class Order(models.Model):
- name = models.CharField(maxlength=50)
- klass = models.ForeignKey(Klass)
- def __str__(self):
- return self.name
-
-class Family(models.Model):
- name = models.CharField(maxlength=50)
- order = models.ForeignKey(Order)
- def __str__(self):
- return self.name
-
-class Genus(models.Model):
- name = models.CharField(maxlength=50)
- family = models.ForeignKey(Family)
- def __str__(self):
- return self.name
-
-class Species(models.Model):
- name = models.CharField(maxlength=50)
- genus = models.ForeignKey(Genus)
- def __str__(self):
- return self.name
-
-def create_tree(stringtree):
- """Helper to create a complete tree"""
- names = stringtree.split()
- models = [Domain, Kingdom, Phylum, Klass, Order, Family, Genus, Species]
- assert len(names) == len(models), (names, models)
-
- parent = None
- for name, model in zip(names, models):
- try:
- obj = model.objects.get(name=name)
- except model.DoesNotExist:
- obj = model(name=name)
- if parent:
- setattr(obj, parent.__class__.__name__.lower(), parent)
- obj.save()
- parent = obj
-
-__test__ = {'API_TESTS':"""
-
-# Set up.
-# The test runner sets settings.DEBUG to False, but we want to gather queries
-# so we'll set it to True here and reset it at the end of the test suite.
->>> from django.conf import settings
->>> settings.DEBUG = True
-
->>> create_tree("Eukaryota Animalia Anthropoda Insecta Diptera Drosophilidae Drosophila melanogaster")
->>> create_tree("Eukaryota Animalia Chordata Mammalia Primates Hominidae Homo sapiens")
->>> create_tree("Eukaryota Plantae Magnoliophyta Magnoliopsida Fabales Fabaceae Pisum sativum")
->>> create_tree("Eukaryota Fungi Basidiomycota Homobasidiomycatae Agaricales Amanitacae Amanita muscaria")
-
->>> from django import db
-
-# Normally, accessing FKs doesn't fill in related objects:
->>> db.reset_queries()
->>> fly = Species.objects.get(name="melanogaster")
->>> fly.genus.family.order.klass.phylum.kingdom.domain
-<Domain: Eukaryota>
->>> len(db.connection.queries)
-8
-
-# However, a select_related() call will fill in those related objects without any extra queries:
->>> db.reset_queries()
->>> person = Species.objects.select_related().get(name="sapiens")
->>> person.genus.family.order.klass.phylum.kingdom.domain
-<Domain: Eukaryota>
->>> len(db.connection.queries)
-1
-
-# select_related() also of course applies to entire lists, not just items.
-# Without select_related()
->>> db.reset_queries()
->>> world = Species.objects.all()
->>> [o.genus.family for o in world]
-[<Family: Drosophilidae>, <Family: Hominidae>, <Family: Fabaceae>, <Family: Amanitacae>]
->>> len(db.connection.queries)
-9
-
-# With select_related():
->>> db.reset_queries()
->>> world = Species.objects.all().select_related()
->>> [o.genus.family for o in world]
-[<Family: Drosophilidae>, <Family: Hominidae>, <Family: Fabaceae>, <Family: Amanitacae>]
->>> len(db.connection.queries)
-1
-
-# The "depth" argument to select_related() will stop the descent at a particular level:
->>> db.reset_queries()
->>> pea = Species.objects.select_related(depth=1).get(name="sativum")
->>> pea.genus.family.order.klass.phylum.kingdom.domain
-<Domain: Eukaryota>
-
-# Notice: one few query than above because of depth=1
->>> len(db.connection.queries)
-7
-
->>> db.reset_queries()
->>> pea = Species.objects.select_related(depth=5).get(name="sativum")
->>> pea.genus.family.order.klass.phylum.kingdom.domain
-<Domain: Eukaryota>
->>> len(db.connection.queries)
-3
-
->>> db.reset_queries()
->>> world = Species.objects.all().select_related(depth=2)
->>> [o.genus.family.order for o in world]
-[<Order: Diptera>, <Order: Primates>, <Order: Fabales>, <Order: Agaricales>]
->>> len(db.connection.queries)
-5
-
-# Reset DEBUG to where we found it.
->>> settings.DEBUG = False
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/serializers/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,162 +0,0 @@
-"""
-41. Serialization
-
-``django.core.serializers`` provides interfaces to converting Django querysets
-to and from "flat" data (i.e. strings).
-"""
-
-from django.db import models
-
-class Category(models.Model):
- name = models.CharField(maxlength=20)
-
- class Meta:
- ordering = ('name',)
-
- def __str__(self):
- return self.name
-
-class Author(models.Model):
- name = models.CharField(maxlength=20)
-
- class Meta:
- ordering = ('name',)
-
- def __str__(self):
- return self.name
-
-class Article(models.Model):
- author = models.ForeignKey(Author)
- headline = models.CharField(maxlength=50)
- pub_date = models.DateTimeField()
- categories = models.ManyToManyField(Category)
-
- class Meta:
- ordering = ('pub_date',)
-
- def __str__(self):
- return self.headline
-
-class AuthorProfile(models.Model):
- author = models.OneToOneField(Author)
- date_of_birth = models.DateField()
-
- def __str__(self):
- return "Profile of %s" % self.author
-
-__test__ = {'API_TESTS':"""
-# Create some data:
->>> from datetime import datetime
->>> sports = Category(name="Sports")
->>> music = Category(name="Music")
->>> op_ed = Category(name="Op-Ed")
->>> sports.save(); music.save(); op_ed.save()
-
->>> joe = Author(name="Joe")
->>> jane = Author(name="Jane")
->>> joe.save(); jane.save()
-
->>> a1 = Article(
-... author = jane,
-... headline = "Poker has no place on ESPN",
-... pub_date = datetime(2006, 6, 16, 11, 00))
->>> a2 = Article(
-... author = joe,
-... headline = "Time to reform copyright",
-... pub_date = datetime(2006, 6, 16, 13, 00))
->>> a1.save(); a2.save()
->>> a1.categories = [sports, op_ed]
->>> a2.categories = [music, op_ed]
-
-# Serialize a queryset to XML
->>> from django.core import serializers
->>> xml = serializers.serialize("xml", Article.objects.all())
-
-# The output is valid XML
->>> from xml.dom import minidom
->>> dom = minidom.parseString(xml)
-
-# Deserializing has a similar interface, except that special DeserializedObject
-# instances are returned. This is because data might have changed in the
-# database since the data was serialized (we'll simulate that below).
->>> for obj in serializers.deserialize("xml", xml):
-... print obj
-<DeserializedObject: Poker has no place on ESPN>
-<DeserializedObject: Time to reform copyright>
-
-# Deserializing data with different field values doesn't change anything in the
-# database until we call save():
->>> xml = xml.replace("Poker has no place on ESPN", "Poker has no place on television")
->>> objs = list(serializers.deserialize("xml", xml))
-
-# Even those I deserialized, the database hasn't been touched
->>> Article.objects.all()
-[<Article: Poker has no place on ESPN>, <Article: Time to reform copyright>]
-
-# But when I save, the data changes as you might except.
->>> objs[0].save()
->>> Article.objects.all()
-[<Article: Poker has no place on television>, <Article: Time to reform copyright>]
-
-# Django also ships with a built-in JSON serializers
->>> json = serializers.serialize("json", Category.objects.filter(pk=2))
->>> json
-'[{"pk": "2", "model": "serializers.category", "fields": {"name": "Music"}}]'
-
-# You can easily create new objects by deserializing data with an empty PK
-# (It's easier to demo this with JSON...)
->>> new_author_json = '[{"pk": null, "model": "serializers.author", "fields": {"name": "Bill"}}]'
->>> for obj in serializers.deserialize("json", new_author_json):
-... obj.save()
->>> Author.objects.all()
-[<Author: Bill>, <Author: Jane>, <Author: Joe>]
-
-# All the serializers work the same
->>> json = serializers.serialize("json", Article.objects.all())
->>> for obj in serializers.deserialize("json", json):
-... print obj
-<DeserializedObject: Poker has no place on television>
-<DeserializedObject: Time to reform copyright>
-
->>> json = json.replace("Poker has no place on television", "Just kidding; I love TV poker")
->>> for obj in serializers.deserialize("json", json):
-... obj.save()
-
->>> Article.objects.all()
-[<Article: Just kidding; I love TV poker>, <Article: Time to reform copyright>]
-
-# If you use your own primary key field (such as a OneToOneField),
-# it doesn't appear in the serialized field list - it replaces the
-# pk identifier.
->>> profile = AuthorProfile(author=joe, date_of_birth=datetime(1970,1,1))
->>> profile.save()
-
->>> json = serializers.serialize("json", AuthorProfile.objects.all())
->>> json
-'[{"pk": "1", "model": "serializers.authorprofile", "fields": {"date_of_birth": "1970-01-01"}}]'
-
->>> for obj in serializers.deserialize("json", json):
-... print obj
-<DeserializedObject: Profile of Joe>
-
-# Objects ids can be referenced before they are defined in the serialization data
-# However, the deserialization process will need to be contained within a transaction
->>> json = '[{"pk": "3", "model": "serializers.article", "fields": {"headline": "Forward references pose no problem", "pub_date": "2006-06-16 15:00:00", "categories": [4, 1], "author": 4}}, {"pk": "4", "model": "serializers.category", "fields": {"name": "Reference"}}, {"pk": "4", "model": "serializers.author", "fields": {"name": "Agnes"}}]'
->>> from django.db import transaction
->>> transaction.enter_transaction_management()
->>> transaction.managed(True)
->>> for obj in serializers.deserialize("json", json):
-... obj.save()
-
->>> transaction.commit()
->>> transaction.leave_transaction_management()
-
->>> article = Article.objects.get(pk=3)
->>> article
-<Article: Forward references pose no problem>
->>> article.categories.all()
-[<Category: Reference>, <Category: Sports>]
->>> article.author
-<Author: Agnes>
-
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/str/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,31 +0,0 @@
-"""
-2. Adding __str__() to models
-
-Although it's not a strict requirement, each model should have a ``__str__()``
-method to return a "human-readable" representation of the object. Do this not
-only for your own sanity when dealing with the interactive prompt, but also
-because objects' representations are used throughout Django's
-automatically-generated admin.
-"""
-
-from django.db import models
-
-class Article(models.Model):
- headline = models.CharField(maxlength=100)
- pub_date = models.DateTimeField()
-
- def __str__(self):
- return self.headline
-
-__test__ = {'API_TESTS':"""
-# Create an Article.
->>> from datetime import datetime
->>> a = Article(headline='Area man programs in Python', pub_date=datetime(2005, 7, 28))
->>> a.save()
-
->>> str(a)
-'Area man programs in Python'
-
->>> a
-<Article: Area man programs in Python>
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/test_client/fixtures/testdata.json Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,20 +0,0 @@
-[
- {
- "pk": "1",
- "model": "auth.user",
- "fields": {
- "username": "testclient",
- "first_name": "Test",
- "last_name": "Client",
- "is_active": true,
- "is_superuser": false,
- "is_staff": false,
- "last_login": "2006-12-17 07:03:31",
- "groups": [],
- "user_permissions": [],
- "password": "sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161",
- "email": "testclient@example.com",
- "date_joined": "2006-12-17 07:03:31"
- }
- }
-]
\ No newline at end of file
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/test_client/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,172 +0,0 @@
-"""
-38. Testing using the Test Client
-
-The test client is a class that can act like a simple
-browser for testing purposes.
-
-It allows the user to compose GET and POST requests, and
-obtain the response that the server gave to those requests.
-The server Response objects are annotated with the details
-of the contexts and templates that were rendered during the
-process of serving the request.
-
-Client objects are stateful - they will retain cookie (and
-thus session) details for the lifetime of the Client instance.
-
-This is not intended as a replacement for Twill,Selenium, or
-other browser automation frameworks - it is here to allow
-testing against the contexts and templates produced by a view,
-rather than the HTML rendered to the end-user.
-
-"""
-from django.test import Client, TestCase
-
-class ClientTest(TestCase):
- fixtures = ['testdata.json']
-
- def setUp(self):
- "Set up test environment"
- self.client = Client()
-
- def test_get_view(self):
- "GET a view"
- response = self.client.get('/test_client/get_view/')
-
- # Check some response details
- self.assertEqual(response.status_code, 200)
- self.assertEqual(response.context['var'], 42)
- self.assertEqual(response.template.name, 'GET Template')
- self.failUnless('This is a test.' in response.content)
-
- def test_get_post_view(self):
- "GET a view that normally expects POSTs"
- response = self.client.get('/test_client/post_view/', {})
-
- # Check some response details
- self.assertEqual(response.status_code, 200)
- self.assertEqual(response.template.name, 'Empty GET Template')
-
- def test_empty_post(self):
- "POST an empty dictionary to a view"
- response = self.client.post('/test_client/post_view/', {})
-
- # Check some response details
- self.assertEqual(response.status_code, 200)
- self.assertEqual(response.template.name, 'Empty POST Template')
-
- def test_post(self):
- "POST some data to a view"
- post_data = {
- 'value': 37
- }
- response = self.client.post('/test_client/post_view/', post_data)
-
- # Check some response details
- self.assertEqual(response.status_code, 200)
- self.assertEqual(response.context['data'], '37')
- self.assertEqual(response.template.name, 'POST Template')
- self.failUnless('Data received' in response.content)
-
- def test_raw_post(self):
- test_doc = """<?xml version="1.0" encoding="utf-8"?><library><book><title>Blink</title><author>Malcolm Gladwell</author></book></library>"""
- response = self.client.post("/test_client/raw_post_view/", test_doc,
- content_type="text/xml")
- self.assertEqual(response.status_code, 200)
- self.assertEqual(response.template.name, "Book template")
- self.assertEqual(response.content, "Blink - Malcolm Gladwell")
-
- def test_redirect(self):
- "GET a URL that redirects elsewhere"
- response = self.client.get('/test_client/redirect_view/')
-
- # Check that the response was a 302 (redirect)
- self.assertEqual(response.status_code, 302)
-
- def test_valid_form(self):
- "POST valid data to a form"
- post_data = {
- 'text': 'Hello World',
- 'email': 'foo@example.com',
- 'value': 37,
- 'single': 'b',
- 'multi': ('b','c','e')
- }
- response = self.client.post('/test_client/form_view/', post_data)
- self.assertEqual(response.status_code, 200)
- self.assertEqual(response.template.name, "Valid POST Template")
-
- def test_incomplete_data_form(self):
- "POST incomplete data to a form"
- post_data = {
- 'text': 'Hello World',
- 'value': 37
- }
- response = self.client.post('/test_client/form_view/', post_data)
- self.assertEqual(response.status_code, 200)
- self.assertEqual(response.template.name, "Invalid POST Template")
-
- def test_form_error(self):
- "POST erroneous data to a form"
- post_data = {
- 'text': 'Hello World',
- 'email': 'not an email address',
- 'value': 37,
- 'single': 'b',
- 'multi': ('b','c','e')
- }
- response = self.client.post('/test_client/form_view/', post_data)
- self.assertEqual(response.status_code, 200)
- self.assertEqual(response.template.name, "Invalid POST Template")
-
- def test_unknown_page(self):
- "GET an invalid URL"
- response = self.client.get('/test_client/unknown_view/')
-
- # Check that the response was a 404
- self.assertEqual(response.status_code, 404)
-
- def test_view_with_login(self):
- "Request a page that is protected with @login_required"
-
- # Get the page without logging in. Should result in 302.
- response = self.client.get('/test_client/login_protected_view/')
- self.assertEqual(response.status_code, 302)
-
- # Request a page that requires a login
- response = self.client.login('/test_client/login_protected_view/', 'testclient', 'password')
- self.failUnless(response)
- self.assertEqual(response.status_code, 200)
- self.assertEqual(response.context['user'].username, 'testclient')
- self.assertEqual(response.template.name, 'Login Template')
-
- def test_view_with_bad_login(self):
- "Request a page that is protected with @login, but use bad credentials"
-
- response = self.client.login('/test_client/login_protected_view/', 'otheruser', 'nopassword')
- self.failIf(response)
-
- def test_session_modifying_view(self):
- "Request a page that modifies the session"
- # Session value isn't set initially
- try:
- self.client.session['tobacconist']
- self.fail("Shouldn't have a session value")
- except KeyError:
- pass
-
- from django.contrib.sessions.models import Session
- response = self.client.post('/test_client/session_view/')
-
- # Check that the session was modified
- self.assertEquals(self.client.session['tobacconist'], 'hovercraft')
-
- def test_view_with_exception(self):
- "Request a page that is known to throw an error"
- self.assertRaises(KeyError, self.client.get, "/test_client/broken_view/")
-
- #Try the same assertion, a different way
- try:
- self.client.get('/test_client/broken_view/')
- self.fail('Should raise an error')
- except KeyError:
- pass
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/test_client/urls.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,13 +0,0 @@
-from django.conf.urls.defaults import *
-import views
-
-urlpatterns = patterns('',
- (r'^get_view/$', views.get_view),
- (r'^post_view/$', views.post_view),
- (r'^raw_post_view/$', views.raw_post_view),
- (r'^redirect_view/$', views.redirect_view),
- (r'^form_view/$', views.form_view),
- (r'^login_protected_view/$', views.login_protected_view),
- (r'^session_view/$', views.session_view),
- (r'^broken_view/$', views.broken_view)
-)
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/test_client/views.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,102 +0,0 @@
-from xml.dom.minidom import parseString
-from django.template import Context, Template
-from django.http import HttpResponse, HttpResponseRedirect
-from django.contrib.auth.decorators import login_required
-from django.newforms.forms import Form
-from django.newforms import fields
-
-def get_view(request):
- "A simple view that expects a GET request, and returns a rendered template"
- t = Template('This is a test. {{ var }} is the value.', name='GET Template')
- c = Context({'var': 42})
-
- return HttpResponse(t.render(c))
-
-def post_view(request):
- """A view that expects a POST, and returns a different template depending
- on whether any POST data is available
- """
- if request.method == 'POST':
- if request.POST:
- t = Template('Data received: {{ data }} is the value.', name='POST Template')
- c = Context({'data': request.POST['value']})
- else:
- t = Template('Viewing POST page.', name='Empty POST Template')
- c = Context()
- else:
- t = Template('Viewing GET page.', name='Empty GET Template')
- c = Context()
-
- return HttpResponse(t.render(c))
-
-def raw_post_view(request):
- """A view which expects raw XML to be posted and returns content extracted
- from the XML"""
- if request.method == 'POST':
- root = parseString(request.raw_post_data)
- first_book = root.firstChild.firstChild
- title, author = [n.firstChild.nodeValue for n in first_book.childNodes]
- t = Template("{{ title }} - {{ author }}", name="Book template")
- c = Context({"title": title, "author": author})
- else:
- t = Template("GET request.", name="Book GET template")
- c = Context()
-
- return HttpResponse(t.render(c))
-
-def redirect_view(request):
- "A view that redirects all requests to the GET view"
- return HttpResponseRedirect('/test_client/get_view/')
-
-TestChoices = (
- ('a', 'First Choice'),
- ('b', 'Second Choice'),
- ('c', 'Third Choice'),
- ('d', 'Fourth Choice'),
- ('e', 'Fifth Choice')
-)
-
-class TestForm(Form):
- text = fields.CharField()
- email = fields.EmailField()
- value = fields.IntegerField()
- single = fields.ChoiceField(choices=TestChoices)
- multi = fields.MultipleChoiceField(choices=TestChoices)
-
-def form_view(request):
- "A view that tests a simple form"
- if request.method == 'POST':
- form = TestForm(request.POST)
- if form.is_valid():
- t = Template('Valid POST data.', name='Valid POST Template')
- c = Context()
- else:
- t = Template('Invalid POST data. {{ form.errors }}', name='Invalid POST Template')
- c = Context({'form': form})
- else:
- form = TestForm()
- t = Template('Viewing base form. {{ form }}.', name='Form GET Template')
- c = Context({'form': form})
-
- return HttpResponse(t.render(c))
-
-def login_protected_view(request):
- "A simple view that is login protected."
- t = Template('This is a login protected test. Username is {{ user.username }}.', name='Login Template')
- c = Context({'user': request.user})
-
- return HttpResponse(t.render(c))
-login_protected_view = login_required(login_protected_view)
-
-def session_view(request):
- "A view that modifies the session"
- request.session['tobacconist'] = 'hovercraft'
-
- t = Template('This is a view that modifies the session.',
- name='Session Modifying View Template')
- c = Context()
- return HttpResponse(t.render(c))
-
-def broken_view(request):
- """A view which just raises an exception, simulating a broken view."""
- raise KeyError("Oops! Looks like you wrote some bad code.")
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/transactions/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,99 +0,0 @@
-"""
-15. Transactions
-
-Django handles transactions in three different ways. The default is to commit
-each transaction upon a write, but you can decorate a function to get
-commit-on-success behavior. Alternatively, you can manage the transaction
-manually.
-"""
-
-from django.db import models
-
-class Reporter(models.Model):
- first_name = models.CharField(maxlength=30)
- last_name = models.CharField(maxlength=30)
- email = models.EmailField()
-
- def __str__(self):
- return "%s %s" % (self.first_name, self.last_name)
-
-__test__ = {'API_TESTS':"""
->>> from django.db import connection, transaction
-"""}
-
-from django.conf import settings
-
-building_docs = getattr(settings, 'BUILDING_DOCS', False)
-
-if building_docs or settings.DATABASE_ENGINE != 'mysql':
- __test__['API_TESTS'] += """
-# the default behavior is to autocommit after each save() action
->>> def create_a_reporter_then_fail(first, last):
-... a = Reporter(first_name=first, last_name=last)
-... a.save()
-... raise Exception("I meant to do that")
-...
->>> create_a_reporter_then_fail("Alice", "Smith")
-Traceback (most recent call last):
- ...
-Exception: I meant to do that
-
-# The object created before the exception still exists
->>> Reporter.objects.all()
-[<Reporter: Alice Smith>]
-
-# the autocommit decorator works exactly the same as the default behavior
->>> autocomitted_create_then_fail = transaction.autocommit(create_a_reporter_then_fail)
->>> autocomitted_create_then_fail("Ben", "Jones")
-Traceback (most recent call last):
- ...
-Exception: I meant to do that
-
-# Same behavior as before
->>> Reporter.objects.all()
-[<Reporter: Alice Smith>, <Reporter: Ben Jones>]
-
-# With the commit_on_success decorator, the transaction is only comitted if the
-# function doesn't throw an exception
->>> committed_on_success = transaction.commit_on_success(create_a_reporter_then_fail)
->>> committed_on_success("Carol", "Doe")
-Traceback (most recent call last):
- ...
-Exception: I meant to do that
-
-# This time the object never got saved
->>> Reporter.objects.all()
-[<Reporter: Alice Smith>, <Reporter: Ben Jones>]
-
-# If there aren't any exceptions, the data will get saved
->>> def remove_a_reporter():
-... r = Reporter.objects.get(first_name="Alice")
-... r.delete()
-...
->>> remove_comitted_on_success = transaction.commit_on_success(remove_a_reporter)
->>> remove_comitted_on_success()
->>> Reporter.objects.all()
-[<Reporter: Ben Jones>]
-
-# You can manually manage transactions if you really want to, but you
-# have to remember to commit/rollback
->>> def manually_managed():
-... r = Reporter(first_name="Carol", last_name="Doe")
-... r.save()
-... transaction.commit()
->>> manually_managed = transaction.commit_manually(manually_managed)
->>> manually_managed()
->>> Reporter.objects.all()
-[<Reporter: Ben Jones>, <Reporter: Carol Doe>]
-
-# If you forget, you'll get bad errors
->>> def manually_managed_mistake():
-... r = Reporter(first_name="David", last_name="Davidson")
-... r.save()
-... # oops, I forgot to commit/rollback!
->>> manually_managed_mistake = transaction.commit_manually(manually_managed_mistake)
->>> manually_managed_mistake()
-Traceback (most recent call last):
- ...
-TransactionManagementError: Transaction managed block ended with pending COMMIT/ROLLBACK
-"""
\ No newline at end of file
--- a/thirdparty/google_appengine/lib/django/tests/modeltests/validation/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,153 +0,0 @@
-"""
-31. Validation
-
-This is an experimental feature!
-
-Each model instance has a validate() method that returns a dictionary of
-validation errors in the instance's fields. This method has a side effect
-of converting each field to its appropriate Python data type.
-"""
-
-from django.db import models
-
-class Person(models.Model):
- is_child = models.BooleanField()
- name = models.CharField(maxlength=20)
- birthdate = models.DateField()
- favorite_moment = models.DateTimeField()
- email = models.EmailField()
-
- def __str__(self):
- return self.name
-
-__test__ = {'API_TESTS':"""
-
->>> import datetime
->>> valid_params = {
-... 'is_child': True,
-... 'name': 'John',
-... 'birthdate': datetime.date(2000, 5, 3),
-... 'favorite_moment': datetime.datetime(2002, 4, 3, 13, 23),
-... 'email': 'john@example.com'
-... }
->>> p = Person(**valid_params)
->>> p.validate()
-{}
-
->>> p = Person(**dict(valid_params, id='23'))
->>> p.validate()
-{}
->>> p.id
-23
-
->>> p = Person(**dict(valid_params, id='foo'))
->>> p.validate()
-{'id': ['This value must be an integer.']}
-
->>> p = Person(**dict(valid_params, id=None))
->>> p.validate()
-{}
->>> repr(p.id)
-'None'
-
->>> p = Person(**dict(valid_params, is_child='t'))
->>> p.validate()
-{}
->>> p.is_child
-True
-
->>> p = Person(**dict(valid_params, is_child='f'))
->>> p.validate()
-{}
->>> p.is_child
-False
-
->>> p = Person(**dict(valid_params, is_child=True))
->>> p.validate()
-{}
->>> p.is_child
-True
-
->>> p = Person(**dict(valid_params, is_child=False))
->>> p.validate()
-{}
->>> p.is_child
-False
-
->>> p = Person(**dict(valid_params, is_child='foo'))
->>> p.validate()
-{'is_child': ['This value must be either True or False.']}
-
->>> p = Person(**dict(valid_params, name=u'Jose'))
->>> p.validate()
-{}
->>> p.name
-u'Jose'
-
->>> p = Person(**dict(valid_params, name=227))
->>> p.validate()
-{}
->>> p.name
-'227'
-
->>> p = Person(**dict(valid_params, birthdate=datetime.date(2000, 5, 3)))
->>> p.validate()
-{}
->>> p.birthdate
-datetime.date(2000, 5, 3)
-
->>> p = Person(**dict(valid_params, birthdate=datetime.datetime(2000, 5, 3)))
->>> p.validate()
-{}
->>> p.birthdate
-datetime.date(2000, 5, 3)
-
->>> p = Person(**dict(valid_params, birthdate='2000-05-03'))
->>> p.validate()
-{}
->>> p.birthdate
-datetime.date(2000, 5, 3)
-
->>> p = Person(**dict(valid_params, birthdate='2000-5-3'))
->>> p.validate()
-{}
->>> p.birthdate
-datetime.date(2000, 5, 3)
-
->>> p = Person(**dict(valid_params, birthdate='foo'))
->>> p.validate()
-{'birthdate': ['Enter a valid date in YYYY-MM-DD format.']}
-
->>> p = Person(**dict(valid_params, favorite_moment=datetime.datetime(2002, 4, 3, 13, 23)))
->>> p.validate()
-{}
->>> p.favorite_moment
-datetime.datetime(2002, 4, 3, 13, 23)
-
->>> p = Person(**dict(valid_params, favorite_moment=datetime.datetime(2002, 4, 3)))
->>> p.validate()
-{}
->>> p.favorite_moment
-datetime.datetime(2002, 4, 3, 0, 0)
-
->>> p = Person(**dict(valid_params, email='john@example.com'))
->>> p.validate()
-{}
->>> p.email
-'john@example.com'
-
->>> p = Person(**dict(valid_params, email=u'john@example.com'))
->>> p.validate()
-{}
->>> p.email
-u'john@example.com'
-
->>> p = Person(**dict(valid_params, email=22))
->>> p.validate()
-{'email': ['Enter a valid e-mail address.']}
-
-# Make sure that Date and DateTime return validation errors and don't raise Python errors.
->>> Person(name='John Doe', is_child=True, email='abc@def.com').validate()
-{'favorite_moment': ['This field is required.'], 'birthdate': ['This field is required.']}
-
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/bug639/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,16 +0,0 @@
-import tempfile
-from django.db import models
-
-class Photo(models.Model):
- title = models.CharField(maxlength=30)
- image = models.FileField(upload_to=tempfile.gettempdir())
-
- # Support code for the tests; this keeps track of how many times save() gets
- # called on each instance.
- def __init__(self, *args, **kwargs):
- super(Photo, self).__init__(*args, **kwargs)
- self._savecount = 0
-
- def save(self):
- super(Photo, self).save()
- self._savecount +=1
\ No newline at end of file
Binary file thirdparty/google_appengine/lib/django/tests/regressiontests/bug639/test.jpg has changed
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/bug639/tests.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,42 +0,0 @@
-"""
-Tests for file field behavior, and specifically #639, in which Model.save() gets
-called *again* for each FileField. This test will fail if calling an
-auto-manipulator's save() method causes Model.save() to be called more than once.
-"""
-
-import os
-import unittest
-from regressiontests.bug639.models import Photo
-from django.http import QueryDict
-from django.utils.datastructures import MultiValueDict
-
-class Bug639Test(unittest.TestCase):
-
- def testBug639(self):
- """
- Simulate a file upload and check how many times Model.save() gets called.
- """
- # Grab an image for testing
- img = open(os.path.join(os.path.dirname(__file__), "test.jpg"), "rb").read()
-
- # Fake a request query dict with the file
- qd = QueryDict("title=Testing&image=", mutable=True)
- qd["image_file"] = {
- "filename" : "test.jpg",
- "content-type" : "image/jpeg",
- "content" : img
- }
-
- manip = Photo.AddManipulator()
- manip.do_html2python(qd)
- p = manip.save(qd)
-
- # Check the savecount stored on the object (see the model)
- self.assertEqual(p._savecount, 1)
-
- def tearDown(self):
- """
- Make sure to delete the "uploaded" file to avoid clogging /tmp.
- """
- p = Photo.objects.get()
- os.unlink(p.get_image_filename())
\ No newline at end of file
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/cache/tests.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,71 +0,0 @@
-# Unit tests for cache framework
-# Uses whatever cache backend is set in the test settings file.
-
-from django.core.cache import cache
-import time, unittest
-
-# functions/classes for complex data type tests
-def f():
- return 42
-class C:
- def m(n):
- return 24
-
-class Cache(unittest.TestCase):
- def test_simple(self):
- # simple set/get
- cache.set("key", "value")
- self.assertEqual(cache.get("key"), "value")
-
- def test_non_existent(self):
- # get with non-existent keys
- self.assertEqual(cache.get("does not exist"), None)
- self.assertEqual(cache.get("does not exist", "bang!"), "bang!")
-
- def test_get_many(self):
- # get_many
- cache.set('a', 'a')
- cache.set('b', 'b')
- cache.set('c', 'c')
- cache.set('d', 'd')
- self.assertEqual(cache.get_many(['a', 'c', 'd']), {'a' : 'a', 'c' : 'c', 'd' : 'd'})
- self.assertEqual(cache.get_many(['a', 'b', 'e']), {'a' : 'a', 'b' : 'b'})
-
- def test_delete(self):
- # delete
- cache.set("key1", "spam")
- cache.set("key2", "eggs")
- self.assertEqual(cache.get("key1"), "spam")
- cache.delete("key1")
- self.assertEqual(cache.get("key1"), None)
- self.assertEqual(cache.get("key2"), "eggs")
-
- def test_has_key(self):
- # has_key
- cache.set("hello", "goodbye")
- self.assertEqual(cache.has_key("hello"), True)
- self.assertEqual(cache.has_key("goodbye"), False)
-
- def test_data_types(self):
- # test data types
- stuff = {
- 'string' : 'this is a string',
- 'int' : 42,
- 'list' : [1, 2, 3, 4],
- 'tuple' : (1, 2, 3, 4),
- 'dict' : {'A': 1, 'B' : 2},
- 'function' : f,
- 'class' : C,
- }
- for (key, value) in stuff.items():
- cache.set(key, value)
- self.assertEqual(cache.get(key), value)
-
- def test_expiration(self):
- # expiration
- cache.set('expire', 'very quickly', 1)
- time.sleep(2)
- self.assertEqual(cache.get("expire"), None)
-
-if __name__ == '__main__':
- unittest.main()
\ No newline at end of file
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/datastructures/tests.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,65 +0,0 @@
-"""
-# Tests for stuff in django.utils.datastructures.
-
->>> from django.utils.datastructures import *
-
-### MergeDict #################################################################
-
->>> d1 = {'chris':'cool','camri':'cute','cotton':'adorable','tulip':'snuggable', 'twoofme':'firstone'}
->>> d2 = {'chris2':'cool2','camri2':'cute2','cotton2':'adorable2','tulip2':'snuggable2'}
->>> d3 = {'chris3':'cool3','camri3':'cute3','cotton3':'adorable3','tulip3':'snuggable3'}
->>> d4 = {'twoofme':'secondone'}
->>> md = MergeDict( d1,d2,d3 )
->>> md['chris']
-'cool'
->>> md['camri']
-'cute'
->>> md['twoofme']
-'firstone'
->>> md2 = md.copy()
->>> md2['chris']
-'cool'
-
-### MultiValueDict ##########################################################
-
->>> d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']})
->>> d['name']
-'Simon'
->>> d.getlist('name')
-['Adrian', 'Simon']
->>> d.get('lastname', 'nonexistent')
-'nonexistent'
->>> d.setlist('lastname', ['Holovaty', 'Willison'])
-
-### SortedDict #################################################################
-
->>> d = SortedDict()
->>> d['one'] = 'one'
->>> d['two'] = 'two'
->>> d['three'] = 'three'
->>> d['one']
-'one'
->>> d['two']
-'two'
->>> d['three']
-'three'
->>> d.keys()
-['one', 'two', 'three']
->>> d.values()
-['one', 'two', 'three']
->>> d['one'] = 'not one'
->>> d['one']
-'not one'
->>> d.keys() == d.copy().keys()
-True
-
-### DotExpandedDict ############################################################
-
->>> d = DotExpandedDict({'person.1.firstname': ['Simon'], 'person.1.lastname': ['Willison'], 'person.2.firstname': ['Adrian'], 'person.2.lastname': ['Holovaty']})
->>> d['person']['1']['lastname']
-['Willison']
->>> d['person']['2']['lastname']
-['Holovaty']
->>> d['person']['2']['firstname']
-['Adrian']
-"""
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/dateformat/tests.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,86 +0,0 @@
-r"""
->>> format(my_birthday, '')
-''
->>> format(my_birthday, 'a')
-'p.m.'
->>> format(my_birthday, 'A')
-'PM'
->>> format(my_birthday, 'd')
-'08'
->>> format(my_birthday, 'j')
-'8'
->>> format(my_birthday, 'l')
-'Sunday'
->>> format(my_birthday, 'L')
-'False'
->>> format(my_birthday, 'm')
-'07'
->>> format(my_birthday, 'M')
-'Jul'
->>> format(my_birthday, 'b')
-'jul'
->>> format(my_birthday, 'n')
-'7'
->>> format(my_birthday, 'N')
-'July'
->>> no_tz or format(my_birthday, 'O') == '+0100'
-True
->>> format(my_birthday, 'P')
-'10 p.m.'
->>> no_tz or format(my_birthday, 'r') == 'Sun, 8 Jul 1979 22:00:00 +0100'
-True
->>> format(my_birthday, 's')
-'00'
->>> format(my_birthday, 'S')
-'th'
->>> format(my_birthday, 't')
-'31'
->>> no_tz or format(my_birthday, 'T') == 'CET'
-True
->>> no_tz or format(my_birthday, 'U') == '300531600'
-True
->>> format(my_birthday, 'w')
-'0'
->>> format(my_birthday, 'W')
-'27'
->>> format(my_birthday, 'y')
-'79'
->>> format(my_birthday, 'Y')
-'1979'
->>> format(my_birthday, 'z')
-'189'
->>> no_tz or format(my_birthday, 'Z') == '3600'
-True
-
->>> no_tz or format(summertime, 'I') == '1'
-True
->>> no_tz or format(summertime, 'O') == '+0200'
-True
->>> no_tz or format(wintertime, 'I') == '0'
-True
->>> no_tz or format(wintertime, 'O') == '+0100'
-True
-
->>> format(my_birthday, r'Y z \C\E\T')
-'1979 189 CET'
-
->>> format(my_birthday, r'jS o\f F')
-'8th of July'
-"""
-
-from django.utils import dateformat, translation
-import datetime, os, time
-
-format = dateformat.format
-os.environ['TZ'] = 'Europe/Copenhagen'
-translation.activate('en-us')
-
-try:
- time.tzset()
- no_tz = False
-except AttributeError:
- no_tz = True
-
-my_birthday = datetime.datetime(1979, 7, 8, 22, 00)
-summertime = datetime.datetime(2005, 10, 30, 1, 00)
-wintertime = datetime.datetime(2005, 10, 30, 4, 00)
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/db_typecasts/tests.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,56 +0,0 @@
-# Unit tests for typecast functions in django.db.backends.util
-
-from django.db.backends import util as typecasts
-import datetime, unittest
-
-TEST_CASES = {
- 'typecast_date': (
- ('', None),
- (None, None),
- ('2005-08-11', datetime.date(2005, 8, 11)),
- ('1990-01-01', datetime.date(1990, 1, 1)),
- ),
- 'typecast_time': (
- ('', None),
- (None, None),
- ('0:00:00', datetime.time(0, 0)),
- ('0:30:00', datetime.time(0, 30)),
- ('8:50:00', datetime.time(8, 50)),
- ('08:50:00', datetime.time(8, 50)),
- ('12:00:00', datetime.time(12, 00)),
- ('12:30:00', datetime.time(12, 30)),
- ('13:00:00', datetime.time(13, 00)),
- ('23:59:00', datetime.time(23, 59)),
- ('00:00:12', datetime.time(0, 0, 12)),
- ('00:00:12.5', datetime.time(0, 0, 12, 500000)),
- ('7:22:13.312', datetime.time(7, 22, 13, 312000)),
- ),
- 'typecast_timestamp': (
- ('', None),
- (None, None),
- ('2005-08-11 0:00:00', datetime.datetime(2005, 8, 11)),
- ('2005-08-11 0:30:00', datetime.datetime(2005, 8, 11, 0, 30)),
- ('2005-08-11 8:50:30', datetime.datetime(2005, 8, 11, 8, 50, 30)),
- ('2005-08-11 8:50:30.123', datetime.datetime(2005, 8, 11, 8, 50, 30, 123000)),
- ('2005-08-11 8:50:30.9', datetime.datetime(2005, 8, 11, 8, 50, 30, 900000)),
- ('2005-08-11 8:50:30.312-05', datetime.datetime(2005, 8, 11, 8, 50, 30, 312000)),
- ('2005-08-11 8:50:30.312+02', datetime.datetime(2005, 8, 11, 8, 50, 30, 312000)),
- ),
- 'typecast_boolean': (
- (None, None),
- ('', False),
- ('t', True),
- ('f', False),
- ('x', False),
- ),
-}
-
-class DBTypeCasts(unittest.TestCase):
- def test_typeCasts(self):
- for k, v in TEST_CASES.items():
- for inpt, expected in v:
- got = getattr(typecasts, k)(inpt)
- assert got == expected, "In %s: %r doesn't match %r. Got %r instead." % (k, inpt, expected, got)
-
-if __name__ == '__main__':
- unittest.main()
\ No newline at end of file
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/defaultfilters/tests.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,452 +0,0 @@
-r"""
->>> floatformat(7.7)
-'7.7'
->>> floatformat(7.0)
-'7'
->>> floatformat(0.7)
-'0.7'
->>> floatformat(0.07)
-'0.1'
->>> floatformat(0.007)
-'0.0'
->>> floatformat(0.0)
-'0'
->>> floatformat(7.7,3)
-'7.700'
->>> floatformat(6.000000,3)
-'6.000'
->>> floatformat(13.1031,-3)
-'13.103'
->>> floatformat(11.1197, -2)
-'11.12'
->>> floatformat(11.0000, -2)
-'11'
->>> floatformat(11.000001, -2)
-'11.00'
->>> floatformat(8.2798, 3)
-'8.280'
->>> floatformat('foo')
-''
->>> floatformat(13.1031, 'bar')
-'13.1031'
->>> floatformat('foo', 'bar')
-''
-
->>> addslashes('"double quotes" and \'single quotes\'')
-'\\"double quotes\\" and \\\'single quotes\\\''
-
->>> addslashes(r'\ : backslashes, too')
-'\\\\ : backslashes, too'
-
->>> capfirst('hello world')
-'Hello world'
-
->>> fix_ampersands('Jack & Jill & Jeroboam')
-'Jack & Jill & Jeroboam'
-
->>> linenumbers('line 1\nline 2')
-'1. line 1\n2. line 2'
-
->>> linenumbers('\n'.join(['x'] * 10))
-'01. x\n02. x\n03. x\n04. x\n05. x\n06. x\n07. x\n08. x\n09. x\n10. x'
-
->>> lower('TEST')
-'test'
-
->>> lower(u'\xcb') # uppercase E umlaut
-u'\xeb'
-
->>> make_list('abc')
-['a', 'b', 'c']
-
->>> make_list(1234)
-['1', '2', '3', '4']
-
->>> slugify(' Jack & Jill like numbers 1,2,3 and 4 and silly characters ?%.$!/')
-'jack-jill-like-numbers-123-and-4-and-silly-characters'
-
->>> stringformat(1, '03d')
-'001'
-
->>> stringformat(1, 'z')
-''
-
->>> title('a nice title, isn\'t it?')
-"A Nice Title, Isn't It?"
-
-
->>> truncatewords('A sentence with a few words in it', 1)
-'A ...'
-
->>> truncatewords('A sentence with a few words in it', 5)
-'A sentence with a few ...'
-
->>> truncatewords('A sentence with a few words in it', 100)
-'A sentence with a few words in it'
-
->>> truncatewords('A sentence with a few words in it', 'not a number')
-'A sentence with a few words in it'
-
->>> truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 0)
-''
-
->>> truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 2)
-'<p>one <a href="#">two ...</a></p>'
-
->>> truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 4)
-'<p>one <a href="#">two - three <br>four ...</a></p>'
-
->>> truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 5)
-'<p>one <a href="#">two - three <br>four</a> five</p>'
-
->>> truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 100)
-'<p>one <a href="#">two - three <br>four</a> five</p>'
-
->>> upper('Mixed case input')
-'MIXED CASE INPUT'
-
->>> upper(u'\xeb') # lowercase e umlaut
-u'\xcb'
-
-
->>> urlencode('jack & jill')
-'jack%20%26%20jill'
->>> urlencode(1)
-'1'
-
-
->>> urlizetrunc('http://short.com/', 20)
-'<a href="http://short.com/" rel="nofollow">http://short.com/</a>'
-
->>> urlizetrunc('http://www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search&meta=', 20)
-'<a href="http://www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search&meta=" rel="nofollow">http://www.google.co...</a>'
-
->>> wordcount('')
-0
-
->>> wordcount('oneword')
-1
-
->>> wordcount('lots of words')
-3
-
->>> wordwrap('this is a long paragraph of text that really needs to be wrapped I\'m afraid', 14)
-"this is a long\nparagraph of\ntext that\nreally needs\nto be wrapped\nI'm afraid"
-
->>> wordwrap('this is a short paragraph of text.\n But this line should be indented',14)
-'this is a\nshort\nparagraph of\ntext.\n But this\nline should be\nindented'
-
->>> wordwrap('this is a short paragraph of text.\n But this line should be indented',15)
-'this is a short\nparagraph of\ntext.\n But this line\nshould be\nindented'
-
->>> ljust('test', 10)
-'test '
-
->>> ljust('test', 3)
-'test'
-
->>> rjust('test', 10)
-' test'
-
->>> rjust('test', 3)
-'test'
-
->>> center('test', 6)
-' test '
-
->>> cut('a string to be mangled', 'a')
-' string to be mngled'
-
->>> cut('a string to be mangled', 'ng')
-'a stri to be maled'
-
->>> cut('a string to be mangled', 'strings')
-'a string to be mangled'
-
->>> escape('<some html & special characters > here')
-'<some html & special characters > here'
-
->>> linebreaks('line 1')
-'<p>line 1</p>'
-
->>> linebreaks('line 1\nline 2')
-'<p>line 1<br />line 2</p>'
-
->>> removetags('some <b>html</b> with <script>alert("You smell")</script> disallowed <img /> tags', 'script img')
-'some <b>html</b> with alert("You smell") disallowed tags'
-
->>> striptags('some <b>html</b> with <script>alert("You smell")</script> disallowed <img /> tags')
-'some html with alert("You smell") disallowed tags'
-
->>> dictsort([{'age': 23, 'name': 'Barbara-Ann'},
-... {'age': 63, 'name': 'Ra Ra Rasputin'},
-... {'name': 'Jonny B Goode', 'age': 18}], 'age')
-[{'age': 18, 'name': 'Jonny B Goode'}, {'age': 23, 'name': 'Barbara-Ann'}, {'age': 63, 'name': 'Ra Ra Rasputin'}]
-
->>> dictsortreversed([{'age': 23, 'name': 'Barbara-Ann'},
-... {'age': 63, 'name': 'Ra Ra Rasputin'},
-... {'name': 'Jonny B Goode', 'age': 18}], 'age')
-[{'age': 63, 'name': 'Ra Ra Rasputin'}, {'age': 23, 'name': 'Barbara-Ann'}, {'age': 18, 'name': 'Jonny B Goode'}]
-
->>> first([0,1,2])
-0
-
->>> first('')
-''
-
->>> first('test')
-'t'
-
->>> join([0,1,2], 'glue')
-'0glue1glue2'
-
->>> length('1234')
-4
-
->>> length([1,2,3,4])
-4
-
->>> length_is([], 0)
-True
-
->>> length_is([], 1)
-False
-
->>> length_is('a', 1)
-True
-
->>> length_is('a', 10)
-False
-
->>> slice_('abcdefg', '0')
-''
-
->>> slice_('abcdefg', '1')
-'a'
-
->>> slice_('abcdefg', '-1')
-'abcdef'
-
->>> slice_('abcdefg', '1:2')
-'b'
-
->>> slice_('abcdefg', '1:3')
-'bc'
-
->>> slice_('abcdefg', '0::2')
-'aceg'
-
->>> unordered_list(['item 1', []])
-'\t<li>item 1</li>'
-
->>> unordered_list(['item 1', [['item 1.1', []]]])
-'\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t</ul>\n\t</li>'
-
->>> unordered_list(['item 1', [['item 1.1', []], ['item 1.2', []]]])
-'\t<li>item 1\n\t<ul>\n\t\t<li>item 1.1</li>\n\t\t<li>item 1.2</li>\n\t</ul>\n\t</li>'
-
->>> add('1', '2')
-3
-
->>> get_digit(123, 1)
-3
-
->>> get_digit(123, 2)
-2
-
->>> get_digit(123, 3)
-1
-
->>> get_digit(123, 4)
-0
-
->>> get_digit(123, 0)
-123
-
->>> get_digit('xyz', 0)
-'xyz'
-
-# real testing of date() is in dateformat.py
->>> date(datetime.datetime(2005, 12, 29), "d F Y")
-'29 December 2005'
->>> date(datetime.datetime(2005, 12, 29), r'jS o\f F')
-'29th of December'
-
-# real testing of time() is done in dateformat.py
->>> time(datetime.time(13), "h")
-'01'
-
->>> time(datetime.time(0), "h")
-'12'
-
-# real testing is done in timesince.py, where we can provide our own 'now'
->>> timesince(datetime.datetime.now() - datetime.timedelta(1))
-'1 day'
-
->>> default("val", "default")
-'val'
-
->>> default(None, "default")
-'default'
-
->>> default('', "default")
-'default'
-
->>> default_if_none("val", "default")
-'val'
-
->>> default_if_none(None, "default")
-'default'
-
->>> default_if_none('', "default")
-''
-
->>> divisibleby(4, 2)
-True
-
->>> divisibleby(4, 3)
-False
-
->>> yesno(True)
-'yes'
-
->>> yesno(False)
-'no'
-
->>> yesno(None)
-'maybe'
-
->>> yesno(True, 'certainly,get out of town,perhaps')
-'certainly'
-
->>> yesno(False, 'certainly,get out of town,perhaps')
-'get out of town'
-
->>> yesno(None, 'certainly,get out of town,perhaps')
-'perhaps'
-
->>> yesno(None, 'certainly,get out of town')
-'get out of town'
-
->>> filesizeformat(1023)
-'1023 bytes'
-
->>> filesizeformat(1024)
-'1.0 KB'
-
->>> filesizeformat(10*1024)
-'10.0 KB'
-
->>> filesizeformat(1024*1024-1)
-'1024.0 KB'
-
->>> filesizeformat(1024*1024)
-'1.0 MB'
-
->>> filesizeformat(1024*1024*50)
-'50.0 MB'
-
->>> filesizeformat(1024*1024*1024-1)
-'1024.0 MB'
-
->>> filesizeformat(1024*1024*1024)
-'1.0 GB'
-
->>> pluralize(1)
-''
-
->>> pluralize(0)
-'s'
-
->>> pluralize(2)
-'s'
-
->>> pluralize([1])
-''
-
->>> pluralize([])
-'s'
-
->>> pluralize([1,2,3])
-'s'
-
->>> pluralize(1,'es')
-''
-
->>> pluralize(0,'es')
-'es'
-
->>> pluralize(2,'es')
-'es'
-
->>> pluralize(1,'y,ies')
-'y'
-
->>> pluralize(0,'y,ies')
-'ies'
-
->>> pluralize(2,'y,ies')
-'ies'
-
->>> pluralize(0,'y,ies,error')
-''
-
->>> phone2numeric('0800 flowers')
-'0800 3569377'
-
-# Filters shouldn't break if passed non-strings
->>> addslashes(123)
-'123'
->>> linenumbers(123)
-'1. 123'
->>> lower(123)
-'123'
->>> make_list(123)
-['1', '2', '3']
->>> slugify(123)
-'123'
->>> title(123)
-'123'
->>> truncatewords(123, 2)
-'123'
->>> upper(123)
-'123'
->>> urlencode(123)
-'123'
->>> urlize(123)
-'123'
->>> urlizetrunc(123, 1)
-'123'
->>> wordcount(123)
-1
->>> wordwrap(123, 2)
-'123'
->>> ljust('123', 4)
-'123 '
->>> rjust('123', 4)
-' 123'
->>> center('123', 5)
-' 123 '
->>> center('123', 6)
-' 123 '
->>> cut(123, '2')
-'13'
->>> escape(123)
-'123'
->>> linebreaks(123)
-'<p>123</p>'
->>> linebreaksbr(123)
-'123'
->>> removetags(123, 'a')
-'123'
->>> striptags(123)
-'123'
-
-"""
-
-from django.template.defaultfilters import *
-import datetime
-
-if __name__ == '__main__':
- import doctest
- doctest.testmod()
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/dispatch/__init__.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,2 +0,0 @@
-"""Unit-tests for the dispatch project
-"""
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/dispatch/tests/__init__.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,7 +0,0 @@
-"""
-Unit-tests for the dispatch project
-"""
-
-from test_dispatcher import *
-from test_robustapply import *
-from test_saferef import *
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/dispatch/tests/test_dispatcher.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,144 +0,0 @@
-from django.dispatch.dispatcher import *
-from django.dispatch import dispatcher, robust
-import unittest
-import copy
-
-def x(a):
- return a
-
-class Dummy(object):
- pass
-
-class Callable(object):
- def __call__(self, a):
- return a
-
- def a(self, a):
- return a
-
-class DispatcherTests(unittest.TestCase):
- """Test suite for dispatcher (barely started)"""
-
- def setUp(self):
- # track the initial state, since it's possible that others have bleed receivers in
- self.sendersBack = copy.copy(dispatcher.sendersBack)
- self.connections = copy.copy(dispatcher.connections)
- self.senders = copy.copy(dispatcher.senders)
-
- def _testIsClean(self):
- """Assert that everything has been cleaned up automatically"""
- self.assertEqual(dispatcher.sendersBack, self.sendersBack)
- self.assertEqual(dispatcher.connections, self.connections)
- self.assertEqual(dispatcher.senders, self.senders)
-
- def testExact(self):
- a = Dummy()
- signal = 'this'
- connect(x, signal, a)
- expected = [(x,a)]
- result = send('this',a, a=a)
- self.assertEqual(result, expected)
- disconnect(x, signal, a)
- self.assertEqual(list(getAllReceivers(a,signal)), [])
- self._testIsClean()
-
- def testAnonymousSend(self):
- a = Dummy()
- signal = 'this'
- connect(x, signal)
- expected = [(x,a)]
- result = send(signal,None, a=a)
- self.assertEqual(result, expected)
- disconnect(x, signal)
- self.assertEqual(list(getAllReceivers(None,signal)), [])
- self._testIsClean()
-
- def testAnyRegistration(self):
- a = Dummy()
- signal = 'this'
- connect(x, signal, Any)
- expected = [(x,a)]
- result = send('this',object(), a=a)
- self.assertEqual(result, expected)
- disconnect(x, signal, Any)
- expected = []
- result = send('this',object(), a=a)
- self.assertEqual(result, expected)
- self.assertEqual(list(getAllReceivers(Any,signal)), [])
-
- self._testIsClean()
-
- def testAnyRegistration2(self):
- a = Dummy()
- signal = 'this'
- connect(x, Any, a)
- expected = [(x,a)]
- result = send('this',a, a=a)
- self.assertEqual(result, expected)
- disconnect(x, Any, a)
- self.assertEqual(list(getAllReceivers(a,Any)), [])
- self._testIsClean()
-
- def testGarbageCollected(self):
- a = Callable()
- b = Dummy()
- signal = 'this'
- connect(a.a, signal, b)
- expected = []
- del a
- result = send('this',b, a=b)
- self.assertEqual(result, expected)
- self.assertEqual(list(getAllReceivers(b,signal)), [])
- self._testIsClean()
-
- def testGarbageCollectedObj(self):
- class x:
- def __call__(self, a):
- return a
- a = Callable()
- b = Dummy()
- signal = 'this'
- connect(a, signal, b)
- expected = []
- del a
- result = send('this',b, a=b)
- self.assertEqual(result, expected)
- self.assertEqual(list(getAllReceivers(b,signal)), [])
- self._testIsClean()
-
-
- def testMultipleRegistration(self):
- a = Callable()
- b = Dummy()
- signal = 'this'
- connect(a, signal, b)
- connect(a, signal, b)
- connect(a, signal, b)
- connect(a, signal, b)
- connect(a, signal, b)
- connect(a, signal, b)
- result = send('this',b, a=b)
- self.assertEqual(len(result), 1)
- self.assertEqual(len(list(getAllReceivers(b,signal))), 1)
- del a
- del b
- del result
- self._testIsClean()
-
- def testRobust(self):
- """Test the sendRobust function"""
- def fails():
- raise ValueError('this')
- a = object()
- signal = 'this'
- connect(fails, Any, a)
- result = robust.sendRobust('this',a, a=a)
- err = result[0][1]
- self.assert_(isinstance(err, ValueError))
- self.assertEqual(err.args, ('this',))
-
-def getSuite():
- return unittest.makeSuite(DispatcherTests,'test')
-
-if __name__ == "__main__":
- unittest.main ()
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/dispatch/tests/test_robustapply.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,34 +0,0 @@
-from django.dispatch.robustapply import *
-
-import unittest
-
-def noArgument():
- pass
-
-def oneArgument(blah):
- pass
-
-def twoArgument(blah, other):
- pass
-
-class TestCases(unittest.TestCase):
- def test01(self):
- robustApply(noArgument)
-
- def test02(self):
- self.assertRaises(TypeError, robustApply, noArgument, "this")
-
- def test03(self):
- self.assertRaises(TypeError, robustApply, oneArgument)
-
- def test04(self):
- """Raise error on duplication of a particular argument"""
- self.assertRaises(TypeError, robustApply, oneArgument, "this", blah = "that")
-
-def getSuite():
- return unittest.makeSuite(TestCases,'test')
-
-
-if __name__ == "__main__":
- unittest.main()
-
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/dispatch/tests/test_saferef.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,77 +0,0 @@
-from django.dispatch.saferef import *
-
-import unittest
-
-class Test1(object):
- def x(self):
- pass
-
-def test2(obj):
- pass
-
-class Test2(object):
- def __call__(self, obj):
- pass
-
-class Tester(unittest.TestCase):
- def setUp(self):
- ts = []
- ss = []
- for x in xrange(5000):
- t = Test1()
- ts.append(t)
- s = safeRef(t.x, self._closure)
- ss.append(s)
- ts.append(test2)
- ss.append(safeRef(test2, self._closure))
- for x in xrange(30):
- t = Test2()
- ts.append(t)
- s = safeRef(t, self._closure)
- ss.append(s)
- self.ts = ts
- self.ss = ss
- self.closureCount = 0
-
- def tearDown(self):
- del self.ts
- del self.ss
-
- def testIn(self):
- """Test the "in" operator for safe references (cmp)"""
- for t in self.ts[:50]:
- self.assert_(safeRef(t.x) in self.ss)
-
- def testValid(self):
- """Test that the references are valid (return instance methods)"""
- for s in self.ss:
- self.assert_(s())
-
- def testShortCircuit (self):
- """Test that creation short-circuits to reuse existing references"""
- sd = {}
- for s in self.ss:
- sd[s] = 1
- for t in self.ts:
- if hasattr(t, 'x'):
- self.assert_(sd.has_key(safeRef(t.x)))
- else:
- self.assert_(sd.has_key(safeRef(t)))
-
- def testRepresentation (self):
- """Test that the reference object's representation works
-
- XXX Doesn't currently check the results, just that no error
- is raised
- """
- repr(self.ss[-1])
-
- def _closure(self, ref):
- """Dumb utility mechanism to increment deletion counter"""
- self.closureCount +=1
-
-def getSuite():
- return unittest.makeSuite(Tester,'test')
-
-if __name__ == "__main__":
- unittest.main()
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/forms/tests.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,3585 +0,0 @@
-# -*- coding: utf-8 -*-
-r"""
->>> from django.newforms import *
->>> import datetime
->>> import re
-
-###########
-# Widgets #
-###########
-
-Each Widget class corresponds to an HTML form widget. A Widget knows how to
-render itself, given a field name and some data. Widgets don't perform
-validation.
-
-# TextInput Widget ############################################################
-
->>> w = TextInput()
->>> w.render('email', '')
-u'<input type="text" name="email" />'
->>> w.render('email', None)
-u'<input type="text" name="email" />'
->>> w.render('email', 'test@example.com')
-u'<input type="text" name="email" value="test@example.com" />'
->>> w.render('email', 'some "quoted" & ampersanded value')
-u'<input type="text" name="email" value="some "quoted" & ampersanded value" />'
->>> w.render('email', 'test@example.com', attrs={'class': 'fun'})
-u'<input type="text" name="email" value="test@example.com" class="fun" />'
-
-# Note that doctest in Python 2.4 (and maybe 2.5?) doesn't support non-ascii
-# characters in output, so we're displaying the repr() here.
->>> w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'})
-u'<input type="text" name="email" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" class="fun" />'
-
-You can also pass 'attrs' to the constructor:
->>> w = TextInput(attrs={'class': 'fun'})
->>> w.render('email', '')
-u'<input type="text" class="fun" name="email" />'
->>> w.render('email', 'foo@example.com')
-u'<input type="text" class="fun" value="foo@example.com" name="email" />'
-
-'attrs' passed to render() get precedence over those passed to the constructor:
->>> w = TextInput(attrs={'class': 'pretty'})
->>> w.render('email', '', attrs={'class': 'special'})
-u'<input type="text" class="special" name="email" />'
-
-# PasswordInput Widget ############################################################
-
->>> w = PasswordInput()
->>> w.render('email', '')
-u'<input type="password" name="email" />'
->>> w.render('email', None)
-u'<input type="password" name="email" />'
->>> w.render('email', 'test@example.com')
-u'<input type="password" name="email" value="test@example.com" />'
->>> w.render('email', 'some "quoted" & ampersanded value')
-u'<input type="password" name="email" value="some "quoted" & ampersanded value" />'
->>> w.render('email', 'test@example.com', attrs={'class': 'fun'})
-u'<input type="password" name="email" value="test@example.com" class="fun" />'
-
-You can also pass 'attrs' to the constructor:
->>> w = PasswordInput(attrs={'class': 'fun'})
->>> w.render('email', '')
-u'<input type="password" class="fun" name="email" />'
->>> w.render('email', 'foo@example.com')
-u'<input type="password" class="fun" value="foo@example.com" name="email" />'
-
-'attrs' passed to render() get precedence over those passed to the constructor:
->>> w = PasswordInput(attrs={'class': 'pretty'})
->>> w.render('email', '', attrs={'class': 'special'})
-u'<input type="password" class="special" name="email" />'
-
->>> w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'})
-u'<input type="password" class="fun" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" name="email" />'
-
-The render_value argument lets you specify whether the widget should render
-its value. You may want to do this for security reasons.
->>> w = PasswordInput(render_value=True)
->>> w.render('email', 'secret')
-u'<input type="password" name="email" value="secret" />'
->>> w = PasswordInput(render_value=False)
->>> w.render('email', '')
-u'<input type="password" name="email" />'
->>> w.render('email', None)
-u'<input type="password" name="email" />'
->>> w.render('email', 'secret')
-u'<input type="password" name="email" />'
->>> w = PasswordInput(attrs={'class': 'fun'}, render_value=False)
->>> w.render('email', 'secret')
-u'<input type="password" class="fun" name="email" />'
-
-# HiddenInput Widget ############################################################
-
->>> w = HiddenInput()
->>> w.render('email', '')
-u'<input type="hidden" name="email" />'
->>> w.render('email', None)
-u'<input type="hidden" name="email" />'
->>> w.render('email', 'test@example.com')
-u'<input type="hidden" name="email" value="test@example.com" />'
->>> w.render('email', 'some "quoted" & ampersanded value')
-u'<input type="hidden" name="email" value="some "quoted" & ampersanded value" />'
->>> w.render('email', 'test@example.com', attrs={'class': 'fun'})
-u'<input type="hidden" name="email" value="test@example.com" class="fun" />'
-
-You can also pass 'attrs' to the constructor:
->>> w = HiddenInput(attrs={'class': 'fun'})
->>> w.render('email', '')
-u'<input type="hidden" class="fun" name="email" />'
->>> w.render('email', 'foo@example.com')
-u'<input type="hidden" class="fun" value="foo@example.com" name="email" />'
-
-'attrs' passed to render() get precedence over those passed to the constructor:
->>> w = HiddenInput(attrs={'class': 'pretty'})
->>> w.render('email', '', attrs={'class': 'special'})
-u'<input type="hidden" class="special" name="email" />'
-
->>> w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'})
-u'<input type="hidden" class="fun" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" name="email" />'
-
-'attrs' passed to render() get precedence over those passed to the constructor:
->>> w = HiddenInput(attrs={'class': 'pretty'})
->>> w.render('email', '', attrs={'class': 'special'})
-u'<input type="hidden" class="special" name="email" />'
-
-# MultipleHiddenInput Widget ##################################################
-
->>> w = MultipleHiddenInput()
->>> w.render('email', [])
-u''
->>> w.render('email', None)
-u''
->>> w.render('email', ['test@example.com'])
-u'<input type="hidden" name="email" value="test@example.com" />'
->>> w.render('email', ['some "quoted" & ampersanded value'])
-u'<input type="hidden" name="email" value="some "quoted" & ampersanded value" />'
->>> w.render('email', ['test@example.com', 'foo@example.com'])
-u'<input type="hidden" name="email" value="test@example.com" />\n<input type="hidden" name="email" value="foo@example.com" />'
->>> w.render('email', ['test@example.com'], attrs={'class': 'fun'})
-u'<input type="hidden" name="email" value="test@example.com" class="fun" />'
->>> w.render('email', ['test@example.com', 'foo@example.com'], attrs={'class': 'fun'})
-u'<input type="hidden" name="email" value="test@example.com" class="fun" />\n<input type="hidden" name="email" value="foo@example.com" class="fun" />'
-
-You can also pass 'attrs' to the constructor:
->>> w = MultipleHiddenInput(attrs={'class': 'fun'})
->>> w.render('email', [])
-u''
->>> w.render('email', ['foo@example.com'])
-u'<input type="hidden" class="fun" value="foo@example.com" name="email" />'
->>> w.render('email', ['foo@example.com', 'test@example.com'])
-u'<input type="hidden" class="fun" value="foo@example.com" name="email" />\n<input type="hidden" class="fun" value="test@example.com" name="email" />'
-
-'attrs' passed to render() get precedence over those passed to the constructor:
->>> w = MultipleHiddenInput(attrs={'class': 'pretty'})
->>> w.render('email', ['foo@example.com'], attrs={'class': 'special'})
-u'<input type="hidden" class="special" value="foo@example.com" name="email" />'
-
->>> w.render('email', ['ŠĐĆŽćžšđ'], attrs={'class': 'fun'})
-u'<input type="hidden" class="fun" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" name="email" />'
-
-'attrs' passed to render() get precedence over those passed to the constructor:
->>> w = MultipleHiddenInput(attrs={'class': 'pretty'})
->>> w.render('email', ['foo@example.com'], attrs={'class': 'special'})
-u'<input type="hidden" class="special" value="foo@example.com" name="email" />'
-
-# FileInput Widget ############################################################
-
->>> w = FileInput()
->>> w.render('email', '')
-u'<input type="file" name="email" />'
->>> w.render('email', None)
-u'<input type="file" name="email" />'
->>> w.render('email', 'test@example.com')
-u'<input type="file" name="email" value="test@example.com" />'
->>> w.render('email', 'some "quoted" & ampersanded value')
-u'<input type="file" name="email" value="some "quoted" & ampersanded value" />'
->>> w.render('email', 'test@example.com', attrs={'class': 'fun'})
-u'<input type="file" name="email" value="test@example.com" class="fun" />'
-
-You can also pass 'attrs' to the constructor:
->>> w = FileInput(attrs={'class': 'fun'})
->>> w.render('email', '')
-u'<input type="file" class="fun" name="email" />'
->>> w.render('email', 'foo@example.com')
-u'<input type="file" class="fun" value="foo@example.com" name="email" />'
-
->>> w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'})
-u'<input type="file" class="fun" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" name="email" />'
-
-# Textarea Widget #############################################################
-
->>> w = Textarea()
->>> w.render('msg', '')
-u'<textarea name="msg"></textarea>'
->>> w.render('msg', None)
-u'<textarea name="msg"></textarea>'
->>> w.render('msg', 'value')
-u'<textarea name="msg">value</textarea>'
->>> w.render('msg', 'some "quoted" & ampersanded value')
-u'<textarea name="msg">some "quoted" & ampersanded value</textarea>'
->>> w.render('msg', 'value', attrs={'class': 'pretty'})
-u'<textarea name="msg" class="pretty">value</textarea>'
-
-You can also pass 'attrs' to the constructor:
->>> w = Textarea(attrs={'class': 'pretty'})
->>> w.render('msg', '')
-u'<textarea class="pretty" name="msg"></textarea>'
->>> w.render('msg', 'example')
-u'<textarea class="pretty" name="msg">example</textarea>'
-
-'attrs' passed to render() get precedence over those passed to the constructor:
->>> w = Textarea(attrs={'class': 'pretty'})
->>> w.render('msg', '', attrs={'class': 'special'})
-u'<textarea class="special" name="msg"></textarea>'
-
->>> w.render('msg', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'})
-u'<textarea class="fun" name="msg">\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111</textarea>'
-
-# CheckboxInput Widget ########################################################
-
->>> w = CheckboxInput()
->>> w.render('is_cool', '')
-u'<input type="checkbox" name="is_cool" />'
->>> w.render('is_cool', None)
-u'<input type="checkbox" name="is_cool" />'
->>> w.render('is_cool', False)
-u'<input type="checkbox" name="is_cool" />'
->>> w.render('is_cool', True)
-u'<input checked="checked" type="checkbox" name="is_cool" />'
-
-Using any value that's not in ('', None, False, True) will check the checkbox
-and set the 'value' attribute.
->>> w.render('is_cool', 'foo')
-u'<input checked="checked" type="checkbox" name="is_cool" value="foo" />'
-
->>> w.render('is_cool', False, attrs={'class': 'pretty'})
-u'<input type="checkbox" name="is_cool" class="pretty" />'
-
-You can also pass 'attrs' to the constructor:
->>> w = CheckboxInput(attrs={'class': 'pretty'})
->>> w.render('is_cool', '')
-u'<input type="checkbox" class="pretty" name="is_cool" />'
-
-'attrs' passed to render() get precedence over those passed to the constructor:
->>> w = CheckboxInput(attrs={'class': 'pretty'})
->>> w.render('is_cool', '', attrs={'class': 'special'})
-u'<input type="checkbox" class="special" name="is_cool" />'
-
-You can pass 'check_test' to the constructor. This is a callable that takes the
-value and returns True if the box should be checked.
->>> w = CheckboxInput(check_test=lambda value: value.startswith('hello'))
->>> w.render('greeting', '')
-u'<input type="checkbox" name="greeting" />'
->>> w.render('greeting', 'hello')
-u'<input checked="checked" type="checkbox" name="greeting" value="hello" />'
->>> w.render('greeting', 'hello there')
-u'<input checked="checked" type="checkbox" name="greeting" value="hello there" />'
->>> w.render('greeting', 'hello & goodbye')
-u'<input checked="checked" type="checkbox" name="greeting" value="hello & goodbye" />'
-
-A subtlety: If the 'check_test' argument cannot handle a value and raises any
-exception during its __call__, then the exception will be swallowed and the box
-will not be checked. In this example, the 'check_test' assumes the value has a
-startswith() method, which fails for the values True, False and None.
->>> w.render('greeting', True)
-u'<input type="checkbox" name="greeting" />'
->>> w.render('greeting', False)
-u'<input type="checkbox" name="greeting" />'
->>> w.render('greeting', None)
-u'<input type="checkbox" name="greeting" />'
-
-# Select Widget ###############################################################
-
->>> w = Select()
->>> print w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')))
-<select name="beatle">
-<option value="J" selected="selected">John</option>
-<option value="P">Paul</option>
-<option value="G">George</option>
-<option value="R">Ringo</option>
-</select>
-
-If the value is None, none of the options are selected:
->>> print w.render('beatle', None, choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')))
-<select name="beatle">
-<option value="J">John</option>
-<option value="P">Paul</option>
-<option value="G">George</option>
-<option value="R">Ringo</option>
-</select>
-
-If the value corresponds to a label (but not to an option value), none of the options are selected:
->>> print w.render('beatle', 'John', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')))
-<select name="beatle">
-<option value="J">John</option>
-<option value="P">Paul</option>
-<option value="G">George</option>
-<option value="R">Ringo</option>
-</select>
-
-The value is compared to its str():
->>> print w.render('num', 2, choices=[('1', '1'), ('2', '2'), ('3', '3')])
-<select name="num">
-<option value="1">1</option>
-<option value="2" selected="selected">2</option>
-<option value="3">3</option>
-</select>
->>> print w.render('num', '2', choices=[(1, 1), (2, 2), (3, 3)])
-<select name="num">
-<option value="1">1</option>
-<option value="2" selected="selected">2</option>
-<option value="3">3</option>
-</select>
->>> print w.render('num', 2, choices=[(1, 1), (2, 2), (3, 3)])
-<select name="num">
-<option value="1">1</option>
-<option value="2" selected="selected">2</option>
-<option value="3">3</option>
-</select>
-
-The 'choices' argument can be any iterable:
->>> from itertools import chain
->>> def get_choices():
-... for i in range(5):
-... yield (i, i)
->>> print w.render('num', 2, choices=get_choices())
-<select name="num">
-<option value="0">0</option>
-<option value="1">1</option>
-<option value="2" selected="selected">2</option>
-<option value="3">3</option>
-<option value="4">4</option>
-</select>
->>> things = ({'id': 1, 'name': 'And Boom'}, {'id': 2, 'name': 'One More Thing!'})
->>> class SomeForm(Form):
-... somechoice = ChoiceField(choices=chain((('', '-'*9),), [(thing['id'], thing['name']) for thing in things]))
->>> f = SomeForm()
->>> f.as_table()
-u'<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="" selected="selected">---------</option>\n<option value="1">And Boom</option>\n<option value="2">One More Thing!</option>\n</select></td></tr>'
->>> f.as_table()
-u'<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="" selected="selected">---------</option>\n<option value="1">And Boom</option>\n<option value="2">One More Thing!</option>\n</select></td></tr>'
->>> f = SomeForm({'somechoice': 2})
->>> f.as_table()
-u'<tr><th><label for="id_somechoice">Somechoice:</label></th><td><select name="somechoice" id="id_somechoice">\n<option value="">---------</option>\n<option value="1">And Boom</option>\n<option value="2" selected="selected">One More Thing!</option>\n</select></td></tr>'
-
-You can also pass 'choices' to the constructor:
->>> w = Select(choices=[(1, 1), (2, 2), (3, 3)])
->>> print w.render('num', 2)
-<select name="num">
-<option value="1">1</option>
-<option value="2" selected="selected">2</option>
-<option value="3">3</option>
-</select>
-
-If 'choices' is passed to both the constructor and render(), then they'll both be in the output:
->>> print w.render('num', 2, choices=[(4, 4), (5, 5)])
-<select name="num">
-<option value="1">1</option>
-<option value="2" selected="selected">2</option>
-<option value="3">3</option>
-<option value="4">4</option>
-<option value="5">5</option>
-</select>
-
->>> w.render('email', 'ŠĐĆŽćžšđ', choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')])
-u'<select name="email">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" selected="selected">\u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</option>\n<option value="\u0107\u017e\u0161\u0111">abc\u0107\u017e\u0161\u0111</option>\n</select>'
-
-If choices is passed to the constructor and is a generator, it can be iterated
-over multiple times without getting consumed:
->>> w = Select(choices=get_choices())
->>> print w.render('num', 2)
-<select name="num">
-<option value="0">0</option>
-<option value="1">1</option>
-<option value="2" selected="selected">2</option>
-<option value="3">3</option>
-<option value="4">4</option>
-</select>
->>> print w.render('num', 3)
-<select name="num">
-<option value="0">0</option>
-<option value="1">1</option>
-<option value="2">2</option>
-<option value="3" selected="selected">3</option>
-<option value="4">4</option>
-</select>
-
-# NullBooleanSelect Widget ####################################################
-
->>> w = NullBooleanSelect()
->>> print w.render('is_cool', True)
-<select name="is_cool">
-<option value="1">Unknown</option>
-<option value="2" selected="selected">Yes</option>
-<option value="3">No</option>
-</select>
->>> print w.render('is_cool', False)
-<select name="is_cool">
-<option value="1">Unknown</option>
-<option value="2">Yes</option>
-<option value="3" selected="selected">No</option>
-</select>
->>> print w.render('is_cool', None)
-<select name="is_cool">
-<option value="1" selected="selected">Unknown</option>
-<option value="2">Yes</option>
-<option value="3">No</option>
-</select>
->>> print w.render('is_cool', '2')
-<select name="is_cool">
-<option value="1">Unknown</option>
-<option value="2" selected="selected">Yes</option>
-<option value="3">No</option>
-</select>
->>> print w.render('is_cool', '3')
-<select name="is_cool">
-<option value="1">Unknown</option>
-<option value="2">Yes</option>
-<option value="3" selected="selected">No</option>
-</select>
-
-# SelectMultiple Widget #######################################################
-
->>> w = SelectMultiple()
->>> print w.render('beatles', ['J'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')))
-<select multiple="multiple" name="beatles">
-<option value="J" selected="selected">John</option>
-<option value="P">Paul</option>
-<option value="G">George</option>
-<option value="R">Ringo</option>
-</select>
->>> print w.render('beatles', ['J', 'P'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')))
-<select multiple="multiple" name="beatles">
-<option value="J" selected="selected">John</option>
-<option value="P" selected="selected">Paul</option>
-<option value="G">George</option>
-<option value="R">Ringo</option>
-</select>
->>> print w.render('beatles', ['J', 'P', 'R'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')))
-<select multiple="multiple" name="beatles">
-<option value="J" selected="selected">John</option>
-<option value="P" selected="selected">Paul</option>
-<option value="G">George</option>
-<option value="R" selected="selected">Ringo</option>
-</select>
-
-If the value is None, none of the options are selected:
->>> print w.render('beatles', None, choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')))
-<select multiple="multiple" name="beatles">
-<option value="J">John</option>
-<option value="P">Paul</option>
-<option value="G">George</option>
-<option value="R">Ringo</option>
-</select>
-
-If the value corresponds to a label (but not to an option value), none of the options are selected:
->>> print w.render('beatles', ['John'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')))
-<select multiple="multiple" name="beatles">
-<option value="J">John</option>
-<option value="P">Paul</option>
-<option value="G">George</option>
-<option value="R">Ringo</option>
-</select>
-
-If multiple values are given, but some of them are not valid, the valid ones are selected:
->>> print w.render('beatles', ['J', 'G', 'foo'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')))
-<select multiple="multiple" name="beatles">
-<option value="J" selected="selected">John</option>
-<option value="P">Paul</option>
-<option value="G" selected="selected">George</option>
-<option value="R">Ringo</option>
-</select>
-
-The value is compared to its str():
->>> print w.render('nums', [2], choices=[('1', '1'), ('2', '2'), ('3', '3')])
-<select multiple="multiple" name="nums">
-<option value="1">1</option>
-<option value="2" selected="selected">2</option>
-<option value="3">3</option>
-</select>
->>> print w.render('nums', ['2'], choices=[(1, 1), (2, 2), (3, 3)])
-<select multiple="multiple" name="nums">
-<option value="1">1</option>
-<option value="2" selected="selected">2</option>
-<option value="3">3</option>
-</select>
->>> print w.render('nums', [2], choices=[(1, 1), (2, 2), (3, 3)])
-<select multiple="multiple" name="nums">
-<option value="1">1</option>
-<option value="2" selected="selected">2</option>
-<option value="3">3</option>
-</select>
-
-The 'choices' argument can be any iterable:
->>> def get_choices():
-... for i in range(5):
-... yield (i, i)
->>> print w.render('nums', [2], choices=get_choices())
-<select multiple="multiple" name="nums">
-<option value="0">0</option>
-<option value="1">1</option>
-<option value="2" selected="selected">2</option>
-<option value="3">3</option>
-<option value="4">4</option>
-</select>
-
-You can also pass 'choices' to the constructor:
->>> w = SelectMultiple(choices=[(1, 1), (2, 2), (3, 3)])
->>> print w.render('nums', [2])
-<select multiple="multiple" name="nums">
-<option value="1">1</option>
-<option value="2" selected="selected">2</option>
-<option value="3">3</option>
-</select>
-
-If 'choices' is passed to both the constructor and render(), then they'll both be in the output:
->>> print w.render('nums', [2], choices=[(4, 4), (5, 5)])
-<select multiple="multiple" name="nums">
-<option value="1">1</option>
-<option value="2" selected="selected">2</option>
-<option value="3">3</option>
-<option value="4">4</option>
-<option value="5">5</option>
-</select>
-
->>> w.render('nums', ['ŠĐĆŽćžšđ'], choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')])
-u'<select multiple="multiple" name="nums">\n<option value="1">1</option>\n<option value="2">2</option>\n<option value="3">3</option>\n<option value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" selected="selected">\u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</option>\n<option value="\u0107\u017e\u0161\u0111">abc\u0107\u017e\u0161\u0111</option>\n</select>'
-
-# RadioSelect Widget ##########################################################
-
->>> w = RadioSelect()
->>> print w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')))
-<ul>
-<li><label><input checked="checked" type="radio" name="beatle" value="J" /> John</label></li>
-<li><label><input type="radio" name="beatle" value="P" /> Paul</label></li>
-<li><label><input type="radio" name="beatle" value="G" /> George</label></li>
-<li><label><input type="radio" name="beatle" value="R" /> Ringo</label></li>
-</ul>
-
-If the value is None, none of the options are checked:
->>> print w.render('beatle', None, choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')))
-<ul>
-<li><label><input type="radio" name="beatle" value="J" /> John</label></li>
-<li><label><input type="radio" name="beatle" value="P" /> Paul</label></li>
-<li><label><input type="radio" name="beatle" value="G" /> George</label></li>
-<li><label><input type="radio" name="beatle" value="R" /> Ringo</label></li>
-</ul>
-
-If the value corresponds to a label (but not to an option value), none of the options are checked:
->>> print w.render('beatle', 'John', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')))
-<ul>
-<li><label><input type="radio" name="beatle" value="J" /> John</label></li>
-<li><label><input type="radio" name="beatle" value="P" /> Paul</label></li>
-<li><label><input type="radio" name="beatle" value="G" /> George</label></li>
-<li><label><input type="radio" name="beatle" value="R" /> Ringo</label></li>
-</ul>
-
-The value is compared to its str():
->>> print w.render('num', 2, choices=[('1', '1'), ('2', '2'), ('3', '3')])
-<ul>
-<li><label><input type="radio" name="num" value="1" /> 1</label></li>
-<li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li>
-<li><label><input type="radio" name="num" value="3" /> 3</label></li>
-</ul>
->>> print w.render('num', '2', choices=[(1, 1), (2, 2), (3, 3)])
-<ul>
-<li><label><input type="radio" name="num" value="1" /> 1</label></li>
-<li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li>
-<li><label><input type="radio" name="num" value="3" /> 3</label></li>
-</ul>
->>> print w.render('num', 2, choices=[(1, 1), (2, 2), (3, 3)])
-<ul>
-<li><label><input type="radio" name="num" value="1" /> 1</label></li>
-<li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li>
-<li><label><input type="radio" name="num" value="3" /> 3</label></li>
-</ul>
-
-The 'choices' argument can be any iterable:
->>> def get_choices():
-... for i in range(5):
-... yield (i, i)
->>> print w.render('num', 2, choices=get_choices())
-<ul>
-<li><label><input type="radio" name="num" value="0" /> 0</label></li>
-<li><label><input type="radio" name="num" value="1" /> 1</label></li>
-<li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li>
-<li><label><input type="radio" name="num" value="3" /> 3</label></li>
-<li><label><input type="radio" name="num" value="4" /> 4</label></li>
-</ul>
-
-You can also pass 'choices' to the constructor:
->>> w = RadioSelect(choices=[(1, 1), (2, 2), (3, 3)])
->>> print w.render('num', 2)
-<ul>
-<li><label><input type="radio" name="num" value="1" /> 1</label></li>
-<li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li>
-<li><label><input type="radio" name="num" value="3" /> 3</label></li>
-</ul>
-
-If 'choices' is passed to both the constructor and render(), then they'll both be in the output:
->>> print w.render('num', 2, choices=[(4, 4), (5, 5)])
-<ul>
-<li><label><input type="radio" name="num" value="1" /> 1</label></li>
-<li><label><input checked="checked" type="radio" name="num" value="2" /> 2</label></li>
-<li><label><input type="radio" name="num" value="3" /> 3</label></li>
-<li><label><input type="radio" name="num" value="4" /> 4</label></li>
-<li><label><input type="radio" name="num" value="5" /> 5</label></li>
-</ul>
-
-The render() method returns a RadioFieldRenderer object, whose str() is a <ul>.
-You can manipulate that object directly to customize the way the RadioSelect
-is rendered.
->>> w = RadioSelect()
->>> r = w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')))
->>> for inp in r:
-... print inp
-<label><input checked="checked" type="radio" name="beatle" value="J" /> John</label>
-<label><input type="radio" name="beatle" value="P" /> Paul</label>
-<label><input type="radio" name="beatle" value="G" /> George</label>
-<label><input type="radio" name="beatle" value="R" /> Ringo</label>
->>> for inp in r:
-... print '%s<br />' % inp
-<label><input checked="checked" type="radio" name="beatle" value="J" /> John</label><br />
-<label><input type="radio" name="beatle" value="P" /> Paul</label><br />
-<label><input type="radio" name="beatle" value="G" /> George</label><br />
-<label><input type="radio" name="beatle" value="R" /> Ringo</label><br />
->>> for inp in r:
-... print '<p>%s %s</p>' % (inp.tag(), inp.choice_label)
-<p><input checked="checked" type="radio" name="beatle" value="J" /> John</p>
-<p><input type="radio" name="beatle" value="P" /> Paul</p>
-<p><input type="radio" name="beatle" value="G" /> George</p>
-<p><input type="radio" name="beatle" value="R" /> Ringo</p>
->>> for inp in r:
-... print '%s %s %s %s %s' % (inp.name, inp.value, inp.choice_value, inp.choice_label, inp.is_checked())
-beatle J J John True
-beatle J P Paul False
-beatle J G George False
-beatle J R Ringo False
-
-A RadioFieldRenderer object also allows index access to individual RadioInput
-objects.
->>> w = RadioSelect()
->>> r = w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')))
->>> print r[1]
-<label><input type="radio" name="beatle" value="P" /> Paul</label>
->>> print r[0]
-<label><input checked="checked" type="radio" name="beatle" value="J" /> John</label>
->>> r[0].is_checked()
-True
->>> r[1].is_checked()
-False
->>> r[1].name, r[1].value, r[1].choice_value, r[1].choice_label
-('beatle', u'J', u'P', u'Paul')
->>> r[10]
-Traceback (most recent call last):
-...
-IndexError: list index out of range
-
->>> w = RadioSelect()
->>> unicode(w.render('email', 'ŠĐĆŽćžšđ', choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]))
-u'<ul>\n<li><label><input checked="checked" type="radio" name="email" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" /> \u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</label></li>\n<li><label><input type="radio" name="email" value="\u0107\u017e\u0161\u0111" /> abc\u0107\u017e\u0161\u0111</label></li>\n</ul>'
-
-# CheckboxSelectMultiple Widget ###############################################
-
->>> w = CheckboxSelectMultiple()
->>> print w.render('beatles', ['J'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')))
-<ul>
-<li><label><input checked="checked" type="checkbox" name="beatles" value="J" /> John</label></li>
-<li><label><input type="checkbox" name="beatles" value="P" /> Paul</label></li>
-<li><label><input type="checkbox" name="beatles" value="G" /> George</label></li>
-<li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li>
-</ul>
->>> print w.render('beatles', ['J', 'P'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')))
-<ul>
-<li><label><input checked="checked" type="checkbox" name="beatles" value="J" /> John</label></li>
-<li><label><input checked="checked" type="checkbox" name="beatles" value="P" /> Paul</label></li>
-<li><label><input type="checkbox" name="beatles" value="G" /> George</label></li>
-<li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li>
-</ul>
->>> print w.render('beatles', ['J', 'P', 'R'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')))
-<ul>
-<li><label><input checked="checked" type="checkbox" name="beatles" value="J" /> John</label></li>
-<li><label><input checked="checked" type="checkbox" name="beatles" value="P" /> Paul</label></li>
-<li><label><input type="checkbox" name="beatles" value="G" /> George</label></li>
-<li><label><input checked="checked" type="checkbox" name="beatles" value="R" /> Ringo</label></li>
-</ul>
-
-If the value is None, none of the options are selected:
->>> print w.render('beatles', None, choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')))
-<ul>
-<li><label><input type="checkbox" name="beatles" value="J" /> John</label></li>
-<li><label><input type="checkbox" name="beatles" value="P" /> Paul</label></li>
-<li><label><input type="checkbox" name="beatles" value="G" /> George</label></li>
-<li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li>
-</ul>
-
-If the value corresponds to a label (but not to an option value), none of the options are selected:
->>> print w.render('beatles', ['John'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')))
-<ul>
-<li><label><input type="checkbox" name="beatles" value="J" /> John</label></li>
-<li><label><input type="checkbox" name="beatles" value="P" /> Paul</label></li>
-<li><label><input type="checkbox" name="beatles" value="G" /> George</label></li>
-<li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li>
-</ul>
-
-If multiple values are given, but some of them are not valid, the valid ones are selected:
->>> print w.render('beatles', ['J', 'G', 'foo'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')))
-<ul>
-<li><label><input checked="checked" type="checkbox" name="beatles" value="J" /> John</label></li>
-<li><label><input type="checkbox" name="beatles" value="P" /> Paul</label></li>
-<li><label><input checked="checked" type="checkbox" name="beatles" value="G" /> George</label></li>
-<li><label><input type="checkbox" name="beatles" value="R" /> Ringo</label></li>
-</ul>
-
-The value is compared to its str():
->>> print w.render('nums', [2], choices=[('1', '1'), ('2', '2'), ('3', '3')])
-<ul>
-<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li>
-<li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li>
-<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li>
-</ul>
->>> print w.render('nums', ['2'], choices=[(1, 1), (2, 2), (3, 3)])
-<ul>
-<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li>
-<li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li>
-<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li>
-</ul>
->>> print w.render('nums', [2], choices=[(1, 1), (2, 2), (3, 3)])
-<ul>
-<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li>
-<li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li>
-<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li>
-</ul>
-
-The 'choices' argument can be any iterable:
->>> def get_choices():
-... for i in range(5):
-... yield (i, i)
->>> print w.render('nums', [2], choices=get_choices())
-<ul>
-<li><label><input type="checkbox" name="nums" value="0" /> 0</label></li>
-<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li>
-<li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li>
-<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li>
-<li><label><input type="checkbox" name="nums" value="4" /> 4</label></li>
-</ul>
-
-You can also pass 'choices' to the constructor:
->>> w = CheckboxSelectMultiple(choices=[(1, 1), (2, 2), (3, 3)])
->>> print w.render('nums', [2])
-<ul>
-<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li>
-<li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li>
-<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li>
-</ul>
-
-If 'choices' is passed to both the constructor and render(), then they'll both be in the output:
->>> print w.render('nums', [2], choices=[(4, 4), (5, 5)])
-<ul>
-<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li>
-<li><label><input checked="checked" type="checkbox" name="nums" value="2" /> 2</label></li>
-<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li>
-<li><label><input type="checkbox" name="nums" value="4" /> 4</label></li>
-<li><label><input type="checkbox" name="nums" value="5" /> 5</label></li>
-</ul>
-
->>> w.render('nums', ['ŠĐĆŽćžšđ'], choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')])
-u'<ul>\n<li><label><input type="checkbox" name="nums" value="1" /> 1</label></li>\n<li><label><input type="checkbox" name="nums" value="2" /> 2</label></li>\n<li><label><input type="checkbox" name="nums" value="3" /> 3</label></li>\n<li><label><input checked="checked" type="checkbox" name="nums" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" /> \u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</label></li>\n<li><label><input type="checkbox" name="nums" value="\u0107\u017e\u0161\u0111" /> abc\u0107\u017e\u0161\u0111</label></li>\n</ul>'
-
-# MultiWidget #################################################################
-
->>> class MyMultiWidget(MultiWidget):
-... def decompress(self, value):
-... if value:
-... return value.split('__')
-... return ['', '']
-... def format_output(self, rendered_widgets):
-... return u'<br />'.join(rendered_widgets)
->>> w = MyMultiWidget(widgets=(TextInput(attrs={'class': 'big'}), TextInput(attrs={'class': 'small'})))
->>> w.render('name', ['john', 'lennon'])
-u'<input type="text" class="big" value="john" name="name_0" /><br /><input type="text" class="small" value="lennon" name="name_1" />'
->>> w.render('name', 'john__lennon')
-u'<input type="text" class="big" value="john" name="name_0" /><br /><input type="text" class="small" value="lennon" name="name_1" />'
-
-# SplitDateTimeWidget #########################################################
-
->>> w = SplitDateTimeWidget()
->>> w.render('date', '')
-u'<input type="text" name="date_0" /><input type="text" name="date_1" />'
->>> w.render('date', None)
-u'<input type="text" name="date_0" /><input type="text" name="date_1" />'
->>> w.render('date', datetime.datetime(2006, 1, 10, 7, 30))
-u'<input type="text" name="date_0" value="2006-01-10" /><input type="text" name="date_1" value="07:30:00" />'
->>> w.render('date', [datetime.date(2006, 1, 10), datetime.time(7, 30)])
-u'<input type="text" name="date_0" value="2006-01-10" /><input type="text" name="date_1" value="07:30:00" />'
-
-You can also pass 'attrs' to the constructor. In this case, the attrs will be
-included on both widgets.
->>> w = SplitDateTimeWidget(attrs={'class': 'pretty'})
->>> w.render('date', datetime.datetime(2006, 1, 10, 7, 30))
-u'<input type="text" class="pretty" value="2006-01-10" name="date_0" /><input type="text" class="pretty" value="07:30:00" name="date_1" />'
-
-##########
-# Fields #
-##########
-
-Each Field class does some sort of validation. Each Field has a clean() method,
-which either raises django.newforms.ValidationError or returns the "clean"
-data -- usually a Unicode object, but, in some rare cases, a list.
-
-Each Field's __init__() takes at least these parameters:
- required -- Boolean that specifies whether the field is required.
- True by default.
- widget -- A Widget class, or instance of a Widget class, that should be
- used for this Field when displaying it. Each Field has a default
- Widget that it'll use if you don't specify this. In most cases,
- the default widget is TextInput.
- label -- A verbose name for this field, for use in displaying this field in
- a form. By default, Django will use a "pretty" version of the form
- field name, if the Field is part of a Form.
- initial -- A value to use in this Field's initial display. This value is
- *not* used as a fallback if data isn't given.
-
-Other than that, the Field subclasses have class-specific options for
-__init__(). For example, CharField has a max_length option.
-
-# CharField ###################################################################
-
->>> f = CharField()
->>> f.clean(1)
-u'1'
->>> f.clean('hello')
-u'hello'
->>> f.clean(None)
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean('')
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean([1, 2, 3])
-u'[1, 2, 3]'
-
->>> f = CharField(required=False)
->>> f.clean(1)
-u'1'
->>> f.clean('hello')
-u'hello'
->>> f.clean(None)
-u''
->>> f.clean('')
-u''
->>> f.clean([1, 2, 3])
-u'[1, 2, 3]'
-
-CharField accepts an optional max_length parameter:
->>> f = CharField(max_length=10, required=False)
->>> f.clean('12345')
-u'12345'
->>> f.clean('1234567890')
-u'1234567890'
->>> f.clean('1234567890a')
-Traceback (most recent call last):
-...
-ValidationError: [u'Ensure this value has at most 10 characters.']
-
-CharField accepts an optional min_length parameter:
->>> f = CharField(min_length=10, required=False)
->>> f.clean('')
-u''
->>> f.clean('12345')
-Traceback (most recent call last):
-...
-ValidationError: [u'Ensure this value has at least 10 characters.']
->>> f.clean('1234567890')
-u'1234567890'
->>> f.clean('1234567890a')
-u'1234567890a'
-
->>> f = CharField(min_length=10, required=True)
->>> f.clean('')
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean('12345')
-Traceback (most recent call last):
-...
-ValidationError: [u'Ensure this value has at least 10 characters.']
->>> f.clean('1234567890')
-u'1234567890'
->>> f.clean('1234567890a')
-u'1234567890a'
-
-# IntegerField ################################################################
-
->>> f = IntegerField()
->>> f.clean('')
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean(None)
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean('1')
-1
->>> isinstance(f.clean('1'), int)
-True
->>> f.clean('23')
-23
->>> f.clean('a')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a whole number.']
->>> f.clean('1 ')
-1
->>> f.clean(' 1')
-1
->>> f.clean(' 1 ')
-1
->>> f.clean('1a')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a whole number.']
-
->>> f = IntegerField(required=False)
->>> f.clean('')
->>> repr(f.clean(''))
-'None'
->>> f.clean(None)
->>> repr(f.clean(None))
-'None'
->>> f.clean('1')
-1
->>> isinstance(f.clean('1'), int)
-True
->>> f.clean('23')
-23
->>> f.clean('a')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a whole number.']
->>> f.clean('1 ')
-1
->>> f.clean(' 1')
-1
->>> f.clean(' 1 ')
-1
->>> f.clean('1a')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a whole number.']
-
-IntegerField accepts an optional max_value parameter:
->>> f = IntegerField(max_value=10)
->>> f.clean(None)
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean(1)
-1
->>> f.clean(10)
-10
->>> f.clean(11)
-Traceback (most recent call last):
-...
-ValidationError: [u'Ensure this value is less than or equal to 10.']
->>> f.clean('10')
-10
->>> f.clean('11')
-Traceback (most recent call last):
-...
-ValidationError: [u'Ensure this value is less than or equal to 10.']
-
-IntegerField accepts an optional min_value parameter:
->>> f = IntegerField(min_value=10)
->>> f.clean(None)
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean(1)
-Traceback (most recent call last):
-...
-ValidationError: [u'Ensure this value is greater than or equal to 10.']
->>> f.clean(10)
-10
->>> f.clean(11)
-11
->>> f.clean('10')
-10
->>> f.clean('11')
-11
-
-min_value and max_value can be used together:
->>> f = IntegerField(min_value=10, max_value=20)
->>> f.clean(None)
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean(1)
-Traceback (most recent call last):
-...
-ValidationError: [u'Ensure this value is greater than or equal to 10.']
->>> f.clean(10)
-10
->>> f.clean(11)
-11
->>> f.clean('10')
-10
->>> f.clean('11')
-11
->>> f.clean(20)
-20
->>> f.clean(21)
-Traceback (most recent call last):
-...
-ValidationError: [u'Ensure this value is less than or equal to 20.']
-
-# DateField ###################################################################
-
->>> import datetime
->>> f = DateField()
->>> f.clean(datetime.date(2006, 10, 25))
-datetime.date(2006, 10, 25)
->>> f.clean(datetime.datetime(2006, 10, 25, 14, 30))
-datetime.date(2006, 10, 25)
->>> f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59))
-datetime.date(2006, 10, 25)
->>> f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200))
-datetime.date(2006, 10, 25)
->>> f.clean('2006-10-25')
-datetime.date(2006, 10, 25)
->>> f.clean('10/25/2006')
-datetime.date(2006, 10, 25)
->>> f.clean('10/25/06')
-datetime.date(2006, 10, 25)
->>> f.clean('Oct 25 2006')
-datetime.date(2006, 10, 25)
->>> f.clean('October 25 2006')
-datetime.date(2006, 10, 25)
->>> f.clean('October 25, 2006')
-datetime.date(2006, 10, 25)
->>> f.clean('25 October 2006')
-datetime.date(2006, 10, 25)
->>> f.clean('25 October, 2006')
-datetime.date(2006, 10, 25)
->>> f.clean('2006-4-31')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid date.']
->>> f.clean('200a-10-25')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid date.']
->>> f.clean('25/10/06')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid date.']
->>> f.clean(None)
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
-
->>> f = DateField(required=False)
->>> f.clean(None)
->>> repr(f.clean(None))
-'None'
->>> f.clean('')
->>> repr(f.clean(''))
-'None'
-
-DateField accepts an optional input_formats parameter:
->>> f = DateField(input_formats=['%Y %m %d'])
->>> f.clean(datetime.date(2006, 10, 25))
-datetime.date(2006, 10, 25)
->>> f.clean(datetime.datetime(2006, 10, 25, 14, 30))
-datetime.date(2006, 10, 25)
->>> f.clean('2006 10 25')
-datetime.date(2006, 10, 25)
-
-The input_formats parameter overrides all default input formats,
-so the default formats won't work unless you specify them:
->>> f.clean('2006-10-25')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid date.']
->>> f.clean('10/25/2006')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid date.']
->>> f.clean('10/25/06')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid date.']
-
-# TimeField ###################################################################
-
->>> import datetime
->>> f = TimeField()
->>> f.clean(datetime.time(14, 25))
-datetime.time(14, 25)
->>> f.clean(datetime.time(14, 25, 59))
-datetime.time(14, 25, 59)
->>> f.clean('14:25')
-datetime.time(14, 25)
->>> f.clean('14:25:59')
-datetime.time(14, 25, 59)
->>> f.clean('hello')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid time.']
->>> f.clean('1:24 p.m.')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid time.']
-
-TimeField accepts an optional input_formats parameter:
->>> f = TimeField(input_formats=['%I:%M %p'])
->>> f.clean(datetime.time(14, 25))
-datetime.time(14, 25)
->>> f.clean(datetime.time(14, 25, 59))
-datetime.time(14, 25, 59)
->>> f.clean('4:25 AM')
-datetime.time(4, 25)
->>> f.clean('4:25 PM')
-datetime.time(16, 25)
-
-The input_formats parameter overrides all default input formats,
-so the default formats won't work unless you specify them:
->>> f.clean('14:30:45')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid time.']
-
-# DateTimeField ###############################################################
-
->>> import datetime
->>> f = DateTimeField()
->>> f.clean(datetime.date(2006, 10, 25))
-datetime.datetime(2006, 10, 25, 0, 0)
->>> f.clean(datetime.datetime(2006, 10, 25, 14, 30))
-datetime.datetime(2006, 10, 25, 14, 30)
->>> f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59))
-datetime.datetime(2006, 10, 25, 14, 30, 59)
->>> f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200))
-datetime.datetime(2006, 10, 25, 14, 30, 59, 200)
->>> f.clean('2006-10-25 14:30:45')
-datetime.datetime(2006, 10, 25, 14, 30, 45)
->>> f.clean('2006-10-25 14:30:00')
-datetime.datetime(2006, 10, 25, 14, 30)
->>> f.clean('2006-10-25 14:30')
-datetime.datetime(2006, 10, 25, 14, 30)
->>> f.clean('2006-10-25')
-datetime.datetime(2006, 10, 25, 0, 0)
->>> f.clean('10/25/2006 14:30:45')
-datetime.datetime(2006, 10, 25, 14, 30, 45)
->>> f.clean('10/25/2006 14:30:00')
-datetime.datetime(2006, 10, 25, 14, 30)
->>> f.clean('10/25/2006 14:30')
-datetime.datetime(2006, 10, 25, 14, 30)
->>> f.clean('10/25/2006')
-datetime.datetime(2006, 10, 25, 0, 0)
->>> f.clean('10/25/06 14:30:45')
-datetime.datetime(2006, 10, 25, 14, 30, 45)
->>> f.clean('10/25/06 14:30:00')
-datetime.datetime(2006, 10, 25, 14, 30)
->>> f.clean('10/25/06 14:30')
-datetime.datetime(2006, 10, 25, 14, 30)
->>> f.clean('10/25/06')
-datetime.datetime(2006, 10, 25, 0, 0)
->>> f.clean('hello')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid date/time.']
->>> f.clean('2006-10-25 4:30 p.m.')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid date/time.']
-
-DateField accepts an optional input_formats parameter:
->>> f = DateTimeField(input_formats=['%Y %m %d %I:%M %p'])
->>> f.clean(datetime.date(2006, 10, 25))
-datetime.datetime(2006, 10, 25, 0, 0)
->>> f.clean(datetime.datetime(2006, 10, 25, 14, 30))
-datetime.datetime(2006, 10, 25, 14, 30)
->>> f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59))
-datetime.datetime(2006, 10, 25, 14, 30, 59)
->>> f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200))
-datetime.datetime(2006, 10, 25, 14, 30, 59, 200)
->>> f.clean('2006 10 25 2:30 PM')
-datetime.datetime(2006, 10, 25, 14, 30)
-
-The input_formats parameter overrides all default input formats,
-so the default formats won't work unless you specify them:
->>> f.clean('2006-10-25 14:30:45')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid date/time.']
-
->>> f = DateTimeField(required=False)
->>> f.clean(None)
->>> repr(f.clean(None))
-'None'
->>> f.clean('')
->>> repr(f.clean(''))
-'None'
-
-# RegexField ##################################################################
-
->>> f = RegexField('^\d[A-F]\d$')
->>> f.clean('2A2')
-u'2A2'
->>> f.clean('3F3')
-u'3F3'
->>> f.clean('3G3')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid value.']
->>> f.clean(' 2A2')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid value.']
->>> f.clean('2A2 ')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid value.']
->>> f.clean('')
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
-
->>> f = RegexField('^\d[A-F]\d$', required=False)
->>> f.clean('2A2')
-u'2A2'
->>> f.clean('3F3')
-u'3F3'
->>> f.clean('3G3')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid value.']
->>> f.clean('')
-u''
-
-Alternatively, RegexField can take a compiled regular expression:
->>> f = RegexField(re.compile('^\d[A-F]\d$'))
->>> f.clean('2A2')
-u'2A2'
->>> f.clean('3F3')
-u'3F3'
->>> f.clean('3G3')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid value.']
->>> f.clean(' 2A2')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid value.']
->>> f.clean('2A2 ')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid value.']
-
-RegexField takes an optional error_message argument:
->>> f = RegexField('^\d\d\d\d$', error_message='Enter a four-digit number.')
->>> f.clean('1234')
-u'1234'
->>> f.clean('123')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a four-digit number.']
->>> f.clean('abcd')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a four-digit number.']
-
-RegexField also access min_length and max_length parameters, for convenience.
->>> f = RegexField('^\d+$', min_length=5, max_length=10)
->>> f.clean('123')
-Traceback (most recent call last):
-...
-ValidationError: [u'Ensure this value has at least 5 characters.']
->>> f.clean('abc')
-Traceback (most recent call last):
-...
-ValidationError: [u'Ensure this value has at least 5 characters.']
->>> f.clean('12345')
-u'12345'
->>> f.clean('1234567890')
-u'1234567890'
->>> f.clean('12345678901')
-Traceback (most recent call last):
-...
-ValidationError: [u'Ensure this value has at most 10 characters.']
->>> f.clean('12345a')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid value.']
-
-# EmailField ##################################################################
-
->>> f = EmailField()
->>> f.clean('')
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean(None)
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean('person@example.com')
-u'person@example.com'
->>> f.clean('foo')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid e-mail address.']
->>> f.clean('foo@')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid e-mail address.']
->>> f.clean('foo@bar')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid e-mail address.']
-
->>> f = EmailField(required=False)
->>> f.clean('')
-u''
->>> f.clean(None)
-u''
->>> f.clean('person@example.com')
-u'person@example.com'
->>> f.clean('foo')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid e-mail address.']
->>> f.clean('foo@')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid e-mail address.']
->>> f.clean('foo@bar')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid e-mail address.']
-
-EmailField also access min_length and max_length parameters, for convenience.
->>> f = EmailField(min_length=10, max_length=15)
->>> f.clean('a@foo.com')
-Traceback (most recent call last):
-...
-ValidationError: [u'Ensure this value has at least 10 characters.']
->>> f.clean('alf@foo.com')
-u'alf@foo.com'
->>> f.clean('alf123456788@foo.com')
-Traceback (most recent call last):
-...
-ValidationError: [u'Ensure this value has at most 15 characters.']
-
-# URLField ##################################################################
-
->>> f = URLField()
->>> f.clean('')
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean(None)
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean('http://example.com')
-u'http://example.com'
->>> f.clean('http://www.example.com')
-u'http://www.example.com'
->>> f.clean('foo')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid URL.']
->>> f.clean('example.com')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid URL.']
->>> f.clean('http://')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid URL.']
->>> f.clean('http://example')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid URL.']
->>> f.clean('http://example.')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid URL.']
->>> f.clean('http://.com')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid URL.']
-
->>> f = URLField(required=False)
->>> f.clean('')
-u''
->>> f.clean(None)
-u''
->>> f.clean('http://example.com')
-u'http://example.com'
->>> f.clean('http://www.example.com')
-u'http://www.example.com'
->>> f.clean('foo')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid URL.']
->>> f.clean('example.com')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid URL.']
->>> f.clean('http://')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid URL.']
->>> f.clean('http://example')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid URL.']
->>> f.clean('http://example.')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid URL.']
->>> f.clean('http://.com')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid URL.']
-
-URLField takes an optional verify_exists parameter, which is False by default.
-This verifies that the URL is live on the Internet and doesn't return a 404 or 500:
->>> f = URLField(verify_exists=True)
->>> f.clean('http://www.google.com') # This will fail if there's no Internet connection
-u'http://www.google.com'
->>> f.clean('http://example')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid URL.']
->>> f.clean('http://www.jfoiwjfoi23jfoijoaijfoiwjofiwjefewl.com') # bad domain
-Traceback (most recent call last):
-...
-ValidationError: [u'This URL appears to be a broken link.']
->>> f.clean('http://google.com/we-love-microsoft.html') # good domain, bad page
-Traceback (most recent call last):
-...
-ValidationError: [u'This URL appears to be a broken link.']
->>> f = URLField(verify_exists=True, required=False)
->>> f.clean('')
-u''
->>> f.clean('http://www.google.com') # This will fail if there's no Internet connection
-u'http://www.google.com'
-
-EmailField also access min_length and max_length parameters, for convenience.
->>> f = URLField(min_length=15, max_length=20)
->>> f.clean('http://f.com')
-Traceback (most recent call last):
-...
-ValidationError: [u'Ensure this value has at least 15 characters.']
->>> f.clean('http://example.com')
-u'http://example.com'
->>> f.clean('http://abcdefghijklmnopqrstuvwxyz.com')
-Traceback (most recent call last):
-...
-ValidationError: [u'Ensure this value has at most 20 characters.']
-
-# BooleanField ################################################################
-
->>> f = BooleanField()
->>> f.clean('')
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean(None)
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean(True)
-True
->>> f.clean(False)
-False
->>> f.clean(1)
-True
->>> f.clean(0)
-False
->>> f.clean('Django rocks')
-True
-
->>> f = BooleanField(required=False)
->>> f.clean('')
-False
->>> f.clean(None)
-False
->>> f.clean(True)
-True
->>> f.clean(False)
-False
->>> f.clean(1)
-True
->>> f.clean(0)
-False
->>> f.clean('Django rocks')
-True
-
-# ChoiceField #################################################################
-
->>> f = ChoiceField(choices=[('1', '1'), ('2', '2')])
->>> f.clean('')
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean(None)
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean(1)
-u'1'
->>> f.clean('1')
-u'1'
->>> f.clean('3')
-Traceback (most recent call last):
-...
-ValidationError: [u'Select a valid choice. That choice is not one of the available choices.']
-
->>> f = ChoiceField(choices=[('1', '1'), ('2', '2')], required=False)
->>> f.clean('')
-u''
->>> f.clean(None)
-u''
->>> f.clean(1)
-u'1'
->>> f.clean('1')
-u'1'
->>> f.clean('3')
-Traceback (most recent call last):
-...
-ValidationError: [u'Select a valid choice. That choice is not one of the available choices.']
-
->>> f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')])
->>> f.clean('J')
-u'J'
->>> f.clean('John')
-Traceback (most recent call last):
-...
-ValidationError: [u'Select a valid choice. That choice is not one of the available choices.']
-
-# NullBooleanField ############################################################
-
->>> f = NullBooleanField()
->>> f.clean('')
->>> f.clean(True)
-True
->>> f.clean(False)
-False
->>> f.clean(None)
->>> f.clean('1')
->>> f.clean('2')
->>> f.clean('3')
->>> f.clean('hello')
-
-# MultipleChoiceField #########################################################
-
->>> f = MultipleChoiceField(choices=[('1', '1'), ('2', '2')])
->>> f.clean('')
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean(None)
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean([1])
-[u'1']
->>> f.clean(['1'])
-[u'1']
->>> f.clean(['1', '2'])
-[u'1', u'2']
->>> f.clean([1, '2'])
-[u'1', u'2']
->>> f.clean((1, '2'))
-[u'1', u'2']
->>> f.clean('hello')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a list of values.']
->>> f.clean([])
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean(())
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean(['3'])
-Traceback (most recent call last):
-...
-ValidationError: [u'Select a valid choice. 3 is not one of the available choices.']
-
->>> f = MultipleChoiceField(choices=[('1', '1'), ('2', '2')], required=False)
->>> f.clean('')
-[]
->>> f.clean(None)
-[]
->>> f.clean([1])
-[u'1']
->>> f.clean(['1'])
-[u'1']
->>> f.clean(['1', '2'])
-[u'1', u'2']
->>> f.clean([1, '2'])
-[u'1', u'2']
->>> f.clean((1, '2'))
-[u'1', u'2']
->>> f.clean('hello')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a list of values.']
->>> f.clean([])
-[]
->>> f.clean(())
-[]
->>> f.clean(['3'])
-Traceback (most recent call last):
-...
-ValidationError: [u'Select a valid choice. 3 is not one of the available choices.']
-
-# ComboField ##################################################################
-
-ComboField takes a list of fields that should be used to validate a value,
-in that order.
->>> f = ComboField(fields=[CharField(max_length=20), EmailField()])
->>> f.clean('test@example.com')
-u'test@example.com'
->>> f.clean('longemailaddress@example.com')
-Traceback (most recent call last):
-...
-ValidationError: [u'Ensure this value has at most 20 characters.']
->>> f.clean('not an e-mail')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid e-mail address.']
->>> f.clean('')
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean(None)
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
-
->>> f = ComboField(fields=[CharField(max_length=20), EmailField()], required=False)
->>> f.clean('test@example.com')
-u'test@example.com'
->>> f.clean('longemailaddress@example.com')
-Traceback (most recent call last):
-...
-ValidationError: [u'Ensure this value has at most 20 characters.']
->>> f.clean('not an e-mail')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid e-mail address.']
->>> f.clean('')
-u''
->>> f.clean(None)
-u''
-
-# SplitDateTimeField ##########################################################
-
->>> f = SplitDateTimeField()
->>> f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)])
-datetime.datetime(2006, 1, 10, 7, 30)
->>> f.clean(None)
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean('')
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean('hello')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a list of values.']
->>> f.clean(['hello', 'there'])
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid date.', u'Enter a valid time.']
->>> f.clean(['2006-01-10', 'there'])
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid time.']
->>> f.clean(['hello', '07:30'])
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid date.']
-
->>> f = SplitDateTimeField(required=False)
->>> f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)])
-datetime.datetime(2006, 1, 10, 7, 30)
->>> f.clean(None)
->>> f.clean('')
->>> f.clean('hello')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a list of values.']
->>> f.clean(['hello', 'there'])
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid date.', u'Enter a valid time.']
->>> f.clean(['2006-01-10', 'there'])
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid time.']
->>> f.clean(['hello', '07:30'])
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a valid date.']
-
-#########
-# Forms #
-#########
-
-A Form is a collection of Fields. It knows how to validate a set of data and it
-knows how to render itself in a couple of default ways (e.g., an HTML table).
-You can pass it data in __init__(), as a dictionary.
-
-# Form ########################################################################
-
->>> class Person(Form):
-... first_name = CharField()
-... last_name = CharField()
-... birthday = DateField()
-
-Pass a dictionary to a Form's __init__().
->>> p = Person({'first_name': u'John', 'last_name': u'Lennon', 'birthday': u'1940-10-9'})
->>> p.is_bound
-True
->>> p.errors
-{}
->>> p.is_valid()
-True
->>> p.errors.as_ul()
-u''
->>> p.errors.as_text()
-u''
->>> p.clean_data
-{'first_name': u'John', 'last_name': u'Lennon', 'birthday': datetime.date(1940, 10, 9)}
->>> print p['first_name']
-<input type="text" name="first_name" value="John" id="id_first_name" />
->>> print p['last_name']
-<input type="text" name="last_name" value="Lennon" id="id_last_name" />
->>> print p['birthday']
-<input type="text" name="birthday" value="1940-10-9" id="id_birthday" />
->>> print p['nonexistentfield']
-Traceback (most recent call last):
-...
-KeyError: "Key 'nonexistentfield' not found in Form"
-
->>> for boundfield in p:
-... print boundfield
-<input type="text" name="first_name" value="John" id="id_first_name" />
-<input type="text" name="last_name" value="Lennon" id="id_last_name" />
-<input type="text" name="birthday" value="1940-10-9" id="id_birthday" />
->>> for boundfield in p:
-... print boundfield.label, boundfield.data
-First name John
-Last name Lennon
-Birthday 1940-10-9
->>> print p
-<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" value="John" id="id_first_name" /></td></tr>
-<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" value="Lennon" id="id_last_name" /></td></tr>
-<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></td></tr>
-
-Empty dictionaries are valid, too.
->>> p = Person({})
->>> p.is_bound
-True
->>> p.errors
-{'first_name': [u'This field is required.'], 'last_name': [u'This field is required.'], 'birthday': [u'This field is required.']}
->>> p.is_valid()
-False
->>> p.clean_data
-Traceback (most recent call last):
-...
-AttributeError: 'Person' object has no attribute 'clean_data'
->>> print p
-<tr><th><label for="id_first_name">First name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="first_name" id="id_first_name" /></td></tr>
-<tr><th><label for="id_last_name">Last name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="last_name" id="id_last_name" /></td></tr>
-<tr><th><label for="id_birthday">Birthday:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="birthday" id="id_birthday" /></td></tr>
->>> print p.as_table()
-<tr><th><label for="id_first_name">First name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="first_name" id="id_first_name" /></td></tr>
-<tr><th><label for="id_last_name">Last name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="last_name" id="id_last_name" /></td></tr>
-<tr><th><label for="id_birthday">Birthday:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="birthday" id="id_birthday" /></td></tr>
->>> print p.as_ul()
-<li><ul class="errorlist"><li>This field is required.</li></ul><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></li>
->>> print p.as_p()
-<p><ul class="errorlist"><li>This field is required.</li></ul></p>
-<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p>
-<p><ul class="errorlist"><li>This field is required.</li></ul></p>
-<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p>
-<p><ul class="errorlist"><li>This field is required.</li></ul></p>
-<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></p>
-
-If you don't pass any values to the Form's __init__(), or if you pass None,
-the Form will be considered unbound and won't do any validation. Form.errors
-will be an empty dictionary *but* Form.is_valid() will return False.
->>> p = Person()
->>> p.is_bound
-False
->>> p.errors
-{}
->>> p.is_valid()
-False
->>> p.clean_data
-Traceback (most recent call last):
-...
-AttributeError: 'Person' object has no attribute 'clean_data'
->>> print p
-<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" id="id_first_name" /></td></tr>
-<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr>
-<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /></td></tr>
->>> print p.as_table()
-<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" id="id_first_name" /></td></tr>
-<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr>
-<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /></td></tr>
->>> print p.as_ul()
-<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></li>
-<li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li>
-<li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></li>
->>> print p.as_p()
-<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p>
-<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p>
-<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /></p>
-
-Unicode values are handled properly.
->>> p = Person({'first_name': u'John', 'last_name': u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111', 'birthday': '1940-10-9'})
->>> p.as_table()
-u'<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" value="John" id="id_first_name" /></td></tr>\n<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></td></tr>\n<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></td></tr>'
->>> p.as_ul()
-u'<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" value="John" id="id_first_name" /></li>\n<li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></li>\n<li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></li>'
->>> p.as_p()
-u'<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" value="John" id="id_first_name" /></p>\n<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" /></p>\n<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" /></p>'
-
->>> p = Person({'last_name': u'Lennon'})
->>> p.errors
-{'first_name': [u'This field is required.'], 'birthday': [u'This field is required.']}
->>> p.is_valid()
-False
->>> p.errors.as_ul()
-u'<ul class="errorlist"><li>first_name<ul class="errorlist"><li>This field is required.</li></ul></li><li>birthday<ul class="errorlist"><li>This field is required.</li></ul></li></ul>'
->>> print p.errors.as_text()
-* first_name
- * This field is required.
-* birthday
- * This field is required.
->>> p.clean_data
-Traceback (most recent call last):
-...
-AttributeError: 'Person' object has no attribute 'clean_data'
->>> p['first_name'].errors
-[u'This field is required.']
->>> p['first_name'].errors.as_ul()
-u'<ul class="errorlist"><li>This field is required.</li></ul>'
->>> p['first_name'].errors.as_text()
-u'* This field is required.'
-
->>> p = Person()
->>> print p['first_name']
-<input type="text" name="first_name" id="id_first_name" />
->>> print p['last_name']
-<input type="text" name="last_name" id="id_last_name" />
->>> print p['birthday']
-<input type="text" name="birthday" id="id_birthday" />
-
-clean_data will always *only* contain a key for fields defined in the
-Form, even if you pass extra data when you define the Form. In this
-example, we pass a bunch of extra fields to the form constructor,
-but clean_data contains only the form's fields.
->>> data = {'first_name': u'John', 'last_name': u'Lennon', 'birthday': u'1940-10-9', 'extra1': 'hello', 'extra2': 'hello'}
->>> p = Person(data)
->>> p.is_valid()
-True
->>> p.clean_data
-{'first_name': u'John', 'last_name': u'Lennon', 'birthday': datetime.date(1940, 10, 9)}
-
-"auto_id" tells the Form to add an "id" attribute to each form element.
-If it's a string that contains '%s', Django will use that as a format string
-into which the field's name will be inserted. It will also put a <label> around
-the human-readable labels for a field.
->>> p = Person(auto_id='%s_id')
->>> print p.as_table()
-<tr><th><label for="first_name_id">First name:</label></th><td><input type="text" name="first_name" id="first_name_id" /></td></tr>
-<tr><th><label for="last_name_id">Last name:</label></th><td><input type="text" name="last_name" id="last_name_id" /></td></tr>
-<tr><th><label for="birthday_id">Birthday:</label></th><td><input type="text" name="birthday" id="birthday_id" /></td></tr>
->>> print p.as_ul()
-<li><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" /></li>
-<li><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" /></li>
-<li><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" /></li>
->>> print p.as_p()
-<p><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" /></p>
-<p><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" /></p>
-<p><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" /></p>
-
-If auto_id is any True value whose str() does not contain '%s', the "id"
-attribute will be the name of the field.
->>> p = Person(auto_id=True)
->>> print p.as_ul()
-<li><label for="first_name">First name:</label> <input type="text" name="first_name" id="first_name" /></li>
-<li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" /></li>
-<li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" /></li>
-
-If auto_id is any False value, an "id" attribute won't be output unless it
-was manually entered.
->>> p = Person(auto_id=False)
->>> print p.as_ul()
-<li>First name: <input type="text" name="first_name" /></li>
-<li>Last name: <input type="text" name="last_name" /></li>
-<li>Birthday: <input type="text" name="birthday" /></li>
-
-In this example, auto_id is False, but the "id" attribute for the "first_name"
-field is given. Also note that field gets a <label>, while the others don't.
->>> class PersonNew(Form):
-... first_name = CharField(widget=TextInput(attrs={'id': 'first_name_id'}))
-... last_name = CharField()
-... birthday = DateField()
->>> p = PersonNew(auto_id=False)
->>> print p.as_ul()
-<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" /></li>
-<li>Last name: <input type="text" name="last_name" /></li>
-<li>Birthday: <input type="text" name="birthday" /></li>
-
-If the "id" attribute is specified in the Form and auto_id is True, the "id"
-attribute in the Form gets precedence.
->>> p = PersonNew(auto_id=True)
->>> print p.as_ul()
-<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" /></li>
-<li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" /></li>
-<li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" /></li>
-
->>> class SignupForm(Form):
-... email = EmailField()
-... get_spam = BooleanField()
->>> f = SignupForm(auto_id=False)
->>> print f['email']
-<input type="text" name="email" />
->>> print f['get_spam']
-<input type="checkbox" name="get_spam" />
-
->>> f = SignupForm({'email': 'test@example.com', 'get_spam': True}, auto_id=False)
->>> print f['email']
-<input type="text" name="email" value="test@example.com" />
->>> print f['get_spam']
-<input checked="checked" type="checkbox" name="get_spam" />
-
-Any Field can have a Widget class passed to its constructor:
->>> class ContactForm(Form):
-... subject = CharField()
-... message = CharField(widget=Textarea)
->>> f = ContactForm(auto_id=False)
->>> print f['subject']
-<input type="text" name="subject" />
->>> print f['message']
-<textarea name="message"></textarea>
-
-as_textarea(), as_text() and as_hidden() are shortcuts for changing the output
-widget type:
->>> f['subject'].as_textarea()
-u'<textarea name="subject"></textarea>'
->>> f['message'].as_text()
-u'<input type="text" name="message" />'
->>> f['message'].as_hidden()
-u'<input type="hidden" name="message" />'
-
-The 'widget' parameter to a Field can also be an instance:
->>> class ContactForm(Form):
-... subject = CharField()
-... message = CharField(widget=Textarea(attrs={'rows': 80, 'cols': 20}))
->>> f = ContactForm(auto_id=False)
->>> print f['message']
-<textarea rows="80" cols="20" name="message"></textarea>
-
-Instance-level attrs are *not* carried over to as_textarea(), as_text() and
-as_hidden():
->>> f['message'].as_text()
-u'<input type="text" name="message" />'
->>> f = ContactForm({'subject': 'Hello', 'message': 'I love you.'}, auto_id=False)
->>> f['subject'].as_textarea()
-u'<textarea name="subject">Hello</textarea>'
->>> f['message'].as_text()
-u'<input type="text" name="message" value="I love you." />'
->>> f['message'].as_hidden()
-u'<input type="hidden" name="message" value="I love you." />'
-
-For a form with a <select>, use ChoiceField:
->>> class FrameworkForm(Form):
-... name = CharField()
-... language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')])
->>> f = FrameworkForm(auto_id=False)
->>> print f['language']
-<select name="language">
-<option value="P">Python</option>
-<option value="J">Java</option>
-</select>
->>> f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
->>> print f['language']
-<select name="language">
-<option value="P" selected="selected">Python</option>
-<option value="J">Java</option>
-</select>
-
-A subtlety: If one of the choices' value is the empty string and the form is
-unbound, then the <option> for the empty-string choice will get selected="selected".
->>> class FrameworkForm(Form):
-... name = CharField()
-... language = ChoiceField(choices=[('', '------'), ('P', 'Python'), ('J', 'Java')])
->>> f = FrameworkForm(auto_id=False)
->>> print f['language']
-<select name="language">
-<option value="" selected="selected">------</option>
-<option value="P">Python</option>
-<option value="J">Java</option>
-</select>
-
-You can specify widget attributes in the Widget constructor.
->>> class FrameworkForm(Form):
-... name = CharField()
-... language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(attrs={'class': 'foo'}))
->>> f = FrameworkForm(auto_id=False)
->>> print f['language']
-<select class="foo" name="language">
-<option value="P">Python</option>
-<option value="J">Java</option>
-</select>
->>> f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
->>> print f['language']
-<select class="foo" name="language">
-<option value="P" selected="selected">Python</option>
-<option value="J">Java</option>
-</select>
-
-When passing a custom widget instance to ChoiceField, note that setting
-'choices' on the widget is meaningless. The widget will use the choices
-defined on the Field, not the ones defined on the Widget.
->>> class FrameworkForm(Form):
-... name = CharField()
-... language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=Select(choices=[('R', 'Ruby'), ('P', 'Perl')], attrs={'class': 'foo'}))
->>> f = FrameworkForm(auto_id=False)
->>> print f['language']
-<select class="foo" name="language">
-<option value="P">Python</option>
-<option value="J">Java</option>
-</select>
->>> f = FrameworkForm({'name': 'Django', 'language': 'P'}, auto_id=False)
->>> print f['language']
-<select class="foo" name="language">
-<option value="P" selected="selected">Python</option>
-<option value="J">Java</option>
-</select>
-
-You can set a ChoiceField's choices after the fact.
->>> class FrameworkForm(Form):
-... name = CharField()
-... language = ChoiceField()
->>> f = FrameworkForm(auto_id=False)
->>> print f['language']
-<select name="language">
-</select>
->>> f.fields['language'].choices = [('P', 'Python'), ('J', 'Java')]
->>> print f['language']
-<select name="language">
-<option value="P">Python</option>
-<option value="J">Java</option>
-</select>
-
-Add widget=RadioSelect to use that widget with a ChoiceField.
->>> class FrameworkForm(Form):
-... name = CharField()
-... language = ChoiceField(choices=[('P', 'Python'), ('J', 'Java')], widget=RadioSelect)
->>> f = FrameworkForm(auto_id=False)
->>> print f['language']
-<ul>
-<li><label><input type="radio" name="language" value="P" /> Python</label></li>
-<li><label><input type="radio" name="language" value="J" /> Java</label></li>
-</ul>
->>> print f
-<tr><th>Name:</th><td><input type="text" name="name" /></td></tr>
-<tr><th>Language:</th><td><ul>
-<li><label><input type="radio" name="language" value="P" /> Python</label></li>
-<li><label><input type="radio" name="language" value="J" /> Java</label></li>
-</ul></td></tr>
->>> print f.as_ul()
-<li>Name: <input type="text" name="name" /></li>
-<li>Language: <ul>
-<li><label><input type="radio" name="language" value="P" /> Python</label></li>
-<li><label><input type="radio" name="language" value="J" /> Java</label></li>
-</ul></li>
-
-Regarding auto_id and <label>, RadioSelect is a special case. Each radio button
-gets a distinct ID, formed by appending an underscore plus the button's
-zero-based index.
->>> f = FrameworkForm(auto_id='id_%s')
->>> print f['language']
-<ul>
-<li><label><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
-<li><label><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
-</ul>
-
-When RadioSelect is used with auto_id, and the whole form is printed using
-either as_table() or as_ul(), the label for the RadioSelect will point to the
-ID of the *first* radio button.
->>> print f
-<tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" id="id_name" /></td></tr>
-<tr><th><label for="id_language_0">Language:</label></th><td><ul>
-<li><label><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
-<li><label><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
-</ul></td></tr>
->>> print f.as_ul()
-<li><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></li>
-<li><label for="id_language_0">Language:</label> <ul>
-<li><label><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
-<li><label><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
-</ul></li>
->>> print f.as_p()
-<p><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" /></p>
-<p><label for="id_language_0">Language:</label> <ul>
-<li><label><input type="radio" id="id_language_0" value="P" name="language" /> Python</label></li>
-<li><label><input type="radio" id="id_language_1" value="J" name="language" /> Java</label></li>
-</ul></p>
-
-MultipleChoiceField is a special case, as its data is required to be a list:
->>> class SongForm(Form):
-... name = CharField()
-... composers = MultipleChoiceField()
->>> f = SongForm(auto_id=False)
->>> print f['composers']
-<select multiple="multiple" name="composers">
-</select>
->>> class SongForm(Form):
-... name = CharField()
-... composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')])
->>> f = SongForm(auto_id=False)
->>> print f['composers']
-<select multiple="multiple" name="composers">
-<option value="J">John Lennon</option>
-<option value="P">Paul McCartney</option>
-</select>
->>> f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False)
->>> print f['name']
-<input type="text" name="name" value="Yesterday" />
->>> print f['composers']
-<select multiple="multiple" name="composers">
-<option value="J">John Lennon</option>
-<option value="P" selected="selected">Paul McCartney</option>
-</select>
-
-MultipleChoiceField rendered as_hidden() is a special case. Because it can
-have multiple values, its as_hidden() renders multiple <input type="hidden">
-tags.
->>> f = SongForm({'name': 'Yesterday', 'composers': ['P']}, auto_id=False)
->>> print f['composers'].as_hidden()
-<input type="hidden" name="composers" value="P" />
->>> f = SongForm({'name': 'From Me To You', 'composers': ['P', 'J']}, auto_id=False)
->>> print f['composers'].as_hidden()
-<input type="hidden" name="composers" value="P" />
-<input type="hidden" name="composers" value="J" />
-
-MultipleChoiceField can also be used with the CheckboxSelectMultiple widget.
->>> class SongForm(Form):
-... name = CharField()
-... composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
->>> f = SongForm(auto_id=False)
->>> print f['composers']
-<ul>
-<li><label><input type="checkbox" name="composers" value="J" /> John Lennon</label></li>
-<li><label><input type="checkbox" name="composers" value="P" /> Paul McCartney</label></li>
-</ul>
->>> f = SongForm({'composers': ['J']}, auto_id=False)
->>> print f['composers']
-<ul>
-<li><label><input checked="checked" type="checkbox" name="composers" value="J" /> John Lennon</label></li>
-<li><label><input type="checkbox" name="composers" value="P" /> Paul McCartney</label></li>
-</ul>
->>> f = SongForm({'composers': ['J', 'P']}, auto_id=False)
->>> print f['composers']
-<ul>
-<li><label><input checked="checked" type="checkbox" name="composers" value="J" /> John Lennon</label></li>
-<li><label><input checked="checked" type="checkbox" name="composers" value="P" /> Paul McCartney</label></li>
-</ul>
-
-Regarding auto_id, CheckboxSelectMultiple is a special case. Each checkbox
-gets a distinct ID, formed by appending an underscore plus the checkbox's
-zero-based index.
->>> f = SongForm(auto_id='%s_id')
->>> print f['composers']
-<ul>
-<li><label><input type="checkbox" name="composers" value="J" id="composers_id_0" /> John Lennon</label></li>
-<li><label><input type="checkbox" name="composers" value="P" id="composers_id_1" /> Paul McCartney</label></li>
-</ul>
-
-Data for a MultipleChoiceField should be a list. QueryDict and MultiValueDict
-conveniently work with this.
->>> data = {'name': 'Yesterday', 'composers': ['J', 'P']}
->>> f = SongForm(data)
->>> f.errors
-{}
->>> from django.http import QueryDict
->>> data = QueryDict('name=Yesterday&composers=J&composers=P')
->>> f = SongForm(data)
->>> f.errors
-{}
->>> from django.utils.datastructures import MultiValueDict
->>> data = MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P']))
->>> f = SongForm(data)
->>> f.errors
-{}
-
-The MultipleHiddenInput widget renders multiple values as hidden fields.
->>> class SongFormHidden(Form):
-... name = CharField()
-... composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=MultipleHiddenInput)
->>> f = SongFormHidden(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])), auto_id=False)
->>> print f.as_ul()
-<li>Name: <input type="text" name="name" value="Yesterday" /><input type="hidden" name="composers" value="J" />
-<input type="hidden" name="composers" value="P" /></li>
-
-When using CheckboxSelectMultiple, the framework expects a list of input and
-returns a list of input.
->>> f = SongForm({'name': 'Yesterday'}, auto_id=False)
->>> f.errors
-{'composers': [u'This field is required.']}
->>> f = SongForm({'name': 'Yesterday', 'composers': ['J']}, auto_id=False)
->>> f.errors
-{}
->>> f.clean_data
-{'composers': [u'J'], 'name': u'Yesterday'}
->>> f = SongForm({'name': 'Yesterday', 'composers': ['J', 'P']}, auto_id=False)
->>> f.errors
-{}
->>> f.clean_data
-{'composers': [u'J', u'P'], 'name': u'Yesterday'}
-
-Validation errors are HTML-escaped when output as HTML.
->>> class EscapingForm(Form):
-... special_name = CharField()
-... def clean_special_name(self):
-... raise ValidationError("Something's wrong with '%s'" % self.clean_data['special_name'])
-
->>> f = EscapingForm({'special_name': "Nothing to escape"}, auto_id=False)
->>> print f
-<tr><th>Special name:</th><td><ul class="errorlist"><li>Something's wrong with 'Nothing to escape'</li></ul><input type="text" name="special_name" value="Nothing to escape" /></td></tr>
->>> f = EscapingForm({'special_name': "Should escape < & > and <script>alert('xss')</script>"}, auto_id=False)
->>> print f
-<tr><th>Special name:</th><td><ul class="errorlist"><li>Something's wrong with 'Should escape < & > and <script>alert('xss')</script>'</li></ul><input type="text" name="special_name" value="Should escape < & > and <script>alert('xss')</script>" /></td></tr>
-
-# Validating multiple fields in relation to another ###########################
-
-There are a couple of ways to do multiple-field validation. If you want the
-validation message to be associated with a particular field, implement the
-clean_XXX() method on the Form, where XXX is the field name. As in
-Field.clean(), the clean_XXX() method should return the cleaned value. In the
-clean_XXX() method, you have access to self.clean_data, which is a dictionary
-of all the data that has been cleaned *so far*, in order by the fields,
-including the current field (e.g., the field XXX if you're in clean_XXX()).
->>> class UserRegistration(Form):
-... username = CharField(max_length=10)
-... password1 = CharField(widget=PasswordInput)
-... password2 = CharField(widget=PasswordInput)
-... def clean_password2(self):
-... if self.clean_data.get('password1') and self.clean_data.get('password2') and self.clean_data['password1'] != self.clean_data['password2']:
-... raise ValidationError(u'Please make sure your passwords match.')
-... return self.clean_data['password2']
->>> f = UserRegistration(auto_id=False)
->>> f.errors
-{}
->>> f = UserRegistration({}, auto_id=False)
->>> f.errors
-{'username': [u'This field is required.'], 'password1': [u'This field is required.'], 'password2': [u'This field is required.']}
->>> f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
->>> f.errors
-{'password2': [u'Please make sure your passwords match.']}
->>> f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False)
->>> f.errors
-{}
->>> f.clean_data
-{'username': u'adrian', 'password1': u'foo', 'password2': u'foo'}
-
-Another way of doing multiple-field validation is by implementing the
-Form's clean() method. If you do this, any ValidationError raised by that
-method will not be associated with a particular field; it will have a
-special-case association with the field named '__all__'.
-Note that in Form.clean(), you have access to self.clean_data, a dictionary of
-all the fields/values that have *not* raised a ValidationError. Also note
-Form.clean() is required to return a dictionary of all clean data.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10)
-... password1 = CharField(widget=PasswordInput)
-... password2 = CharField(widget=PasswordInput)
-... def clean(self):
-... if self.clean_data.get('password1') and self.clean_data.get('password2') and self.clean_data['password1'] != self.clean_data['password2']:
-... raise ValidationError(u'Please make sure your passwords match.')
-... return self.clean_data
->>> f = UserRegistration(auto_id=False)
->>> f.errors
-{}
->>> f = UserRegistration({}, auto_id=False)
->>> print f.as_table()
-<tr><th>Username:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="username" maxlength="10" /></td></tr>
-<tr><th>Password1:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="password" name="password1" /></td></tr>
-<tr><th>Password2:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="password" name="password2" /></td></tr>
->>> f.errors
-{'username': [u'This field is required.'], 'password1': [u'This field is required.'], 'password2': [u'This field is required.']}
->>> f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
->>> f.errors
-{'__all__': [u'Please make sure your passwords match.']}
->>> print f.as_table()
-<tr><td colspan="2"><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></td></tr>
-<tr><th>Username:</th><td><input type="text" name="username" value="adrian" maxlength="10" /></td></tr>
-<tr><th>Password1:</th><td><input type="password" name="password1" value="foo" /></td></tr>
-<tr><th>Password2:</th><td><input type="password" name="password2" value="bar" /></td></tr>
->>> print f.as_ul()
-<li><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></li>
-<li>Username: <input type="text" name="username" value="adrian" maxlength="10" /></li>
-<li>Password1: <input type="password" name="password1" value="foo" /></li>
-<li>Password2: <input type="password" name="password2" value="bar" /></li>
->>> f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'foo'}, auto_id=False)
->>> f.errors
-{}
->>> f.clean_data
-{'username': u'adrian', 'password1': u'foo', 'password2': u'foo'}
-
-# Dynamic construction ########################################################
-
-It's possible to construct a Form dynamically by adding to the self.fields
-dictionary in __init__(). Don't forget to call Form.__init__() within the
-subclass' __init__().
->>> class Person(Form):
-... first_name = CharField()
-... last_name = CharField()
-... def __init__(self, *args, **kwargs):
-... super(Person, self).__init__(*args, **kwargs)
-... self.fields['birthday'] = DateField()
->>> p = Person(auto_id=False)
->>> print p
-<tr><th>First name:</th><td><input type="text" name="first_name" /></td></tr>
-<tr><th>Last name:</th><td><input type="text" name="last_name" /></td></tr>
-<tr><th>Birthday:</th><td><input type="text" name="birthday" /></td></tr>
-
-Instances of a dynamic Form do not persist fields from one Form instance to
-the next.
->>> class MyForm(Form):
-... def __init__(self, data=None, auto_id=False, field_list=[]):
-... Form.__init__(self, data, auto_id)
-... for field in field_list:
-... self.fields[field[0]] = field[1]
->>> field_list = [('field1', CharField()), ('field2', CharField())]
->>> my_form = MyForm(field_list=field_list)
->>> print my_form
-<tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr>
-<tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr>
->>> field_list = [('field3', CharField()), ('field4', CharField())]
->>> my_form = MyForm(field_list=field_list)
->>> print my_form
-<tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr>
-<tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr>
-
->>> class MyForm(Form):
-... default_field_1 = CharField()
-... default_field_2 = CharField()
-... def __init__(self, data=None, auto_id=False, field_list=[]):
-... Form.__init__(self, data, auto_id)
-... for field in field_list:
-... self.fields[field[0]] = field[1]
->>> field_list = [('field1', CharField()), ('field2', CharField())]
->>> my_form = MyForm(field_list=field_list)
->>> print my_form
-<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" /></td></tr>
-<tr><th>Default field 2:</th><td><input type="text" name="default_field_2" /></td></tr>
-<tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr>
-<tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr>
->>> field_list = [('field3', CharField()), ('field4', CharField())]
->>> my_form = MyForm(field_list=field_list)
->>> print my_form
-<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" /></td></tr>
-<tr><th>Default field 2:</th><td><input type="text" name="default_field_2" /></td></tr>
-<tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr>
-<tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr>
-
-Similarly, changes to field attributes do not persist from one Form instance
-to the next.
->>> class Person(Form):
-... first_name = CharField(required=False)
-... last_name = CharField(required=False)
-... def __init__(self, names_required=False, *args, **kwargs):
-... super(Person, self).__init__(*args, **kwargs)
-... if names_required:
-... self.fields['first_name'].required = True
-... self.fields['last_name'].required = True
->>> f = Person(names_required=False)
->>> f['first_name'].field.required, f['last_name'].field.required
-(False, False)
->>> f = Person(names_required=True)
->>> f['first_name'].field.required, f['last_name'].field.required
-(True, True)
->>> f = Person(names_required=False)
->>> f['first_name'].field.required, f['last_name'].field.required
-(False, False)
->>> class Person(Form):
-... first_name = CharField(max_length=30)
-... last_name = CharField(max_length=30)
-... def __init__(self, name_max_length=None, *args, **kwargs):
-... super(Person, self).__init__(*args, **kwargs)
-... if name_max_length:
-... self.fields['first_name'].max_length = name_max_length
-... self.fields['last_name'].max_length = name_max_length
->>> f = Person(name_max_length=None)
->>> f['first_name'].field.max_length, f['last_name'].field.max_length
-(30, 30)
->>> f = Person(name_max_length=20)
->>> f['first_name'].field.max_length, f['last_name'].field.max_length
-(20, 20)
->>> f = Person(name_max_length=None)
->>> f['first_name'].field.max_length, f['last_name'].field.max_length
-(30, 30)
-
-HiddenInput widgets are displayed differently in the as_table(), as_ul()
-and as_p() output of a Form -- their verbose names are not displayed, and a
-separate row is not displayed. They're displayed in the last row of the
-form, directly after that row's form element.
->>> class Person(Form):
-... first_name = CharField()
-... last_name = CharField()
-... hidden_text = CharField(widget=HiddenInput)
-... birthday = DateField()
->>> p = Person(auto_id=False)
->>> print p
-<tr><th>First name:</th><td><input type="text" name="first_name" /></td></tr>
-<tr><th>Last name:</th><td><input type="text" name="last_name" /></td></tr>
-<tr><th>Birthday:</th><td><input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></td></tr>
->>> print p.as_ul()
-<li>First name: <input type="text" name="first_name" /></li>
-<li>Last name: <input type="text" name="last_name" /></li>
-<li>Birthday: <input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></li>
->>> print p.as_p()
-<p>First name: <input type="text" name="first_name" /></p>
-<p>Last name: <input type="text" name="last_name" /></p>
-<p>Birthday: <input type="text" name="birthday" /><input type="hidden" name="hidden_text" /></p>
-
-With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label.
->>> p = Person(auto_id='id_%s')
->>> print p
-<tr><th><label for="id_first_name">First name:</label></th><td><input type="text" name="first_name" id="id_first_name" /></td></tr>
-<tr><th><label for="id_last_name">Last name:</label></th><td><input type="text" name="last_name" id="id_last_name" /></td></tr>
-<tr><th><label for="id_birthday">Birthday:</label></th><td><input type="text" name="birthday" id="id_birthday" /><input type="hidden" name="hidden_text" id="id_hidden_text" /></td></tr>
->>> print p.as_ul()
-<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></li>
-<li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></li>
-<li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /><input type="hidden" name="hidden_text" id="id_hidden_text" /></li>
->>> print p.as_p()
-<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" /></p>
-<p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" /></p>
-<p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" /><input type="hidden" name="hidden_text" id="id_hidden_text" /></p>
-
-If a field with a HiddenInput has errors, the as_table() and as_ul() output
-will include the error message(s) with the text "(Hidden field [fieldname]) "
-prepended. This message is displayed at the top of the output, regardless of
-its field's order in the form.
->>> p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'}, auto_id=False)
->>> print p
-<tr><td colspan="2"><ul class="errorlist"><li>(Hidden field hidden_text) This field is required.</li></ul></td></tr>
-<tr><th>First name:</th><td><input type="text" name="first_name" value="John" /></td></tr>
-<tr><th>Last name:</th><td><input type="text" name="last_name" value="Lennon" /></td></tr>
-<tr><th>Birthday:</th><td><input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></td></tr>
->>> print p.as_ul()
-<li><ul class="errorlist"><li>(Hidden field hidden_text) This field is required.</li></ul></li>
-<li>First name: <input type="text" name="first_name" value="John" /></li>
-<li>Last name: <input type="text" name="last_name" value="Lennon" /></li>
-<li>Birthday: <input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></li>
->>> print p.as_p()
-<p><ul class="errorlist"><li>(Hidden field hidden_text) This field is required.</li></ul></p>
-<p>First name: <input type="text" name="first_name" value="John" /></p>
-<p>Last name: <input type="text" name="last_name" value="Lennon" /></p>
-<p>Birthday: <input type="text" name="birthday" value="1940-10-9" /><input type="hidden" name="hidden_text" /></p>
-
-A corner case: It's possible for a form to have only HiddenInputs.
->>> class TestForm(Form):
-... foo = CharField(widget=HiddenInput)
-... bar = CharField(widget=HiddenInput)
->>> p = TestForm(auto_id=False)
->>> print p.as_table()
-<input type="hidden" name="foo" /><input type="hidden" name="bar" />
->>> print p.as_ul()
-<input type="hidden" name="foo" /><input type="hidden" name="bar" />
->>> print p.as_p()
-<input type="hidden" name="foo" /><input type="hidden" name="bar" />
-
-A Form's fields are displayed in the same order in which they were defined.
->>> class TestForm(Form):
-... field1 = CharField()
-... field2 = CharField()
-... field3 = CharField()
-... field4 = CharField()
-... field5 = CharField()
-... field6 = CharField()
-... field7 = CharField()
-... field8 = CharField()
-... field9 = CharField()
-... field10 = CharField()
-... field11 = CharField()
-... field12 = CharField()
-... field13 = CharField()
-... field14 = CharField()
->>> p = TestForm(auto_id=False)
->>> print p
-<tr><th>Field1:</th><td><input type="text" name="field1" /></td></tr>
-<tr><th>Field2:</th><td><input type="text" name="field2" /></td></tr>
-<tr><th>Field3:</th><td><input type="text" name="field3" /></td></tr>
-<tr><th>Field4:</th><td><input type="text" name="field4" /></td></tr>
-<tr><th>Field5:</th><td><input type="text" name="field5" /></td></tr>
-<tr><th>Field6:</th><td><input type="text" name="field6" /></td></tr>
-<tr><th>Field7:</th><td><input type="text" name="field7" /></td></tr>
-<tr><th>Field8:</th><td><input type="text" name="field8" /></td></tr>
-<tr><th>Field9:</th><td><input type="text" name="field9" /></td></tr>
-<tr><th>Field10:</th><td><input type="text" name="field10" /></td></tr>
-<tr><th>Field11:</th><td><input type="text" name="field11" /></td></tr>
-<tr><th>Field12:</th><td><input type="text" name="field12" /></td></tr>
-<tr><th>Field13:</th><td><input type="text" name="field13" /></td></tr>
-<tr><th>Field14:</th><td><input type="text" name="field14" /></td></tr>
-
-Some Field classes have an effect on the HTML attributes of their associated
-Widget. If you set max_length in a CharField and its associated widget is
-either a TextInput or PasswordInput, then the widget's rendered HTML will
-include the "maxlength" attribute.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10) # uses TextInput by default
-... password = CharField(max_length=10, widget=PasswordInput)
-... realname = CharField(max_length=10, widget=TextInput) # redundantly define widget, just to test
-... address = CharField() # no max_length defined here
->>> p = UserRegistration(auto_id=False)
->>> print p.as_ul()
-<li>Username: <input type="text" name="username" maxlength="10" /></li>
-<li>Password: <input type="password" name="password" maxlength="10" /></li>
-<li>Realname: <input type="text" name="realname" maxlength="10" /></li>
-<li>Address: <input type="text" name="address" /></li>
-
-If you specify a custom "attrs" that includes the "maxlength" attribute,
-the Field's max_length attribute will override whatever "maxlength" you specify
-in "attrs".
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, widget=TextInput(attrs={'maxlength': 20}))
-... password = CharField(max_length=10, widget=PasswordInput)
->>> p = UserRegistration(auto_id=False)
->>> print p.as_ul()
-<li>Username: <input type="text" name="username" maxlength="10" /></li>
-<li>Password: <input type="password" name="password" maxlength="10" /></li>
-
-# Specifying labels ###########################################################
-
-You can specify the label for a field by using the 'label' argument to a Field
-class. If you don't specify 'label', Django will use the field name with
-underscores converted to spaces, and the initial letter capitalized.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, label='Your username')
-... password1 = CharField(widget=PasswordInput)
-... password2 = CharField(widget=PasswordInput, label='Password (again)')
->>> p = UserRegistration(auto_id=False)
->>> print p.as_ul()
-<li>Your username: <input type="text" name="username" maxlength="10" /></li>
-<li>Password1: <input type="password" name="password1" /></li>
-<li>Password (again): <input type="password" name="password2" /></li>
-
-A label can be a Unicode object or a bytestring with special characters.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, label='ŠĐĆŽćžšđ')
-... password = CharField(widget=PasswordInput, label=u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111')
->>> p = UserRegistration(auto_id=False)
->>> p.as_ul()
-u'<li>\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111: <input type="text" name="username" maxlength="10" /></li>\n<li>\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111: <input type="password" name="password" /></li>'
-
-If a label is set to the empty string for a field, that field won't get a label.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, label='')
-... password = CharField(widget=PasswordInput)
->>> p = UserRegistration(auto_id=False)
->>> print p.as_ul()
-<li> <input type="text" name="username" maxlength="10" /></li>
-<li>Password: <input type="password" name="password" /></li>
->>> p = UserRegistration(auto_id='id_%s')
->>> print p.as_ul()
-<li> <input id="id_username" type="text" name="username" maxlength="10" /></li>
-<li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></li>
-
-If label is None, Django will auto-create the label from the field name. This
-is default behavior.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, label=None)
-... password = CharField(widget=PasswordInput)
->>> p = UserRegistration(auto_id=False)
->>> print p.as_ul()
-<li>Username: <input type="text" name="username" maxlength="10" /></li>
-<li>Password: <input type="password" name="password" /></li>
->>> p = UserRegistration(auto_id='id_%s')
->>> print p.as_ul()
-<li><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" /></li>
-<li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" /></li>
-
-# Initial data ################################################################
-
-You can specify initial data for a field by using the 'initial' argument to a
-Field class. This initial data is displayed when a Form is rendered with *no*
-data. It is not displayed when a Form is rendered with any data (including an
-empty dictionary). Also, the initial value is *not* used if data for a
-particular required field isn't provided.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, initial='django')
-... password = CharField(widget=PasswordInput)
-
-Here, we're not submitting any data, so the initial value will be displayed.
->>> p = UserRegistration(auto_id=False)
->>> print p.as_ul()
-<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
-<li>Password: <input type="password" name="password" /></li>
-
-Here, we're submitting data, so the initial value will *not* be displayed.
->>> p = UserRegistration({}, auto_id=False)
->>> print p.as_ul()
-<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>
->>> p = UserRegistration({'username': u''}, auto_id=False)
->>> print p.as_ul()
-<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>
->>> p = UserRegistration({'username': u'foo'}, auto_id=False)
->>> print p.as_ul()
-<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>
-
-An 'initial' value is *not* used as a fallback if data is not provided. In this
-example, we don't provide a value for 'username', and the form raises a
-validation error rather than using the initial value for 'username'.
->>> p = UserRegistration({'password': 'secret'})
->>> p.errors
-{'username': [u'This field is required.']}
->>> p.is_valid()
-False
-
-# Dynamic initial data ########################################################
-
-The previous technique dealt with "hard-coded" initial data, but it's also
-possible to specify initial data after you've already created the Form class
-(i.e., at runtime). Use the 'initial' parameter to the Form constructor. This
-should be a dictionary containing initial values for one or more fields in the
-form, keyed by field name.
-
->>> class UserRegistration(Form):
-... username = CharField(max_length=10)
-... password = CharField(widget=PasswordInput)
-
-Here, we're not submitting any data, so the initial value will be displayed.
->>> p = UserRegistration(initial={'username': 'django'}, auto_id=False)
->>> print p.as_ul()
-<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
-<li>Password: <input type="password" name="password" /></li>
->>> p = UserRegistration(initial={'username': 'stephane'}, auto_id=False)
->>> print p.as_ul()
-<li>Username: <input type="text" name="username" value="stephane" maxlength="10" /></li>
-<li>Password: <input type="password" name="password" /></li>
-
-The 'initial' parameter is meaningless if you pass data.
->>> p = UserRegistration({}, initial={'username': 'django'}, auto_id=False)
->>> print p.as_ul()
-<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>
->>> p = UserRegistration({'username': u''}, initial={'username': 'django'}, auto_id=False)
->>> print p.as_ul()
-<li><ul class="errorlist"><li>This field is required.</li></ul>Username: <input type="text" name="username" maxlength="10" /></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>
->>> p = UserRegistration({'username': u'foo'}, initial={'username': 'django'}, auto_id=False)
->>> print p.as_ul()
-<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>
-
-A dynamic 'initial' value is *not* used as a fallback if data is not provided.
-In this example, we don't provide a value for 'username', and the form raises a
-validation error rather than using the initial value for 'username'.
->>> p = UserRegistration({'password': 'secret'}, initial={'username': 'django'})
->>> p.errors
-{'username': [u'This field is required.']}
->>> p.is_valid()
-False
-
-If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(),
-then the latter will get precedence.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, initial='django')
-... password = CharField(widget=PasswordInput)
->>> p = UserRegistration(initial={'username': 'babik'}, auto_id=False)
->>> print p.as_ul()
-<li>Username: <input type="text" name="username" value="babik" maxlength="10" /></li>
-<li>Password: <input type="password" name="password" /></li>
-
-# Help text ###################################################################
-
-You can specify descriptive text for a field by using the 'help_text' argument
-to a Field class. This help text is displayed when a Form is rendered.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, help_text='e.g., user@example.com')
-... password = CharField(widget=PasswordInput, help_text='Choose wisely.')
->>> p = UserRegistration(auto_id=False)
->>> print p.as_ul()
-<li>Username: <input type="text" name="username" maxlength="10" /> e.g., user@example.com</li>
-<li>Password: <input type="password" name="password" /> Choose wisely.</li>
->>> print p.as_p()
-<p>Username: <input type="text" name="username" maxlength="10" /> e.g., user@example.com</p>
-<p>Password: <input type="password" name="password" /> Choose wisely.</p>
->>> print p.as_table()
-<tr><th>Username:</th><td><input type="text" name="username" maxlength="10" /><br />e.g., user@example.com</td></tr>
-<tr><th>Password:</th><td><input type="password" name="password" /><br />Choose wisely.</td></tr>
-
-The help text is displayed whether or not data is provided for the form.
->>> p = UserRegistration({'username': u'foo'}, auto_id=False)
->>> print p.as_ul()
-<li>Username: <input type="text" name="username" value="foo" maxlength="10" /> e.g., user@example.com</li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /> Choose wisely.</li>
-
-help_text is not displayed for hidden fields. It can be used for documentation
-purposes, though.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, help_text='e.g., user@example.com')
-... password = CharField(widget=PasswordInput)
-... next = CharField(widget=HiddenInput, initial='/', help_text='Redirect destination')
->>> p = UserRegistration(auto_id=False)
->>> print p.as_ul()
-<li>Username: <input type="text" name="username" maxlength="10" /> e.g., user@example.com</li>
-<li>Password: <input type="password" name="password" /><input type="hidden" name="next" value="/" /></li>
-
-Help text can include arbitrary Unicode characters.
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, help_text='ŠĐĆŽćžšđ')
->>> p = UserRegistration(auto_id=False)
->>> p.as_ul()
-u'<li>Username: <input type="text" name="username" maxlength="10" /> \u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111</li>'
-
-# Subclassing forms ###########################################################
-
-You can subclass a Form to add fields. The resulting form subclass will have
-all of the fields of the parent Form, plus whichever fields you define in the
-subclass.
->>> class Person(Form):
-... first_name = CharField()
-... last_name = CharField()
-... birthday = DateField()
->>> class Musician(Person):
-... instrument = CharField()
->>> p = Person(auto_id=False)
->>> print p.as_ul()
-<li>First name: <input type="text" name="first_name" /></li>
-<li>Last name: <input type="text" name="last_name" /></li>
-<li>Birthday: <input type="text" name="birthday" /></li>
->>> m = Musician(auto_id=False)
->>> print m.as_ul()
-<li>First name: <input type="text" name="first_name" /></li>
-<li>Last name: <input type="text" name="last_name" /></li>
-<li>Birthday: <input type="text" name="birthday" /></li>
-<li>Instrument: <input type="text" name="instrument" /></li>
-
-Yes, you can subclass multiple forms. The fields are added in the order in
-which the parent classes are listed.
->>> class Person(Form):
-... first_name = CharField()
-... last_name = CharField()
-... birthday = DateField()
->>> class Instrument(Form):
-... instrument = CharField()
->>> class Beatle(Person, Instrument):
-... haircut_type = CharField()
->>> b = Beatle(auto_id=False)
->>> print b.as_ul()
-<li>First name: <input type="text" name="first_name" /></li>
-<li>Last name: <input type="text" name="last_name" /></li>
-<li>Birthday: <input type="text" name="birthday" /></li>
-<li>Instrument: <input type="text" name="instrument" /></li>
-<li>Haircut type: <input type="text" name="haircut_type" /></li>
-
-# Forms with prefixes #########################################################
-
-Sometimes it's necessary to have multiple forms display on the same HTML page,
-or multiple copies of the same form. We can accomplish this with form prefixes.
-Pass the keyword argument 'prefix' to the Form constructor to use this feature.
-This value will be prepended to each HTML form field name. One way to think
-about this is "namespaces for HTML forms". Notice that in the data argument,
-each field's key has the prefix, in this case 'person1', prepended to the
-actual field name.
->>> class Person(Form):
-... first_name = CharField()
-... last_name = CharField()
-... birthday = DateField()
->>> data = {
-... 'person1-first_name': u'John',
-... 'person1-last_name': u'Lennon',
-... 'person1-birthday': u'1940-10-9'
-... }
->>> p = Person(data, prefix='person1')
->>> print p.as_ul()
-<li><label for="id_person1-first_name">First name:</label> <input type="text" name="person1-first_name" value="John" id="id_person1-first_name" /></li>
-<li><label for="id_person1-last_name">Last name:</label> <input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" /></li>
-<li><label for="id_person1-birthday">Birthday:</label> <input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" /></li>
->>> print p['first_name']
-<input type="text" name="person1-first_name" value="John" id="id_person1-first_name" />
->>> print p['last_name']
-<input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" />
->>> print p['birthday']
-<input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" />
->>> p.errors
-{}
->>> p.is_valid()
-True
->>> p.clean_data
-{'first_name': u'John', 'last_name': u'Lennon', 'birthday': datetime.date(1940, 10, 9)}
-
-Let's try submitting some bad data to make sure form.errors and field.errors
-work as expected.
->>> data = {
-... 'person1-first_name': u'',
-... 'person1-last_name': u'',
-... 'person1-birthday': u''
-... }
->>> p = Person(data, prefix='person1')
->>> p.errors
-{'first_name': [u'This field is required.'], 'last_name': [u'This field is required.'], 'birthday': [u'This field is required.']}
->>> p['first_name'].errors
-[u'This field is required.']
->>> p['person1-first_name'].errors
-Traceback (most recent call last):
-...
-KeyError: "Key 'person1-first_name' not found in Form"
-
-In this example, the data doesn't have a prefix, but the form requires it, so
-the form doesn't "see" the fields.
->>> data = {
-... 'first_name': u'John',
-... 'last_name': u'Lennon',
-... 'birthday': u'1940-10-9'
-... }
->>> p = Person(data, prefix='person1')
->>> p.errors
-{'first_name': [u'This field is required.'], 'last_name': [u'This field is required.'], 'birthday': [u'This field is required.']}
-
-With prefixes, a single data dictionary can hold data for multiple instances
-of the same form.
->>> data = {
-... 'person1-first_name': u'John',
-... 'person1-last_name': u'Lennon',
-... 'person1-birthday': u'1940-10-9',
-... 'person2-first_name': u'Jim',
-... 'person2-last_name': u'Morrison',
-... 'person2-birthday': u'1943-12-8'
-... }
->>> p1 = Person(data, prefix='person1')
->>> p1.is_valid()
-True
->>> p1.clean_data
-{'first_name': u'John', 'last_name': u'Lennon', 'birthday': datetime.date(1940, 10, 9)}
->>> p2 = Person(data, prefix='person2')
->>> p2.is_valid()
-True
->>> p2.clean_data
-{'first_name': u'Jim', 'last_name': u'Morrison', 'birthday': datetime.date(1943, 12, 8)}
-
-By default, forms append a hyphen between the prefix and the field name, but a
-form can alter that behavior by implementing the add_prefix() method. This
-method takes a field name and returns the prefixed field, according to
-self.prefix.
->>> class Person(Form):
-... first_name = CharField()
-... last_name = CharField()
-... birthday = DateField()
-... def add_prefix(self, field_name):
-... return self.prefix and '%s-prefix-%s' % (self.prefix, field_name) or field_name
->>> p = Person(prefix='foo')
->>> print p.as_ul()
-<li><label for="id_foo-prefix-first_name">First name:</label> <input type="text" name="foo-prefix-first_name" id="id_foo-prefix-first_name" /></li>
-<li><label for="id_foo-prefix-last_name">Last name:</label> <input type="text" name="foo-prefix-last_name" id="id_foo-prefix-last_name" /></li>
-<li><label for="id_foo-prefix-birthday">Birthday:</label> <input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday" /></li>
->>> data = {
-... 'foo-prefix-first_name': u'John',
-... 'foo-prefix-last_name': u'Lennon',
-... 'foo-prefix-birthday': u'1940-10-9'
-... }
->>> p = Person(data, prefix='foo')
->>> p.is_valid()
-True
->>> p.clean_data
-{'first_name': u'John', 'last_name': u'Lennon', 'birthday': datetime.date(1940, 10, 9)}
-
-# Forms with NullBooleanFields ################################################
-
-NullBooleanField is a bit of a special case because its presentation (widget)
-is different than its data. This is handled transparently, though.
-
->>> class Person(Form):
-... name = CharField()
-... is_cool = NullBooleanField()
->>> p = Person({'name': u'Joe'}, auto_id=False)
->>> print p['is_cool']
-<select name="is_cool">
-<option value="1" selected="selected">Unknown</option>
-<option value="2">Yes</option>
-<option value="3">No</option>
-</select>
->>> p = Person({'name': u'Joe', 'is_cool': u'1'}, auto_id=False)
->>> print p['is_cool']
-<select name="is_cool">
-<option value="1" selected="selected">Unknown</option>
-<option value="2">Yes</option>
-<option value="3">No</option>
-</select>
->>> p = Person({'name': u'Joe', 'is_cool': u'2'}, auto_id=False)
->>> print p['is_cool']
-<select name="is_cool">
-<option value="1">Unknown</option>
-<option value="2" selected="selected">Yes</option>
-<option value="3">No</option>
-</select>
->>> p = Person({'name': u'Joe', 'is_cool': u'3'}, auto_id=False)
->>> print p['is_cool']
-<select name="is_cool">
-<option value="1">Unknown</option>
-<option value="2">Yes</option>
-<option value="3" selected="selected">No</option>
-</select>
->>> p = Person({'name': u'Joe', 'is_cool': True}, auto_id=False)
->>> print p['is_cool']
-<select name="is_cool">
-<option value="1">Unknown</option>
-<option value="2" selected="selected">Yes</option>
-<option value="3">No</option>
-</select>
->>> p = Person({'name': u'Joe', 'is_cool': False}, auto_id=False)
->>> print p['is_cool']
-<select name="is_cool">
-<option value="1">Unknown</option>
-<option value="2">Yes</option>
-<option value="3" selected="selected">No</option>
-</select>
-
-# Basic form processing in a view #############################################
-
->>> from django.template import Template, Context
->>> class UserRegistration(Form):
-... username = CharField(max_length=10)
-... password1 = CharField(widget=PasswordInput)
-... password2 = CharField(widget=PasswordInput)
-... def clean(self):
-... if self.clean_data.get('password1') and self.clean_data.get('password2') and self.clean_data['password1'] != self.clean_data['password2']:
-... raise ValidationError(u'Please make sure your passwords match.')
-... return self.clean_data
->>> def my_function(method, post_data):
-... if method == 'POST':
-... form = UserRegistration(post_data, auto_id=False)
-... else:
-... form = UserRegistration(auto_id=False)
-... if form.is_valid():
-... return 'VALID: %r' % form.clean_data
-... t = Template('<form action="" method="post">\n<table>\n{{ form }}\n</table>\n<input type="submit" />\n</form>')
-... return t.render(Context({'form': form}))
-
-Case 1: GET (an empty form, with no errors).
->>> print my_function('GET', {})
-<form action="" method="post">
-<table>
-<tr><th>Username:</th><td><input type="text" name="username" maxlength="10" /></td></tr>
-<tr><th>Password1:</th><td><input type="password" name="password1" /></td></tr>
-<tr><th>Password2:</th><td><input type="password" name="password2" /></td></tr>
-</table>
-<input type="submit" />
-</form>
-
-Case 2: POST with erroneous data (a redisplayed form, with errors).
->>> print my_function('POST', {'username': 'this-is-a-long-username', 'password1': 'foo', 'password2': 'bar'})
-<form action="" method="post">
-<table>
-<tr><td colspan="2"><ul class="errorlist"><li>Please make sure your passwords match.</li></ul></td></tr>
-<tr><th>Username:</th><td><ul class="errorlist"><li>Ensure this value has at most 10 characters.</li></ul><input type="text" name="username" value="this-is-a-long-username" maxlength="10" /></td></tr>
-<tr><th>Password1:</th><td><input type="password" name="password1" value="foo" /></td></tr>
-<tr><th>Password2:</th><td><input type="password" name="password2" value="bar" /></td></tr>
-</table>
-<input type="submit" />
-</form>
-
-Case 3: POST with valid data (the success message).
->>> print my_function('POST', {'username': 'adrian', 'password1': 'secret', 'password2': 'secret'})
-VALID: {'username': u'adrian', 'password1': u'secret', 'password2': u'secret'}
-
-# Some ideas for using templates with forms ###################################
-
->>> class UserRegistration(Form):
-... username = CharField(max_length=10, help_text="Good luck picking a username that doesn't already exist.")
-... password1 = CharField(widget=PasswordInput)
-... password2 = CharField(widget=PasswordInput)
-... def clean(self):
-... if self.clean_data.get('password1') and self.clean_data.get('password2') and self.clean_data['password1'] != self.clean_data['password2']:
-... raise ValidationError(u'Please make sure your passwords match.')
-... return self.clean_data
-
-You have full flexibility in displaying form fields in a template. Just pass a
-Form instance to the template, and use "dot" access to refer to individual
-fields. Note, however, that this flexibility comes with the responsibility of
-displaying all the errors, including any that might not be associated with a
-particular field.
->>> t = Template('''<form action="">
-... {{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p>
-... {{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p>
-... {{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p>
-... <input type="submit" />
-... </form>''')
->>> print t.render(Context({'form': UserRegistration(auto_id=False)}))
-<form action="">
-<p><label>Your username: <input type="text" name="username" maxlength="10" /></label></p>
-<p><label>Password: <input type="password" name="password1" /></label></p>
-<p><label>Password (again): <input type="password" name="password2" /></label></p>
-<input type="submit" />
-</form>
->>> print t.render(Context({'form': UserRegistration({'username': 'django'}, auto_id=False)}))
-<form action="">
-<p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p>
-<ul class="errorlist"><li>This field is required.</li></ul><p><label>Password: <input type="password" name="password1" /></label></p>
-<ul class="errorlist"><li>This field is required.</li></ul><p><label>Password (again): <input type="password" name="password2" /></label></p>
-<input type="submit" />
-</form>
-
-Use form.[field].label to output a field's label. You can specify the label for
-a field by using the 'label' argument to a Field class. If you don't specify
-'label', Django will use the field name with underscores converted to spaces,
-and the initial letter capitalized.
->>> t = Template('''<form action="">
-... <p><label>{{ form.username.label }}: {{ form.username }}</label></p>
-... <p><label>{{ form.password1.label }}: {{ form.password1 }}</label></p>
-... <p><label>{{ form.password2.label }}: {{ form.password2 }}</label></p>
-... <input type="submit" />
-... </form>''')
->>> print t.render(Context({'form': UserRegistration(auto_id=False)}))
-<form action="">
-<p><label>Username: <input type="text" name="username" maxlength="10" /></label></p>
-<p><label>Password1: <input type="password" name="password1" /></label></p>
-<p><label>Password2: <input type="password" name="password2" /></label></p>
-<input type="submit" />
-</form>
-
-User form.[field].label_tag to output a field's label with a <label> tag
-wrapped around it, but *only* if the given field has an "id" attribute.
-Recall from above that passing the "auto_id" argument to a Form gives each
-field an "id" attribute.
->>> t = Template('''<form action="">
-... <p>{{ form.username.label_tag }}: {{ form.username }}</p>
-... <p>{{ form.password1.label_tag }}: {{ form.password1 }}</p>
-... <p>{{ form.password2.label_tag }}: {{ form.password2 }}</p>
-... <input type="submit" />
-... </form>''')
->>> print t.render(Context({'form': UserRegistration(auto_id=False)}))
-<form action="">
-<p>Username: <input type="text" name="username" maxlength="10" /></p>
-<p>Password1: <input type="password" name="password1" /></p>
-<p>Password2: <input type="password" name="password2" /></p>
-<input type="submit" />
-</form>
->>> print t.render(Context({'form': UserRegistration(auto_id='id_%s')}))
-<form action="">
-<p><label for="id_username">Username</label>: <input id="id_username" type="text" name="username" maxlength="10" /></p>
-<p><label for="id_password1">Password1</label>: <input type="password" name="password1" id="id_password1" /></p>
-<p><label for="id_password2">Password2</label>: <input type="password" name="password2" id="id_password2" /></p>
-<input type="submit" />
-</form>
-
-User form.[field].help_text to output a field's help text. If the given field
-does not have help text, nothing will be output.
->>> t = Template('''<form action="">
-... <p>{{ form.username.label_tag }}: {{ form.username }}<br />{{ form.username.help_text }}</p>
-... <p>{{ form.password1.label_tag }}: {{ form.password1 }}</p>
-... <p>{{ form.password2.label_tag }}: {{ form.password2 }}</p>
-... <input type="submit" />
-... </form>''')
->>> print t.render(Context({'form': UserRegistration(auto_id=False)}))
-<form action="">
-<p>Username: <input type="text" name="username" maxlength="10" /><br />Good luck picking a username that doesn't already exist.</p>
-<p>Password1: <input type="password" name="password1" /></p>
-<p>Password2: <input type="password" name="password2" /></p>
-<input type="submit" />
-</form>
->>> Template('{{ form.password1.help_text }}').render(Context({'form': UserRegistration(auto_id=False)}))
-''
-
-The label_tag() method takes an optional attrs argument: a dictionary of HTML
-attributes to add to the <label> tag.
->>> f = UserRegistration(auto_id='id_%s')
->>> for bf in f:
-... print bf.label_tag(attrs={'class': 'pretty'})
-<label for="id_username" class="pretty">Username</label>
-<label for="id_password1" class="pretty">Password1</label>
-<label for="id_password2" class="pretty">Password2</label>
-
-To display the errors that aren't associated with a particular field -- e.g.,
-the errors caused by Form.clean() -- use {{ form.non_field_errors }} in the
-template. If used on its own, it is displayed as a <ul> (or an empty string, if
-the list of errors is empty). You can also use it in {% if %} statements.
->>> t = Template('''<form action="">
-... {{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p>
-... {{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p>
-... {{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p>
-... <input type="submit" />
-... </form>''')
->>> print t.render(Context({'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)}))
-<form action="">
-<p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p>
-<p><label>Password: <input type="password" name="password1" value="foo" /></label></p>
-<p><label>Password (again): <input type="password" name="password2" value="bar" /></label></p>
-<input type="submit" />
-</form>
->>> t = Template('''<form action="">
-... {{ form.non_field_errors }}
-... {{ form.username.errors.as_ul }}<p><label>Your username: {{ form.username }}</label></p>
-... {{ form.password1.errors.as_ul }}<p><label>Password: {{ form.password1 }}</label></p>
-... {{ form.password2.errors.as_ul }}<p><label>Password (again): {{ form.password2 }}</label></p>
-... <input type="submit" />
-... </form>''')
->>> print t.render(Context({'form': UserRegistration({'username': 'django', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)}))
-<form action="">
-<ul class="errorlist"><li>Please make sure your passwords match.</li></ul>
-<p><label>Your username: <input type="text" name="username" value="django" maxlength="10" /></label></p>
-<p><label>Password: <input type="password" name="password1" value="foo" /></label></p>
-<p><label>Password (again): <input type="password" name="password2" value="bar" /></label></p>
-<input type="submit" />
-</form>
-
-###############
-# Extra stuff #
-###############
-
-The newforms library comes with some extra, higher-level Field and Widget
-classes that demonstrate some of the library's abilities.
-
-# SelectDateWidget ############################################################
-
->>> from django.newforms.extras import SelectDateWidget
->>> w = SelectDateWidget(years=('2007','2008','2009','2010','2011','2012','2013','2014','2015','2016'))
->>> print w.render('mydate', '')
-<select name="mydate_month">
-<option value="1">January</option>
-<option value="2">February</option>
-<option value="3">March</option>
-<option value="4">April</option>
-<option value="5">May</option>
-<option value="6">June</option>
-<option value="7">July</option>
-<option value="8">August</option>
-<option value="9">September</option>
-<option value="10">October</option>
-<option value="11">November</option>
-<option value="12">December</option>
-</select>
-<select name="mydate_day">
-<option value="1">1</option>
-<option value="2">2</option>
-<option value="3">3</option>
-<option value="4">4</option>
-<option value="5">5</option>
-<option value="6">6</option>
-<option value="7">7</option>
-<option value="8">8</option>
-<option value="9">9</option>
-<option value="10">10</option>
-<option value="11">11</option>
-<option value="12">12</option>
-<option value="13">13</option>
-<option value="14">14</option>
-<option value="15">15</option>
-<option value="16">16</option>
-<option value="17">17</option>
-<option value="18">18</option>
-<option value="19">19</option>
-<option value="20">20</option>
-<option value="21">21</option>
-<option value="22">22</option>
-<option value="23">23</option>
-<option value="24">24</option>
-<option value="25">25</option>
-<option value="26">26</option>
-<option value="27">27</option>
-<option value="28">28</option>
-<option value="29">29</option>
-<option value="30">30</option>
-<option value="31">31</option>
-</select>
-<select name="mydate_year">
-<option value="2007">2007</option>
-<option value="2008">2008</option>
-<option value="2009">2009</option>
-<option value="2010">2010</option>
-<option value="2011">2011</option>
-<option value="2012">2012</option>
-<option value="2013">2013</option>
-<option value="2014">2014</option>
-<option value="2015">2015</option>
-<option value="2016">2016</option>
-</select>
->>> w.render('mydate', None) == w.render('mydate', '')
-True
->>> print w.render('mydate', '2010-04-15')
-<select name="mydate_month">
-<option value="1">January</option>
-<option value="2">February</option>
-<option value="3">March</option>
-<option value="4" selected="selected">April</option>
-<option value="5">May</option>
-<option value="6">June</option>
-<option value="7">July</option>
-<option value="8">August</option>
-<option value="9">September</option>
-<option value="10">October</option>
-<option value="11">November</option>
-<option value="12">December</option>
-</select>
-<select name="mydate_day">
-<option value="1">1</option>
-<option value="2">2</option>
-<option value="3">3</option>
-<option value="4">4</option>
-<option value="5">5</option>
-<option value="6">6</option>
-<option value="7">7</option>
-<option value="8">8</option>
-<option value="9">9</option>
-<option value="10">10</option>
-<option value="11">11</option>
-<option value="12">12</option>
-<option value="13">13</option>
-<option value="14">14</option>
-<option value="15" selected="selected">15</option>
-<option value="16">16</option>
-<option value="17">17</option>
-<option value="18">18</option>
-<option value="19">19</option>
-<option value="20">20</option>
-<option value="21">21</option>
-<option value="22">22</option>
-<option value="23">23</option>
-<option value="24">24</option>
-<option value="25">25</option>
-<option value="26">26</option>
-<option value="27">27</option>
-<option value="28">28</option>
-<option value="29">29</option>
-<option value="30">30</option>
-<option value="31">31</option>
-</select>
-<select name="mydate_year">
-<option value="2007">2007</option>
-<option value="2008">2008</option>
-<option value="2009">2009</option>
-<option value="2010" selected="selected">2010</option>
-<option value="2011">2011</option>
-<option value="2012">2012</option>
-<option value="2013">2013</option>
-<option value="2014">2014</option>
-<option value="2015">2015</option>
-<option value="2016">2016</option>
-</select>
-
-# USZipCodeField ##############################################################
-
-USZipCodeField validates that the data is either a five-digit U.S. zip code or
-a zip+4.
->>> from django.contrib.localflavor.usa.forms import USZipCodeField
->>> f = USZipCodeField()
->>> f.clean('60606')
-u'60606'
->>> f.clean(60606)
-u'60606'
->>> f.clean('04000')
-u'04000'
->>> f.clean('4000')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a zip code in the format XXXXX or XXXXX-XXXX.']
->>> f.clean('60606-1234')
-u'60606-1234'
->>> f.clean('6060-1234')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a zip code in the format XXXXX or XXXXX-XXXX.']
->>> f.clean('60606-')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a zip code in the format XXXXX or XXXXX-XXXX.']
->>> f.clean(None)
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean('')
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
-
->>> f = USZipCodeField(required=False)
->>> f.clean('60606')
-u'60606'
->>> f.clean(60606)
-u'60606'
->>> f.clean('04000')
-u'04000'
->>> f.clean('4000')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a zip code in the format XXXXX or XXXXX-XXXX.']
->>> f.clean('60606-1234')
-u'60606-1234'
->>> f.clean('6060-1234')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a zip code in the format XXXXX or XXXXX-XXXX.']
->>> f.clean('60606-')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a zip code in the format XXXXX or XXXXX-XXXX.']
->>> f.clean(None)
-u''
->>> f.clean('')
-u''
-
-# USPhoneNumberField ##########################################################
-
-USPhoneNumberField validates that the data is a valid U.S. phone number,
-including the area code. It's normalized to XXX-XXX-XXXX format.
->>> from django.contrib.localflavor.usa.forms import USPhoneNumberField
->>> f = USPhoneNumberField()
->>> f.clean('312-555-1212')
-u'312-555-1212'
->>> f.clean('3125551212')
-u'312-555-1212'
->>> f.clean('312 555-1212')
-u'312-555-1212'
->>> f.clean('(312) 555-1212')
-u'312-555-1212'
->>> f.clean('312 555 1212')
-u'312-555-1212'
->>> f.clean('312.555.1212')
-u'312-555-1212'
->>> f.clean('312.555-1212')
-u'312-555-1212'
->>> f.clean(' (312) 555.1212 ')
-u'312-555-1212'
->>> f.clean('555-1212')
-Traceback (most recent call last):
-...
-ValidationError: [u'Phone numbers must be in XXX-XXX-XXXX format.']
->>> f.clean('312-55-1212')
-Traceback (most recent call last):
-...
-ValidationError: [u'Phone numbers must be in XXX-XXX-XXXX format.']
->>> f.clean(None)
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean('')
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
-
->>> f = USPhoneNumberField(required=False)
->>> f.clean('312-555-1212')
-u'312-555-1212'
->>> f.clean('3125551212')
-u'312-555-1212'
->>> f.clean('312 555-1212')
-u'312-555-1212'
->>> f.clean('(312) 555-1212')
-u'312-555-1212'
->>> f.clean('312 555 1212')
-u'312-555-1212'
->>> f.clean('312.555.1212')
-u'312-555-1212'
->>> f.clean('312.555-1212')
-u'312-555-1212'
->>> f.clean(' (312) 555.1212 ')
-u'312-555-1212'
->>> f.clean('555-1212')
-Traceback (most recent call last):
-...
-ValidationError: [u'Phone numbers must be in XXX-XXX-XXXX format.']
->>> f.clean('312-55-1212')
-Traceback (most recent call last):
-...
-ValidationError: [u'Phone numbers must be in XXX-XXX-XXXX format.']
->>> f.clean(None)
-u''
->>> f.clean('')
-u''
-
-# USStateField ################################################################
-
-USStateField validates that the data is either an abbreviation or name of a
-U.S. state.
->>> from django.contrib.localflavor.usa.forms import USStateField
->>> f = USStateField()
->>> f.clean('il')
-u'IL'
->>> f.clean('IL')
-u'IL'
->>> f.clean('illinois')
-u'IL'
->>> f.clean(' illinois ')
-u'IL'
->>> f.clean(60606)
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a U.S. state or territory.']
->>> f.clean(None)
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean('')
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
-
->>> f = USStateField(required=False)
->>> f.clean('il')
-u'IL'
->>> f.clean('IL')
-u'IL'
->>> f.clean('illinois')
-u'IL'
->>> f.clean(' illinois ')
-u'IL'
->>> f.clean(60606)
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a U.S. state or territory.']
->>> f.clean(None)
-u''
->>> f.clean('')
-u''
-
-# USStateSelect ###############################################################
-
-USStateSelect is a Select widget that uses a list of U.S. states/territories
-as its choices.
->>> from django.contrib.localflavor.usa.forms import USStateSelect
->>> w = USStateSelect()
->>> print w.render('state', 'IL')
-<select name="state">
-<option value="AL">Alabama</option>
-<option value="AK">Alaska</option>
-<option value="AS">American Samoa</option>
-<option value="AZ">Arizona</option>
-<option value="AR">Arkansas</option>
-<option value="CA">California</option>
-<option value="CO">Colorado</option>
-<option value="CT">Connecticut</option>
-<option value="DE">Deleware</option>
-<option value="DC">District of Columbia</option>
-<option value="FM">Federated States of Micronesia</option>
-<option value="FL">Florida</option>
-<option value="GA">Georgia</option>
-<option value="GU">Guam</option>
-<option value="HI">Hawaii</option>
-<option value="ID">Idaho</option>
-<option value="IL" selected="selected">Illinois</option>
-<option value="IN">Indiana</option>
-<option value="IA">Iowa</option>
-<option value="KS">Kansas</option>
-<option value="KY">Kentucky</option>
-<option value="LA">Louisiana</option>
-<option value="ME">Maine</option>
-<option value="MH">Marshall Islands</option>
-<option value="MD">Maryland</option>
-<option value="MA">Massachusetts</option>
-<option value="MI">Michigan</option>
-<option value="MN">Minnesota</option>
-<option value="MS">Mississippi</option>
-<option value="MO">Missouri</option>
-<option value="MT">Montana</option>
-<option value="NE">Nebraska</option>
-<option value="NV">Nevada</option>
-<option value="NH">New Hampshire</option>
-<option value="NJ">New Jersey</option>
-<option value="NM">New Mexico</option>
-<option value="NY">New York</option>
-<option value="NC">North Carolina</option>
-<option value="ND">North Dakota</option>
-<option value="MP">Northern Mariana Islands</option>
-<option value="OH">Ohio</option>
-<option value="OK">Oklahoma</option>
-<option value="OR">Oregon</option>
-<option value="PW">Palau</option>
-<option value="PA">Pennsylvania</option>
-<option value="PR">Puerto Rico</option>
-<option value="RI">Rhode Island</option>
-<option value="SC">South Carolina</option>
-<option value="SD">South Dakota</option>
-<option value="TN">Tennessee</option>
-<option value="TX">Texas</option>
-<option value="UT">Utah</option>
-<option value="VT">Vermont</option>
-<option value="VI">Virgin Islands</option>
-<option value="VA">Virginia</option>
-<option value="WA">Washington</option>
-<option value="WV">West Virginia</option>
-<option value="WI">Wisconsin</option>
-<option value="WY">Wyoming</option>
-</select>
-
-# UKPostcodeField #############################################################
-
-UKPostcodeField validates that the data is a valid UK postcode.
->>> from django.contrib.localflavor.uk.forms import UKPostcodeField
->>> f = UKPostcodeField()
->>> f.clean('BT32 4PX')
-u'BT32 4PX'
->>> f.clean('GIR 0AA')
-u'GIR 0AA'
->>> f.clean('BT324PX')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a postcode. A space is required between the two postcode parts.']
->>> f.clean('1NV 4L1D')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a postcode. A space is required between the two postcode parts.']
->>> f.clean(None)
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
->>> f.clean('')
-Traceback (most recent call last):
-...
-ValidationError: [u'This field is required.']
-
->>> f = UKPostcodeField(required=False)
->>> f.clean('BT32 4PX')
-u'BT32 4PX'
->>> f.clean('GIR 0AA')
-u'GIR 0AA'
->>> f.clean('1NV 4L1D')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a postcode. A space is required between the two postcode parts.']
->>> f.clean('BT324PX')
-Traceback (most recent call last):
-...
-ValidationError: [u'Enter a postcode. A space is required between the two postcode parts.']
->>> f.clean(None)
-u''
->>> f.clean('')
-u''
-
-#################################
-# Tests of underlying functions #
-#################################
-
-# smart_unicode tests
->>> from django.newforms.util import smart_unicode
->>> class Test:
-... def __str__(self):
-... return 'ŠĐĆŽćžšđ'
->>> class TestU:
-... def __str__(self):
-... return 'Foo'
-... def __unicode__(self):
-... return u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111'
->>> smart_unicode(Test())
-u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111'
->>> smart_unicode(TestU())
-u'\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111'
->>> smart_unicode(1)
-u'1'
->>> smart_unicode('foo')
-u'foo'
-"""
-
-if __name__ == "__main__":
- import doctest
- doctest.testmod()
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/httpwrappers/tests.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,358 +0,0 @@
-"""
-###################
-# Empty QueryDict #
-###################
-
->>> q = QueryDict('')
-
->>> q['foo']
-Traceback (most recent call last):
-...
-MultiValueDictKeyError: "Key 'foo' not found in <MultiValueDict: {}>"
-
->>> q['something'] = 'bar'
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.get('foo', 'default')
-'default'
-
->>> q.getlist('foo')
-[]
-
->>> q.setlist('foo', ['bar', 'baz'])
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.appendlist('foo', ['bar'])
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.has_key('foo')
-False
-
->>> q.items()
-[]
-
->>> q.lists()
-[]
-
->>> q.keys()
-[]
-
->>> q.values()
-[]
-
->>> len(q)
-0
-
->>> q.update({'foo': 'bar'})
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.pop('foo')
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.popitem()
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.clear()
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.setdefault('foo', 'bar')
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.urlencode()
-''
-
-###################################
-# Mutable copy of empty QueryDict #
-###################################
-
->>> q = q.copy()
-
->>> q['foo']
-Traceback (most recent call last):
-...
-MultiValueDictKeyError: "Key 'foo' not found in <MultiValueDict: {}>"
-
->>> q['name'] = 'john'
-
->>> q['name']
-'john'
-
->>> q.get('foo', 'default')
-'default'
-
->>> q.get('name', 'default')
-'john'
-
->>> q.getlist('name')
-['john']
-
->>> q.getlist('foo')
-[]
-
->>> q.setlist('foo', ['bar', 'baz'])
-
->>> q.get('foo', 'default')
-'baz'
-
->>> q.getlist('foo')
-['bar', 'baz']
-
->>> q.appendlist('foo', 'another')
-
->>> q.getlist('foo')
-['bar', 'baz', 'another']
-
->>> q['foo']
-'another'
-
->>> q.has_key('foo')
-True
-
->>> q.items()
-[('foo', 'another'), ('name', 'john')]
-
->>> q.lists()
-[('foo', ['bar', 'baz', 'another']), ('name', ['john'])]
-
->>> q.keys()
-['foo', 'name']
-
->>> q.values()
-['another', 'john']
-
->>> len(q)
-2
-
->>> q.update({'foo': 'hello'})
-
-# Displays last value
->>> q['foo']
-'hello'
-
->>> q.get('foo', 'not available')
-'hello'
-
->>> q.getlist('foo')
-['bar', 'baz', 'another', 'hello']
-
->>> q.pop('foo')
-['bar', 'baz', 'another', 'hello']
-
->>> q.get('foo', 'not there')
-'not there'
-
->>> q.setdefault('foo', 'bar')
-'bar'
-
->>> q['foo']
-'bar'
-
->>> q.getlist('foo')
-['bar']
-
->>> q.urlencode()
-'foo=bar&name=john'
-
->>> q.clear()
-
->>> len(q)
-0
-
-#####################################
-# QueryDict with one key/value pair #
-#####################################
-
->>> q = QueryDict('foo=bar')
-
->>> q['foo']
-'bar'
-
->>> q['bar']
-Traceback (most recent call last):
-...
-MultiValueDictKeyError: "Key 'bar' not found in <MultiValueDict: {'foo': ['bar']}>"
-
->>> q['something'] = 'bar'
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.get('foo', 'default')
-'bar'
-
->>> q.get('bar', 'default')
-'default'
-
->>> q.getlist('foo')
-['bar']
-
->>> q.getlist('bar')
-[]
-
->>> q.setlist('foo', ['bar', 'baz'])
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.appendlist('foo', ['bar'])
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.has_key('foo')
-True
-
->>> q.has_key('bar')
-False
-
->>> q.items()
-[('foo', 'bar')]
-
->>> q.lists()
-[('foo', ['bar'])]
-
->>> q.keys()
-['foo']
-
->>> q.values()
-['bar']
-
->>> len(q)
-1
-
->>> q.update({'foo': 'bar'})
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.pop('foo')
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.popitem()
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.clear()
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.setdefault('foo', 'bar')
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.urlencode()
-'foo=bar'
-
-#####################################################
-# QueryDict with two key/value pairs with same keys #
-#####################################################
-
->>> q = QueryDict('vote=yes&vote=no')
-
->>> q['vote']
-'no'
-
->>> q['something'] = 'bar'
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.get('vote', 'default')
-'no'
-
->>> q.get('foo', 'default')
-'default'
-
->>> q.getlist('vote')
-['yes', 'no']
-
->>> q.getlist('foo')
-[]
-
->>> q.setlist('foo', ['bar', 'baz'])
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.appendlist('foo', ['bar'])
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.has_key('vote')
-True
-
->>> q.has_key('foo')
-False
-
->>> q.items()
-[('vote', 'no')]
-
->>> q.lists()
-[('vote', ['yes', 'no'])]
-
->>> q.keys()
-['vote']
-
->>> q.values()
-['no']
-
->>> len(q)
-1
-
->>> q.update({'foo': 'bar'})
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.pop('foo')
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.popitem()
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.clear()
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.setdefault('foo', 'bar')
-Traceback (most recent call last):
-...
-AttributeError: This QueryDict instance is immutable
-
->>> q.urlencode()
-'vote=yes&vote=no'
-
-"""
-
-from django.http import QueryDict
-
-if __name__ == "__main__":
- import doctest
- doctest.testmod()
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/humanize/tests.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,52 +0,0 @@
-import unittest
-from django.template import Template, Context, add_to_builtins
-
-add_to_builtins('django.contrib.humanize.templatetags.humanize')
-
-class HumanizeTests(unittest.TestCase):
-
- def humanize_tester(self, test_list, result_list, method):
- # Using max below ensures we go through both lists
- # However, if the lists are not equal length, this raises an exception
- for index in xrange(len(max(test_list,result_list))):
- test_content = test_list[index]
- t = Template('{{ test_content|%s }}' % method)
- rendered = t.render(Context(locals())).strip()
- self.assertEqual(rendered, result_list[index],
- msg="""%s test failed, produced %s,
-should've produced %s""" % (method, rendered, result_list[index]))
-
- def test_ordinal(self):
- test_list = ('1','2','3','4','11','12',
- '13','101','102','103','111',
- 'something else')
- result_list = ('1st', '2nd', '3rd', '4th', '11th',
- '12th', '13th', '101st', '102nd', '103rd',
- '111th', 'something else')
-
- self.humanize_tester(test_list, result_list, 'ordinal')
-
- def test_intcomma(self):
- test_list = ('100','1000','10123','10311','1000000')
- result_list = ('100', '1,000', '10,123', '10,311', '1,000,000')
-
- self.humanize_tester(test_list, result_list, 'intcomma')
-
- def test_intword(self):
- test_list = ('100', '1000000', '1200000', '1290000',
- '1000000000','2000000000','6000000000000')
- result_list = ('100', '1.0 million', '1.2 million', '1.3 million',
- '1.0 billion', '2.0 billion', '6.0 trillion')
-
- self.humanize_tester(test_list, result_list, 'intword')
-
- def test_apnumber(self):
- test_list = [str(x) for x in xrange(1,11)]
- result_list = ('one', 'two', 'three', 'four', 'five', 'six',
- 'seven', 'eight', 'nine', '10')
-
- self.humanize_tester(test_list, result_list, 'apnumber')
-
-if __name__ == '__main__':
- unittest.main()
-
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/initial_sql_regress/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,13 +0,0 @@
-"""
-Regression tests for initial SQL insertion.
-"""
-
-from django.db import models
-
-class Simple(models.Model):
- name = models.CharField(maxlength = 50)
-
-__test__ = {'API_TESTS':""}
-
-# NOTE: The format of the included SQL file for this test suite is important.
-# It must end with a trailing newline in order to test the fix for #2161.
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/initial_sql_regress/sql/simple.sql Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,8 +0,0 @@
-INSERT INTO initial_sql_regress_simple (name) VALUES ('John');
-INSERT INTO initial_sql_regress_simple (name) VALUES ('Paul');
-INSERT INTO initial_sql_regress_simple (name) VALUES ('Ringo');
-INSERT INTO initial_sql_regress_simple (name) VALUES ('George');
-INSERT INTO initial_sql_regress_simple (name) VALUES ('Miles O''Brien');
-INSERT INTO initial_sql_regress_simple (name) VALUES ('Semicolon;Man');
-INSERT INTO initial_sql_regress_simple (name) VALUES ('This line has a Windows line ending');
-
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/invalid_admin_options/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,337 +0,0 @@
-"""
-Admin options
-
-Test invalid and valid admin options to make sure that
-model validation is working properly.
-"""
-
-from django.db import models
-model_errors = ""
-
-# TODO: Invalid admin options should not cause a metaclass error
-##This should fail gracefully but is causing a metaclass error
-#class BadAdminOption(models.Model):
-# "Test nonexistent admin option"
-# name = models.CharField(maxlength=30)
-#
-# class Admin:
-# nonexistent = 'option'
-#
-#model_errors += """invalid_admin_options.badadminoption: "admin" attribute, if given, must be set to a models.AdminOptions() instance.
-#"""
-
-class ListDisplayBadOne(models.Model):
- "Test list_display, list_display must be a list or tuple"
- first_name = models.CharField(maxlength=30)
-
- class Admin:
- list_display = 'first_name'
-
-model_errors += """invalid_admin_options.listdisplaybadone: "admin.list_display", if given, must be set to a list or tuple.
-"""
-
-class ListDisplayBadTwo(models.Model):
- "Test list_display, list_display items must be attributes, methods or properties."
- first_name = models.CharField(maxlength=30)
-
- class Admin:
- list_display = ['first_name','nonexistent']
-
-model_errors += """invalid_admin_options.listdisplaybadtwo: "admin.list_display" refers to 'nonexistent', which isn't an attribute, method or property.
-"""
-class ListDisplayBadThree(models.Model):
- "Test list_display, list_display items can not be a ManyToManyField."
- first_name = models.CharField(maxlength=30)
- nick_names = models.ManyToManyField('ListDisplayGood')
-
- class Admin:
- list_display = ['first_name','nick_names']
-
-model_errors += """invalid_admin_options.listdisplaybadthree: "admin.list_display" doesn't support ManyToManyFields ('nick_names').
-"""
-
-class ListDisplayGood(models.Model):
- "Test list_display, Admin list_display can be a attribute, method or property."
- first_name = models.CharField(maxlength=30)
-
- def _last_name(self):
- return self.first_name
- last_name = property(_last_name)
-
- def full_name(self):
- return "%s %s" % (self.first_name, self.last_name)
-
- class Admin:
- list_display = ['first_name','last_name','full_name']
-
-class ListDisplayLinksBadOne(models.Model):
- "Test list_display_links, item must be included in list_display."
- first_name = models.CharField(maxlength=30)
- last_name = models.CharField(maxlength=30)
-
- class Admin:
- list_display = ['last_name']
- list_display_links = ['first_name']
-
-model_errors += """invalid_admin_options.listdisplaylinksbadone: "admin.list_display_links" refers to 'first_name', which is not defined in "admin.list_display".
-"""
-
-class ListDisplayLinksBadTwo(models.Model):
- "Test list_display_links, must be a list or tuple."
- first_name = models.CharField(maxlength=30)
- last_name = models.CharField(maxlength=30)
-
- class Admin:
- list_display = ['first_name','last_name']
- list_display_links = 'last_name'
-
-model_errors += """invalid_admin_options.listdisplaylinksbadtwo: "admin.list_display_links", if given, must be set to a list or tuple.
-"""
-
-# TODO: Fix list_display_links validation or remove the check for list_display
-## This is failing but the validation which should fail is not.
-#class ListDisplayLinksBadThree(models.Model):
-# "Test list_display_links, must define list_display to use list_display_links."
-# first_name = models.CharField(maxlength=30)
-# last_name = models.CharField(maxlength=30)
-#
-# class Admin:
-# list_display_links = ('first_name',)
-#
-#model_errors += """invalid_admin_options.listdisplaylinksbadthree: "admin.list_display" must be defined for "admin.list_display_links" to be used.
-#"""
-
-class ListDisplayLinksGood(models.Model):
- "Test list_display_links, Admin list_display_list can be a attribute, method or property."
- first_name = models.CharField(maxlength=30)
-
- def _last_name(self):
- return self.first_name
- last_name = property(_last_name)
-
- def full_name(self):
- return "%s %s" % (self.first_name, self.last_name)
-
- class Admin:
- list_display = ['first_name','last_name','full_name']
- list_display_links = ['first_name','last_name','full_name']
-
-class ListFilterBadOne(models.Model):
- "Test list_filter, must be a list or tuple."
- first_name = models.CharField(maxlength=30)
-
- class Admin:
- list_filter = 'first_name'
-
-model_errors += """invalid_admin_options.listfilterbadone: "admin.list_filter", if given, must be set to a list or tuple.
-"""
-
-class ListFilterBadTwo(models.Model):
- "Test list_filter, must be a field not a property or method."
- first_name = models.CharField(maxlength=30)
-
- def _last_name(self):
- return self.first_name
- last_name = property(_last_name)
-
- def full_name(self):
- return "%s %s" % (self.first_name, self.last_name)
-
- class Admin:
- list_filter = ['first_name','last_name','full_name']
-
-model_errors += """invalid_admin_options.listfilterbadtwo: "admin.list_filter" refers to 'last_name', which isn't a field.
-invalid_admin_options.listfilterbadtwo: "admin.list_filter" refers to 'full_name', which isn't a field.
-"""
-
-class DateHierarchyBadOne(models.Model):
- "Test date_hierarchy, must be a date or datetime field."
- first_name = models.CharField(maxlength=30)
- birth_day = models.DateField()
-
- class Admin:
- date_hierarchy = 'first_name'
-
-# TODO: Date Hierarchy needs to check if field is a date/datetime field.
-#model_errors += """invalid_admin_options.datehierarchybadone: "admin.date_hierarchy" refers to 'first_name', which isn't a date field or datetime field.
-#"""
-
-class DateHierarchyBadTwo(models.Model):
- "Test date_hieracrhy, must be a field."
- first_name = models.CharField(maxlength=30)
- birth_day = models.DateField()
-
- class Admin:
- date_hierarchy = 'nonexistent'
-
-model_errors += """invalid_admin_options.datehierarchybadtwo: "admin.date_hierarchy" refers to 'nonexistent', which isn't a field.
-"""
-
-class DateHierarchyGood(models.Model):
- "Test date_hieracrhy, must be a field."
- first_name = models.CharField(maxlength=30)
- birth_day = models.DateField()
-
- class Admin:
- date_hierarchy = 'birth_day'
-
-class SearchFieldsBadOne(models.Model):
- "Test search_fields, must be a list or tuple."
- first_name = models.CharField(maxlength=30)
-
- class Admin:
- search_fields = ('nonexistent')
-
-# TODO: Add search_fields validation
-#model_errors += """invalid_admin_options.seacrhfieldsbadone: "admin.search_fields", if given, must be set to a list or tuple.
-#"""
-
-class SearchFieldsBadTwo(models.Model):
- "Test search_fields, must be a field."
- first_name = models.CharField(maxlength=30)
-
- def _last_name(self):
- return self.first_name
- last_name = property(_last_name)
-
- class Admin:
- search_fields = ['first_name','last_name']
-
-# TODO: Add search_fields validation
-#model_errors += """invalid_admin_options.seacrhfieldsbadone: "admin.search_fields" refers to 'last_name', which isn't a field.
-#"""
-
-class SearchFieldsGood(models.Model):
- "Test search_fields, must be a list or tuple."
- first_name = models.CharField(maxlength=30)
- last_name = models.CharField(maxlength=30)
-
- class Admin:
- search_fields = ['first_name','last_name']
-
-
-class JsBadOne(models.Model):
- "Test js, must be a list or tuple"
- name = models.CharField(maxlength=30)
-
- class Admin:
- js = 'test.js'
-
-# TODO: Add a js validator
-#model_errors += """invalid_admin_options.jsbadone: "admin.js", if given, must be set to a list or tuple.
-#"""
-
-class SaveAsBad(models.Model):
- "Test save_as, should be True or False"
- name = models.CharField(maxlength=30)
-
- class Admin:
- save_as = 'not True or False'
-
-# TODO: Add a save_as validator.
-#model_errors += """invalid_admin_options.saveasbad: "admin.save_as", if given, must be set to True or False.
-#"""
-
-class SaveOnTopBad(models.Model):
- "Test save_on_top, should be True or False"
- name = models.CharField(maxlength=30)
-
- class Admin:
- save_on_top = 'not True or False'
-
-# TODO: Add a save_on_top validator.
-#model_errors += """invalid_admin_options.saveontopbad: "admin.save_on_top", if given, must be set to True or False.
-#"""
-
-class ListSelectRelatedBad(models.Model):
- "Test list_select_related, should be True or False"
- name = models.CharField(maxlength=30)
-
- class Admin:
- list_select_related = 'not True or False'
-
-# TODO: Add a list_select_related validator.
-#model_errors += """invalid_admin_options.listselectrelatebad: "admin.list_select_related", if given, must be set to True or False.
-#"""
-
-class ListPerPageBad(models.Model):
- "Test list_per_page, should be a positive integer value."
- name = models.CharField(maxlength=30)
-
- class Admin:
- list_per_page = 89.3
-
-# TODO: Add a list_per_page validator.
-#model_errors += """invalid_admin_options.listperpagebad: "admin.list_per_page", if given, must be a positive integer.
-#"""
-
-class FieldsBadOne(models.Model):
- "Test fields, should be a tuple"
- first_name = models.CharField(maxlength=30)
- last_name = models.CharField(maxlength=30)
-
- class Admin:
- fields = 'not a tuple'
-
-# TODO: Add a fields validator.
-#model_errors += """invalid_admin_options.fieldsbadone: "admin.fields", if given, must be a tuple.
-#"""
-
-class FieldsBadTwo(models.Model):
- """Test fields, 'fields' dict option is required."""
- first_name = models.CharField(maxlength=30)
- last_name = models.CharField(maxlength=30)
-
- class Admin:
- fields = ('Name', {'description': 'this fieldset needs fields'})
-
-# TODO: Add a fields validator.
-#model_errors += """invalid_admin_options.fieldsbadtwo: "admin.fields" each fieldset must include a 'fields' dict.
-#"""
-
-class FieldsBadThree(models.Model):
- """Test fields, 'classes' and 'description' are the only allowable extra dict options."""
- first_name = models.CharField(maxlength=30)
- last_name = models.CharField(maxlength=30)
-
- class Admin:
- fields = ('Name', {'fields': ('first_name','last_name'),'badoption': 'verybadoption'})
-
-# TODO: Add a fields validator.
-#model_errors += """invalid_admin_options.fieldsbadthree: "admin.fields" fieldset options must be either 'classes' or 'description'.
-#"""
-
-class FieldsGood(models.Model):
- "Test fields, working example"
- first_name = models.CharField(maxlength=30)
- last_name = models.CharField(maxlength=30)
- birth_day = models.DateField()
-
- class Admin:
- fields = (
- ('Name', {'fields': ('first_name','last_name'),'classes': 'collapse'}),
- (None, {'fields': ('birth_day',),'description': 'enter your b-day'})
- )
-
-class OrderingBad(models.Model):
- "Test ordering, must be a field."
- first_name = models.CharField(maxlength=30)
- last_name = models.CharField(maxlength=30)
-
- class Admin:
- ordering = 'nonexistent'
-
-# TODO: Add a ordering validator.
-#model_errors += """invalid_admin_options.orderingbad: "admin.ordering" refers to 'nonexistent', which isn't a field.
-#"""
-
-## TODO: Add a manager validator, this should fail gracefully.
-#class ManagerBad(models.Model):
-# "Test manager, must be a manager object."
-# first_name = models.CharField(maxlength=30)
-#
-# class Admin:
-# manager = 'nonexistent'
-#
-#model_errors += """invalid_admin_options.managerbad: "admin.manager" refers to 'nonexistent', which isn't a Manager().
-#"""
\ No newline at end of file
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/many_to_one_regress/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,34 +0,0 @@
-from django.db import models
-
-# If ticket #1578 ever slips back in, these models will not be able to be
-# created (the field names being lower-cased versions of their opposite
-# classes is important here).
-
-class First(models.Model):
- second = models.IntegerField()
-
-class Second(models.Model):
- first = models.ForeignKey(First, related_name = 'the_first')
-
-# Protect against repetition of #1839, #2415 and #2536.
-class Third(models.Model):
- name = models.CharField(maxlength=20)
- third = models.ForeignKey('self', null=True, related_name='child_set')
-
-class Parent(models.Model):
- name = models.CharField(maxlength=20)
- bestchild = models.ForeignKey('Child', null=True, related_name='favored_by')
-
-class Child(models.Model):
- name = models.CharField(maxlength=20)
- parent = models.ForeignKey(Parent)
-
-
-__test__ = {'API_TESTS':"""
->>> Third.AddManipulator().save(dict(id='3', name='An example', another=None))
-<Third: Third object>
->>> parent = Parent(name = 'fred')
->>> parent.save()
->>> Child.AddManipulator().save(dict(name='bam-bam', parent=parent.id))
-<Child: Child object>
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/markup/tests.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,69 +0,0 @@
-# Quick tests for the markup templatetags (django.contrib.markup)
-
-from django.template import Template, Context, add_to_builtins
-import re
-import unittest
-
-add_to_builtins('django.contrib.markup.templatetags.markup')
-
-class Templates(unittest.TestCase):
- def test_textile(self):
- try:
- import textile
- except ImportError:
- textile = None
-
- textile_content = """Paragraph 1
-
-Paragraph 2 with "quotes" and @code@"""
-
- t = Template("{{ textile_content|textile }}")
- rendered = t.render(Context(locals())).strip()
- if textile:
- self.assertEqual(rendered, """<p>Paragraph 1</p>
-
-<p>Paragraph 2 with “quotes” and <code>code</code></p>""")
- else:
- self.assertEqual(rendered, textile_content)
-
- def test_markdown(self):
- try:
- import markdown
- except ImportError:
- markdown = None
-
- markdown_content = """Paragraph 1
-
-## An h2"""
-
- t = Template("{{ markdown_content|markdown }}")
- rendered = t.render(Context(locals())).strip()
- if markdown:
- pattern = re.compile("""<p>Paragraph 1\s*</p>\s*<h2>\s*An h2</h2>""")
- self.assert_(pattern.match(rendered))
- else:
- self.assertEqual(rendered, markdown_content)
-
- def test_docutils(self):
- try:
- import docutils
- except ImportError:
- docutils = None
-
- rest_content = """Paragraph 1
-
-Paragraph 2 with a link_
-
-.. _link: http://www.example.com/"""
-
- t = Template("{{ rest_content|restructuredtext }}")
- rendered = t.render(Context(locals())).strip()
- if docutils:
- self.assertEqual(rendered, """<p>Paragraph 1</p>
-<p>Paragraph 2 with a <a class="reference" href="http://www.example.com/">link</a></p>""")
- else:
- self.assertEqual(rendered, rest_content)
-
-
-if __name__ == '__main__':
- unittest.main()
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/null_queries/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,54 +0,0 @@
-from django.db import models
-
-class Poll(models.Model):
- question = models.CharField(maxlength=200)
-
- def __str__(self):
- return "Q: %s " % self.question
-
-class Choice(models.Model):
- poll = models.ForeignKey(Poll)
- choice = models.CharField(maxlength=200)
-
- def __str__(self):
- return "Choice: %s in poll %s" % (self.choice, self.poll)
-
-__test__ = {'API_TESTS':"""
-# Regression test for the use of None as a query value. None is interpreted as
-# an SQL NULL, but only in __exact queries.
-# Set up some initial polls and choices
->>> p1 = Poll(question='Why?')
->>> p1.save()
->>> c1 = Choice(poll=p1, choice='Because.')
->>> c1.save()
->>> c2 = Choice(poll=p1, choice='Why Not?')
->>> c2.save()
-
-# Exact query with value None returns nothing (=NULL in sql)
->>> Choice.objects.filter(id__exact=None)
-[]
-
-# Valid query, but fails because foo isn't a keyword
->>> Choice.objects.filter(foo__exact=None)
-Traceback (most recent call last):
-...
-TypeError: Cannot resolve keyword 'foo' into field
-
-# Can't use None on anything other than __exact
->>> Choice.objects.filter(id__gt=None)
-Traceback (most recent call last):
-...
-ValueError: Cannot use None as a query value
-
-# Can't use None on anything other than __exact
->>> Choice.objects.filter(foo__gt=None)
-Traceback (most recent call last):
-...
-ValueError: Cannot use None as a query value
-
-# Related managers use __exact=None implicitly if the object hasn't been saved.
->>> p2 = Poll(question="How?")
->>> p2.choice_set.all()
-[]
-
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/one_to_one_regress/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,37 +0,0 @@
-from django.db import models
-
-class Place(models.Model):
- name = models.CharField(maxlength=50)
- address = models.CharField(maxlength=80)
-
- def __str__(self):
- return "%s the place" % self.name
-
-class Restaurant(models.Model):
- place = models.OneToOneField(Place)
- serves_hot_dogs = models.BooleanField()
- serves_pizza = models.BooleanField()
-
- def __str__(self):
- return "%s the restaurant" % self.place.name
-
-class Favorites(models.Model):
- name = models.CharField(maxlength = 50)
- restaurants = models.ManyToManyField(Restaurant)
-
- def __str__(self):
- return "Favorites for %s" % self.name
-
-__test__ = {'API_TESTS':"""
-# Regression test for #1064 and #1506: Check that we create models via the m2m
-# relation if the remote model has a OneToOneField.
->>> p1 = Place(name='Demon Dogs', address='944 W. Fullerton')
->>> p1.save()
->>> r = Restaurant(place=p1, serves_hot_dogs=True, serves_pizza=False)
->>> r.save()
->>> f = Favorites(name = 'Fred')
->>> f.save()
->>> f.restaurants = [r]
->>> f.restaurants.all()
-[<Restaurant: Demon Dogs the restaurant>]
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/serializers_regress/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,187 +0,0 @@
-"""
-A test spanning all the capabilities of all the serializers.
-
-This class sets up a model for each model field type
-(except for image types, because of the PIL dependency).
-"""
-
-from django.db import models
-from django.contrib.contenttypes.models import ContentType
-
-# The following classes are for testing basic data
-# marshalling, including NULL values.
-
-class BooleanData(models.Model):
- data = models.BooleanField(null=True)
-
-class CharData(models.Model):
- data = models.CharField(maxlength=30, null=True)
-
-class DateData(models.Model):
- data = models.DateField(null=True)
-
-class DateTimeData(models.Model):
- data = models.DateTimeField(null=True)
-
-class EmailData(models.Model):
- data = models.EmailField(null=True)
-
-class FileData(models.Model):
- data = models.FileField(null=True, upload_to='/foo/bar')
-
-class FilePathData(models.Model):
- data = models.FilePathField(null=True)
-
-class FloatData(models.Model):
- data = models.FloatField(null=True, decimal_places=3, max_digits=5)
-
-class IntegerData(models.Model):
- data = models.IntegerField(null=True)
-
-# class ImageData(models.Model):
-# data = models.ImageField(null=True)
-
-class IPAddressData(models.Model):
- data = models.IPAddressField(null=True)
-
-class NullBooleanData(models.Model):
- data = models.NullBooleanField(null=True)
-
-class PhoneData(models.Model):
- data = models.PhoneNumberField(null=True)
-
-class PositiveIntegerData(models.Model):
- data = models.PositiveIntegerField(null=True)
-
-class PositiveSmallIntegerData(models.Model):
- data = models.PositiveSmallIntegerField(null=True)
-
-class SlugData(models.Model):
- data = models.SlugField(null=True)
-
-class SmallData(models.Model):
- data = models.SmallIntegerField(null=True)
-
-class TextData(models.Model):
- data = models.TextField(null=True)
-
-class TimeData(models.Model):
- data = models.TimeField(null=True)
-
-class USStateData(models.Model):
- data = models.USStateField(null=True)
-
-class XMLData(models.Model):
- data = models.XMLField(null=True)
-
-class Tag(models.Model):
- """A tag on an item."""
- data = models.SlugField()
- content_type = models.ForeignKey(ContentType)
- object_id = models.PositiveIntegerField()
-
- content_object = models.GenericForeignKey()
-
- class Meta:
- ordering = ["data"]
-
-class GenericData(models.Model):
- data = models.CharField(maxlength=30)
-
- tags = models.GenericRelation(Tag)
-
-# The following test classes are all for validation
-# of related objects; in particular, forward, backward,
-# and self references.
-
-class Anchor(models.Model):
- """This is a model that can be used as
- something for other models to point at"""
-
- data = models.CharField(maxlength=30)
-
-class FKData(models.Model):
- data = models.ForeignKey(Anchor, null=True)
-
-class M2MData(models.Model):
- data = models.ManyToManyField(Anchor, null=True)
-
-class O2OData(models.Model):
- data = models.OneToOneField(Anchor, null=True)
-
-class FKSelfData(models.Model):
- data = models.ForeignKey('self', null=True)
-
-class M2MSelfData(models.Model):
- data = models.ManyToManyField('self', null=True, symmetrical=False)
-
-# The following test classes are for validating the
-# deserialization of objects that use a user-defined
-# field as the primary key.
-# Some of these data types have been commented out
-# because they can't be used as a primary key on one
-# or all database backends.
-
-class BooleanPKData(models.Model):
- data = models.BooleanField(primary_key=True)
-
-class CharPKData(models.Model):
- data = models.CharField(maxlength=30, primary_key=True)
-
-# class DatePKData(models.Model):
-# data = models.DateField(primary_key=True)
-
-# class DateTimePKData(models.Model):
-# data = models.DateTimeField(primary_key=True)
-
-class EmailPKData(models.Model):
- data = models.EmailField(primary_key=True)
-
-class FilePKData(models.Model):
- data = models.FileField(primary_key=True, upload_to='/foo/bar')
-
-class FilePathPKData(models.Model):
- data = models.FilePathField(primary_key=True)
-
-class FloatPKData(models.Model):
- data = models.FloatField(primary_key=True, decimal_places=3, max_digits=5)
-
-class IntegerPKData(models.Model):
- data = models.IntegerField(primary_key=True)
-
-# class ImagePKData(models.Model):
-# data = models.ImageField(primary_key=True)
-
-class IPAddressPKData(models.Model):
- data = models.IPAddressField(primary_key=True)
-
-class NullBooleanPKData(models.Model):
- data = models.NullBooleanField(primary_key=True)
-
-class PhonePKData(models.Model):
- data = models.PhoneNumberField(primary_key=True)
-
-class PositiveIntegerPKData(models.Model):
- data = models.PositiveIntegerField(primary_key=True)
-
-class PositiveSmallIntegerPKData(models.Model):
- data = models.PositiveSmallIntegerField(primary_key=True)
-
-class SlugPKData(models.Model):
- data = models.SlugField(primary_key=True)
-
-class SmallPKData(models.Model):
- data = models.SmallIntegerField(primary_key=True)
-
-# class TextPKData(models.Model):
-# data = models.TextField(primary_key=True)
-
-# class TimePKData(models.Model):
-# data = models.TimeField(primary_key=True)
-
-class USStatePKData(models.Model):
- data = models.USStateField(primary_key=True)
-
-# class XMLPKData(models.Model):
-# data = models.XMLField(primary_key=True)
-
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/serializers_regress/tests.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,263 +0,0 @@
-"""
-A test spanning all the capabilities of all the serializers.
-
-This class defines sample data and a dynamically generated
-test case that is capable of testing the capabilities of
-the serializers. This includes all valid data values, plus
-forward, backwards and self references.
-"""
-
-
-import unittest, datetime
-
-from django.utils.functional import curry
-from django.core import serializers
-from django.db import transaction
-from django.core import management
-
-from models import *
-
-# A set of functions that can be used to recreate
-# test data objects of various kinds
-def data_create(pk, klass, data):
- instance = klass(id=pk)
- instance.data = data
- instance.save()
- return instance
-
-def generic_create(pk, klass, data):
- instance = klass(id=pk)
- instance.data = data[0]
- instance.save()
- for tag in data[1:]:
- instance.tags.create(data=tag)
- return instance
-
-def fk_create(pk, klass, data):
- instance = klass(id=pk)
- setattr(instance, 'data_id', data)
- instance.save()
- return instance
-
-def m2m_create(pk, klass, data):
- instance = klass(id=pk)
- instance.save()
- instance.data = data
- return instance
-
-def o2o_create(pk, klass, data):
- instance = klass()
- instance.data_id = data
- instance.save()
- return instance
-
-def pk_create(pk, klass, data):
- instance = klass()
- instance.data = data
- instance.save()
- return instance
-
-# A set of functions that can be used to compare
-# test data objects of various kinds
-def data_compare(testcase, pk, klass, data):
- instance = klass.objects.get(id=pk)
- testcase.assertEqual(data, instance.data,
- "Objects with PK=%d not equal; expected '%s' (%s), got '%s' (%s)" % (pk,data, type(data), instance.data, type(instance.data)))
-
-def generic_compare(testcase, pk, klass, data):
- instance = klass.objects.get(id=pk)
- testcase.assertEqual(data[0], instance.data)
- testcase.assertEqual(data[1:], [t.data for t in instance.tags.all()])
-
-def fk_compare(testcase, pk, klass, data):
- instance = klass.objects.get(id=pk)
- testcase.assertEqual(data, instance.data_id)
-
-def m2m_compare(testcase, pk, klass, data):
- instance = klass.objects.get(id=pk)
- testcase.assertEqual(data, [obj.id for obj in instance.data.all()])
-
-def o2o_compare(testcase, pk, klass, data):
- instance = klass.objects.get(data=data)
- testcase.assertEqual(data, instance.data_id)
-
-def pk_compare(testcase, pk, klass, data):
- instance = klass.objects.get(data=data)
- testcase.assertEqual(data, instance.data)
-
-# Define some data types. Each data type is
-# actually a pair of functions; one to create
-# and one to compare objects of that type
-data_obj = (data_create, data_compare)
-generic_obj = (generic_create, generic_compare)
-fk_obj = (fk_create, fk_compare)
-m2m_obj = (m2m_create, m2m_compare)
-o2o_obj = (o2o_create, o2o_compare)
-pk_obj = (pk_create, pk_compare)
-
-test_data = [
- # Format: (data type, PK value, Model Class, data)
- (data_obj, 1, BooleanData, True),
- (data_obj, 2, BooleanData, False),
- (data_obj, 10, CharData, "Test Char Data"),
- (data_obj, 11, CharData, ""),
- (data_obj, 12, CharData, "None"),
- (data_obj, 13, CharData, "null"),
- (data_obj, 14, CharData, "NULL"),
- (data_obj, 15, CharData, None),
- (data_obj, 20, DateData, datetime.date(2006,6,16)),
- (data_obj, 21, DateData, None),
- (data_obj, 30, DateTimeData, datetime.datetime(2006,6,16,10,42,37)),
- (data_obj, 31, DateTimeData, None),
- (data_obj, 40, EmailData, "hovercraft@example.com"),
- (data_obj, 41, EmailData, None),
- (data_obj, 50, FileData, 'file:///foo/bar/whiz.txt'),
- (data_obj, 51, FileData, None),
- (data_obj, 60, FilePathData, "/foo/bar/whiz.txt"),
- (data_obj, 61, FilePathData, None),
- (data_obj, 70, FloatData, 12.345),
- (data_obj, 71, FloatData, -12.345),
- (data_obj, 72, FloatData, 0.0),
- (data_obj, 73, FloatData, None),
- (data_obj, 80, IntegerData, 123456789),
- (data_obj, 81, IntegerData, -123456789),
- (data_obj, 82, IntegerData, 0),
- (data_obj, 83, IntegerData, None),
- #(XX, ImageData
- (data_obj, 90, IPAddressData, "127.0.0.1"),
- (data_obj, 91, IPAddressData, None),
- (data_obj, 100, NullBooleanData, True),
- (data_obj, 101, NullBooleanData, False),
- (data_obj, 102, NullBooleanData, None),
- (data_obj, 110, PhoneData, "212-634-5789"),
- (data_obj, 111, PhoneData, None),
- (data_obj, 120, PositiveIntegerData, 123456789),
- (data_obj, 121, PositiveIntegerData, None),
- (data_obj, 130, PositiveSmallIntegerData, 12),
- (data_obj, 131, PositiveSmallIntegerData, None),
- (data_obj, 140, SlugData, "this-is-a-slug"),
- (data_obj, 141, SlugData, None),
- (data_obj, 150, SmallData, 12),
- (data_obj, 151, SmallData, -12),
- (data_obj, 152, SmallData, 0),
- (data_obj, 153, SmallData, None),
- (data_obj, 160, TextData, """This is a long piece of text.
-It contains line breaks.
-Several of them.
-The end."""),
- (data_obj, 161, TextData, ""),
- (data_obj, 162, TextData, None),
- (data_obj, 170, TimeData, datetime.time(10,42,37)),
- (data_obj, 171, TimeData, None),
- (data_obj, 180, USStateData, "MA"),
- (data_obj, 181, USStateData, None),
- (data_obj, 190, XMLData, "<foo></foo>"),
- (data_obj, 191, XMLData, None),
-
- (generic_obj, 200, GenericData, ['Generic Object 1', 'tag1', 'tag2']),
- (generic_obj, 201, GenericData, ['Generic Object 2', 'tag2', 'tag3']),
-
- (data_obj, 300, Anchor, "Anchor 1"),
- (data_obj, 301, Anchor, "Anchor 2"),
-
- (fk_obj, 400, FKData, 300), # Post reference
- (fk_obj, 401, FKData, 500), # Pre reference
- (fk_obj, 402, FKData, None), # Empty reference
-
- (m2m_obj, 410, M2MData, []), # Empty set
- (m2m_obj, 411, M2MData, [300,301]), # Post reference
- (m2m_obj, 412, M2MData, [500,501]), # Pre reference
- (m2m_obj, 413, M2MData, [300,301,500,501]), # Pre and Post reference
-
- (o2o_obj, None, O2OData, 300), # Post reference
- (o2o_obj, None, O2OData, 500), # Pre reference
-
- (fk_obj, 430, FKSelfData, 431), # Pre reference
- (fk_obj, 431, FKSelfData, 430), # Post reference
- (fk_obj, 432, FKSelfData, None), # Empty reference
-
- (m2m_obj, 440, M2MSelfData, []),
- (m2m_obj, 441, M2MSelfData, []),
- (m2m_obj, 442, M2MSelfData, [440, 441]),
- (m2m_obj, 443, M2MSelfData, [445, 446]),
- (m2m_obj, 444, M2MSelfData, [440, 441, 445, 446]),
- (m2m_obj, 445, M2MSelfData, []),
- (m2m_obj, 446, M2MSelfData, []),
-
- (data_obj, 500, Anchor, "Anchor 3"),
- (data_obj, 501, Anchor, "Anchor 4"),
-
- (pk_obj, 601, BooleanPKData, True),
- (pk_obj, 602, BooleanPKData, False),
- (pk_obj, 610, CharPKData, "Test Char PKData"),
-# (pk_obj, 620, DatePKData, datetime.date(2006,6,16)),
-# (pk_obj, 630, DateTimePKData, datetime.datetime(2006,6,16,10,42,37)),
- (pk_obj, 640, EmailPKData, "hovercraft@example.com"),
- (pk_obj, 650, FilePKData, 'file:///foo/bar/whiz.txt'),
- (pk_obj, 660, FilePathPKData, "/foo/bar/whiz.txt"),
- (pk_obj, 670, FloatPKData, 12.345),
- (pk_obj, 671, FloatPKData, -12.345),
- (pk_obj, 672, FloatPKData, 0.0),
- (pk_obj, 680, IntegerPKData, 123456789),
- (pk_obj, 681, IntegerPKData, -123456789),
- (pk_obj, 682, IntegerPKData, 0),
-# (XX, ImagePKData
- (pk_obj, 690, IPAddressPKData, "127.0.0.1"),
- (pk_obj, 700, NullBooleanPKData, True),
- (pk_obj, 701, NullBooleanPKData, False),
- (pk_obj, 710, PhonePKData, "212-634-5789"),
- (pk_obj, 720, PositiveIntegerPKData, 123456789),
- (pk_obj, 730, PositiveSmallIntegerPKData, 12),
- (pk_obj, 740, SlugPKData, "this-is-a-slug"),
- (pk_obj, 750, SmallPKData, 12),
- (pk_obj, 751, SmallPKData, -12),
- (pk_obj, 752, SmallPKData, 0),
-# (pk_obj, 760, TextPKData, """This is a long piece of text.
-# It contains line breaks.
-# Several of them.
-# The end."""),
-# (pk_obj, 770, TimePKData, datetime.time(10,42,37)),
- (pk_obj, 780, USStatePKData, "MA"),
-# (pk_obj, 790, XMLPKData, "<foo></foo>"),
-]
-
-# Dynamically create serializer tests to ensure that all
-# registered serializers are automatically tested.
-class SerializerTests(unittest.TestCase):
- pass
-
-def serializerTest(format, self):
- # Clear the database first
- management.flush(verbosity=0, interactive=False)
-
- # Create all the objects defined in the test data
- objects = []
- transaction.enter_transaction_management()
- transaction.managed(True)
- for (func, pk, klass, datum) in test_data:
- objects.append(func[0](pk, klass, datum))
- transaction.commit()
- transaction.leave_transaction_management()
-
- # Add the generic tagged objects to the object list
- objects.extend(Tag.objects.all())
-
- # Serialize the test database
- serialized_data = serializers.serialize(format, objects, indent=2)
-
- # Flush the database and recreate from the serialized data
- management.flush(verbosity=0, interactive=False)
- transaction.enter_transaction_management()
- transaction.managed(True)
- for obj in serializers.deserialize(format, serialized_data):
- obj.save()
- transaction.commit()
- transaction.leave_transaction_management()
-
- # Assert that the deserialized data is the same
- # as the original source
- for (func, pk, klass, datum) in test_data:
- func[1](self, pk, klass, datum)
-
-for format in serializers.get_serializer_formats():
- setattr(SerializerTests, 'test_'+format+'_serializer', curry(serializerTest, format))
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/string_lookup/models.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,69 +0,0 @@
-from django.db import models
-
-class Foo(models.Model):
- name = models.CharField(maxlength=50)
-
- def __str__(self):
- return "Foo %s" % self.name
-
-class Bar(models.Model):
- name = models.CharField(maxlength=50)
- normal = models.ForeignKey(Foo, related_name='normal_foo')
- fwd = models.ForeignKey("Whiz")
- back = models.ForeignKey("Foo")
-
- def __str__(self):
- return "Bar %s" % self.place.name
-
-class Whiz(models.Model):
- name = models.CharField(maxlength = 50)
-
- def __str__(self):
- return "Whiz %s" % self.name
-
-class Child(models.Model):
- parent = models.OneToOneField('Base')
- name = models.CharField(maxlength = 50)
-
- def __str__(self):
- return "Child %s" % self.name
-
-class Base(models.Model):
- name = models.CharField(maxlength = 50)
-
- def __str__(self):
- return "Base %s" % self.name
-
-__test__ = {'API_TESTS':"""
-# Regression test for #1661 and #1662: Check that string form referencing of models works,
-# both as pre and post reference, on all RelatedField types.
-
->>> f1 = Foo(name="Foo1")
->>> f1.save()
->>> f2 = Foo(name="Foo1")
->>> f2.save()
-
->>> w1 = Whiz(name="Whiz1")
->>> w1.save()
-
->>> b1 = Bar(name="Bar1", normal=f1, fwd=w1, back=f2)
->>> b1.save()
-
->>> b1.normal
-<Foo: Foo Foo1>
-
->>> b1.fwd
-<Whiz: Whiz Whiz1>
-
->>> b1.back
-<Foo: Foo Foo1>
-
->>> base1 = Base(name="Base1")
->>> base1.save()
-
->>> child1 = Child(name="Child1", parent=base1)
->>> child1.save()
-
->>> child1.parent
-<Base: Base Base1>
-"""}
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/templates/tests.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,757 +0,0 @@
-# -*- coding: utf-8 -*-
-from django.conf import settings
-
-if __name__ == '__main__':
- # When running this file in isolation, we need to set up the configuration
- # before importing 'template'.
- settings.configure()
-
-from django import template
-from django.template import loader
-from django.utils.translation import activate, deactivate, install
-from django.utils.tzinfo import LocalTimezone
-from datetime import datetime, timedelta
-import unittest
-
-#################################
-# Custom template tag for tests #
-#################################
-
-register = template.Library()
-
-class EchoNode(template.Node):
- def __init__(self, contents):
- self.contents = contents
-
- def render(self, context):
- return " ".join(self.contents)
-
-def do_echo(parser, token):
- return EchoNode(token.contents.split()[1:])
-
-register.tag("echo", do_echo)
-
-template.libraries['django.templatetags.testtags'] = register
-
-#####################################
-# Helper objects for template tests #
-#####################################
-
-class SomeException(Exception):
- silent_variable_failure = True
-
-class SomeOtherException(Exception):
- pass
-
-class SomeClass:
- def __init__(self):
- self.otherclass = OtherClass()
-
- def method(self):
- return "SomeClass.method"
-
- def method2(self, o):
- return o
-
- def method3(self):
- raise SomeException
-
- def method4(self):
- raise SomeOtherException
-
-class OtherClass:
- def method(self):
- return "OtherClass.method"
-
-class UnicodeInStrClass:
- "Class whose __str__ returns a Unicode object."
- def __str__(self):
- return u'ŠĐĆŽćžšđ'
-
-class Templates(unittest.TestCase):
- def test_templates(self):
- # NOW and NOW_tz are used by timesince tag tests.
- NOW = datetime.now()
- NOW_tz = datetime.now(LocalTimezone(datetime.now()))
-
- # SYNTAX --
- # 'template_name': ('template contents', 'context dict', 'expected string output' or Exception class)
- TEMPLATE_TESTS = {
-
- ### BASIC SYNTAX ##########################################################
-
- # Plain text should go through the template parser untouched
- 'basic-syntax01': ("something cool", {}, "something cool"),
-
- # Variables should be replaced with their value in the current context
- 'basic-syntax02': ("{{ headline }}", {'headline':'Success'}, "Success"),
-
- # More than one replacement variable is allowed in a template
- 'basic-syntax03': ("{{ first }} --- {{ second }}", {"first" : 1, "second" : 2}, "1 --- 2"),
-
- # Fail silently when a variable is not found in the current context
- 'basic-syntax04': ("as{{ missing }}df", {}, ("asdf","asINVALIDdf")),
-
- # A variable may not contain more than one word
- 'basic-syntax06': ("{{ multi word variable }}", {}, template.TemplateSyntaxError),
-
- # Raise TemplateSyntaxError for empty variable tags
- 'basic-syntax07': ("{{ }}", {}, template.TemplateSyntaxError),
- 'basic-syntax08': ("{{ }}", {}, template.TemplateSyntaxError),
-
- # Attribute syntax allows a template to call an object's attribute
- 'basic-syntax09': ("{{ var.method }}", {"var": SomeClass()}, "SomeClass.method"),
-
- # Multiple levels of attribute access are allowed
- 'basic-syntax10': ("{{ var.otherclass.method }}", {"var": SomeClass()}, "OtherClass.method"),
-
- # Fail silently when a variable's attribute isn't found
- 'basic-syntax11': ("{{ var.blech }}", {"var": SomeClass()}, ("","INVALID")),
-
- # Raise TemplateSyntaxError when trying to access a variable beginning with an underscore
- 'basic-syntax12': ("{{ var.__dict__ }}", {"var": SomeClass()}, template.TemplateSyntaxError),
-
- # Raise TemplateSyntaxError when trying to access a variable containing an illegal character
- 'basic-syntax13': ("{{ va>r }}", {}, template.TemplateSyntaxError),
- 'basic-syntax14': ("{{ (var.r) }}", {}, template.TemplateSyntaxError),
- 'basic-syntax15': ("{{ sp%am }}", {}, template.TemplateSyntaxError),
- 'basic-syntax16': ("{{ eggs! }}", {}, template.TemplateSyntaxError),
- 'basic-syntax17': ("{{ moo? }}", {}, template.TemplateSyntaxError),
-
- # Attribute syntax allows a template to call a dictionary key's value
- 'basic-syntax18': ("{{ foo.bar }}", {"foo" : {"bar" : "baz"}}, "baz"),
-
- # Fail silently when a variable's dictionary key isn't found
- 'basic-syntax19': ("{{ foo.spam }}", {"foo" : {"bar" : "baz"}}, ("","INVALID")),
-
- # Fail silently when accessing a non-simple method
- 'basic-syntax20': ("{{ var.method2 }}", {"var": SomeClass()}, ("","INVALID")),
-
- # List-index syntax allows a template to access a certain item of a subscriptable object.
- 'list-index01': ("{{ var.1 }}", {"var": ["first item", "second item"]}, "second item"),
-
- # Fail silently when the list index is out of range.
- 'list-index02': ("{{ var.5 }}", {"var": ["first item", "second item"]}, ("", "INVALID")),
-
- # Fail silently when the variable is not a subscriptable object.
- 'list-index03': ("{{ var.1 }}", {"var": None}, ("", "INVALID")),
-
- # Fail silently when variable is a dict without the specified key.
- 'list-index04': ("{{ var.1 }}", {"var": {}}, ("", "INVALID")),
-
- # Dictionary lookup wins out when dict's key is a string.
- 'list-index05': ("{{ var.1 }}", {"var": {'1': "hello"}}, "hello"),
-
- # But list-index lookup wins out when dict's key is an int, which
- # behind the scenes is really a dictionary lookup (for a dict)
- # after converting the key to an int.
- 'list-index06': ("{{ var.1 }}", {"var": {1: "hello"}}, "hello"),
-
- # Dictionary lookup wins out when there is a string and int version of the key.
- 'list-index07': ("{{ var.1 }}", {"var": {'1': "hello", 1: "world"}}, "hello"),
-
- # Basic filter usage
- 'basic-syntax21': ("{{ var|upper }}", {"var": "Django is the greatest!"}, "DJANGO IS THE GREATEST!"),
-
- # Chained filters
- 'basic-syntax22': ("{{ var|upper|lower }}", {"var": "Django is the greatest!"}, "django is the greatest!"),
-
- # Raise TemplateSyntaxError for space between a variable and filter pipe
- 'basic-syntax23': ("{{ var |upper }}", {}, template.TemplateSyntaxError),
-
- # Raise TemplateSyntaxError for space after a filter pipe
- 'basic-syntax24': ("{{ var| upper }}", {}, template.TemplateSyntaxError),
-
- # Raise TemplateSyntaxError for a nonexistent filter
- 'basic-syntax25': ("{{ var|does_not_exist }}", {}, template.TemplateSyntaxError),
-
- # Raise TemplateSyntaxError when trying to access a filter containing an illegal character
- 'basic-syntax26': ("{{ var|fil(ter) }}", {}, template.TemplateSyntaxError),
-
- # Raise TemplateSyntaxError for invalid block tags
- 'basic-syntax27': ("{% nothing_to_see_here %}", {}, template.TemplateSyntaxError),
-
- # Raise TemplateSyntaxError for empty block tags
- 'basic-syntax28': ("{% %}", {}, template.TemplateSyntaxError),
-
- # Chained filters, with an argument to the first one
- 'basic-syntax29': ('{{ var|removetags:"b i"|upper|lower }}', {"var": "<b><i>Yes</i></b>"}, "yes"),
-
- # Escaped string as argument
- 'basic-syntax30': (r'{{ var|default_if_none:" endquote\" hah" }}', {"var": None}, ' endquote" hah'),
-
- # Variable as argument
- 'basic-syntax31': (r'{{ var|default_if_none:var2 }}', {"var": None, "var2": "happy"}, 'happy'),
-
- # Default argument testing
- 'basic-syntax32': (r'{{ var|yesno:"yup,nup,mup" }} {{ var|yesno }}', {"var": True}, 'yup yes'),
-
- # Fail silently for methods that raise an exception with a "silent_variable_failure" attribute
- 'basic-syntax33': (r'1{{ var.method3 }}2', {"var": SomeClass()}, ("12", "1INVALID2")),
-
- # In methods that raise an exception without a "silent_variable_attribute" set to True,
- # the exception propagates
- 'basic-syntax34': (r'1{{ var.method4 }}2', {"var": SomeClass()}, SomeOtherException),
-
- # Escaped backslash in argument
- 'basic-syntax35': (r'{{ var|default_if_none:"foo\bar" }}', {"var": None}, r'foo\bar'),
-
- # Escaped backslash using known escape char
- 'basic-syntax35': (r'{{ var|default_if_none:"foo\now" }}', {"var": None}, r'foo\now'),
-
- # Empty strings can be passed as arguments to filters
- 'basic-syntax36': (r'{{ var|join:"" }}', {'var': ['a', 'b', 'c']}, 'abc'),
-
- # If a variable has a __str__() that returns a Unicode object, the value
- # will be converted to a bytestring.
- 'basic-syntax37': (r'{{ var }}', {'var': UnicodeInStrClass()}, '\xc5\xa0\xc4\x90\xc4\x86\xc5\xbd\xc4\x87\xc5\xbe\xc5\xa1\xc4\x91'),
-
- ### COMMENT SYNTAX ########################################################
- 'comment-syntax01': ("{# this is hidden #}hello", {}, "hello"),
- 'comment-syntax02': ("{# this is hidden #}hello{# foo #}", {}, "hello"),
-
- # Comments can contain invalid stuff.
- 'comment-syntax03': ("foo{# {% if %} #}", {}, "foo"),
- 'comment-syntax04': ("foo{# {% endblock %} #}", {}, "foo"),
- 'comment-syntax05': ("foo{# {% somerandomtag %} #}", {}, "foo"),
- 'comment-syntax06': ("foo{# {% #}", {}, "foo"),
- 'comment-syntax07': ("foo{# %} #}", {}, "foo"),
- 'comment-syntax08': ("foo{# %} #}bar", {}, "foobar"),
- 'comment-syntax09': ("foo{# {{ #}", {}, "foo"),
- 'comment-syntax10': ("foo{# }} #}", {}, "foo"),
- 'comment-syntax11': ("foo{# { #}", {}, "foo"),
- 'comment-syntax12': ("foo{# } #}", {}, "foo"),
-
- ### COMMENT TAG ###########################################################
- 'comment-tag01': ("{% comment %}this is hidden{% endcomment %}hello", {}, "hello"),
- 'comment-tag02': ("{% comment %}this is hidden{% endcomment %}hello{% comment %}foo{% endcomment %}", {}, "hello"),
-
- # Comment tag can contain invalid stuff.
- 'comment-tag03': ("foo{% comment %} {% if %} {% endcomment %}", {}, "foo"),
- 'comment-tag04': ("foo{% comment %} {% endblock %} {% endcomment %}", {}, "foo"),
- 'comment-tag05': ("foo{% comment %} {% somerandomtag %} {% endcomment %}", {}, "foo"),
-
- ### CYCLE TAG #############################################################
- 'cycle01': ('{% cycle a %}', {}, template.TemplateSyntaxError),
- 'cycle02': ('{% cycle a,b,c as abc %}{% cycle abc %}', {}, 'ab'),
- 'cycle03': ('{% cycle a,b,c as abc %}{% cycle abc %}{% cycle abc %}', {}, 'abc'),
- 'cycle04': ('{% cycle a,b,c as abc %}{% cycle abc %}{% cycle abc %}{% cycle abc %}', {}, 'abca'),
- 'cycle05': ('{% cycle %}', {}, template.TemplateSyntaxError),
- 'cycle06': ('{% cycle a %}', {}, template.TemplateSyntaxError),
- 'cycle07': ('{% cycle a,b,c as foo %}{% cycle bar %}', {}, template.TemplateSyntaxError),
- 'cycle08': ('{% cycle a,b,c as foo %}{% cycle foo %}{{ foo }}{{ foo }}{% cycle foo %}{{ foo }}', {}, 'abbbcc'),
-
- ### EXCEPTIONS ############################################################
-
- # Raise exception for invalid template name
- 'exception01': ("{% extends 'nonexistent' %}", {}, template.TemplateSyntaxError),
-
- # Raise exception for invalid template name (in variable)
- 'exception02': ("{% extends nonexistent %}", {}, template.TemplateSyntaxError),
-
- # Raise exception for extra {% extends %} tags
- 'exception03': ("{% extends 'inheritance01' %}{% block first %}2{% endblock %}{% extends 'inheritance16' %}", {}, template.TemplateSyntaxError),
-
- # Raise exception for custom tags used in child with {% load %} tag in parent, not in child
- 'exception04': ("{% extends 'inheritance17' %}{% block first %}{% echo 400 %}5678{% endblock %}", {}, template.TemplateSyntaxError),
-
- ### FILTER TAG ############################################################
- 'filter01': ('{% filter upper %}{% endfilter %}', {}, ''),
- 'filter02': ('{% filter upper %}django{% endfilter %}', {}, 'DJANGO'),
- 'filter03': ('{% filter upper|lower %}django{% endfilter %}', {}, 'django'),
-
- ### FIRSTOF TAG ###########################################################
- 'firstof01': ('{% firstof a b c %}', {'a':0,'b':0,'c':0}, ''),
- 'firstof02': ('{% firstof a b c %}', {'a':1,'b':0,'c':0}, '1'),
- 'firstof03': ('{% firstof a b c %}', {'a':0,'b':2,'c':0}, '2'),
- 'firstof04': ('{% firstof a b c %}', {'a':0,'b':0,'c':3}, '3'),
- 'firstof05': ('{% firstof a b c %}', {'a':1,'b':2,'c':3}, '1'),
- 'firstof06': ('{% firstof %}', {}, template.TemplateSyntaxError),
-
- ### FOR TAG ###############################################################
- 'for-tag01': ("{% for val in values %}{{ val }}{% endfor %}", {"values": [1, 2, 3]}, "123"),
- 'for-tag02': ("{% for val in values reversed %}{{ val }}{% endfor %}", {"values": [1, 2, 3]}, "321"),
- 'for-tag-vars01': ("{% for val in values %}{{ forloop.counter }}{% endfor %}", {"values": [6, 6, 6]}, "123"),
- 'for-tag-vars02': ("{% for val in values %}{{ forloop.counter0 }}{% endfor %}", {"values": [6, 6, 6]}, "012"),
- 'for-tag-vars03': ("{% for val in values %}{{ forloop.revcounter }}{% endfor %}", {"values": [6, 6, 6]}, "321"),
- 'for-tag-vars04': ("{% for val in values %}{{ forloop.revcounter0 }}{% endfor %}", {"values": [6, 6, 6]}, "210"),
-
- ### IF TAG ################################################################
- 'if-tag01': ("{% if foo %}yes{% else %}no{% endif %}", {"foo": True}, "yes"),
- 'if-tag02': ("{% if foo %}yes{% else %}no{% endif %}", {"foo": False}, "no"),
- 'if-tag03': ("{% if foo %}yes{% else %}no{% endif %}", {}, "no"),
-
- # AND
- 'if-tag-and01': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'yes'),
- 'if-tag-and02': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'no'),
- 'if-tag-and03': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'no'),
- 'if-tag-and04': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'no'),
- 'if-tag-and05': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': False}, 'no'),
- 'if-tag-and06': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'bar': False}, 'no'),
- 'if-tag-and07': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': True}, 'no'),
- 'if-tag-and08': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'bar': True}, 'no'),
-
- # OR
- 'if-tag-or01': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'yes'),
- 'if-tag-or02': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'yes'),
- 'if-tag-or03': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'yes'),
- 'if-tag-or04': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'no'),
- 'if-tag-or05': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': False}, 'no'),
- 'if-tag-or06': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'bar': False}, 'no'),
- 'if-tag-or07': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'foo': True}, 'yes'),
- 'if-tag-or08': ("{% if foo or bar %}yes{% else %}no{% endif %}", {'bar': True}, 'yes'),
-
- # TODO: multiple ORs
-
- # NOT
- 'if-tag-not01': ("{% if not foo %}no{% else %}yes{% endif %}", {'foo': True}, 'yes'),
- 'if-tag-not02': ("{% if not %}yes{% else %}no{% endif %}", {'foo': True}, 'no'),
- 'if-tag-not03': ("{% if not %}yes{% else %}no{% endif %}", {'not': True}, 'yes'),
- 'if-tag-not04': ("{% if not not %}no{% else %}yes{% endif %}", {'not': True}, 'yes'),
- 'if-tag-not05': ("{% if not not %}no{% else %}yes{% endif %}", {}, 'no'),
-
- 'if-tag-not06': ("{% if foo and not bar %}yes{% else %}no{% endif %}", {}, 'no'),
- 'if-tag-not07': ("{% if foo and not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'no'),
- 'if-tag-not08': ("{% if foo and not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'yes'),
- 'if-tag-not09': ("{% if foo and not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'no'),
- 'if-tag-not10': ("{% if foo and not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'no'),
-
- 'if-tag-not11': ("{% if not foo and bar %}yes{% else %}no{% endif %}", {}, 'no'),
- 'if-tag-not12': ("{% if not foo and bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'no'),
- 'if-tag-not13': ("{% if not foo and bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'no'),
- 'if-tag-not14': ("{% if not foo and bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'yes'),
- 'if-tag-not15': ("{% if not foo and bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'no'),
-
- 'if-tag-not16': ("{% if foo or not bar %}yes{% else %}no{% endif %}", {}, 'yes'),
- 'if-tag-not17': ("{% if foo or not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'yes'),
- 'if-tag-not18': ("{% if foo or not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'yes'),
- 'if-tag-not19': ("{% if foo or not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'no'),
- 'if-tag-not20': ("{% if foo or not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'yes'),
-
- 'if-tag-not21': ("{% if not foo or bar %}yes{% else %}no{% endif %}", {}, 'yes'),
- 'if-tag-not22': ("{% if not foo or bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'yes'),
- 'if-tag-not23': ("{% if not foo or bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'no'),
- 'if-tag-not24': ("{% if not foo or bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'yes'),
- 'if-tag-not25': ("{% if not foo or bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'yes'),
-
- 'if-tag-not26': ("{% if not foo and not bar %}yes{% else %}no{% endif %}", {}, 'yes'),
- 'if-tag-not27': ("{% if not foo and not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'no'),
- 'if-tag-not28': ("{% if not foo and not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'no'),
- 'if-tag-not29': ("{% if not foo and not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'no'),
- 'if-tag-not30': ("{% if not foo and not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'yes'),
-
- 'if-tag-not31': ("{% if not foo or not bar %}yes{% else %}no{% endif %}", {}, 'yes'),
- 'if-tag-not32': ("{% if not foo or not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'no'),
- 'if-tag-not33': ("{% if not foo or not bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': False}, 'yes'),
- 'if-tag-not34': ("{% if not foo or not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': True}, 'yes'),
- 'if-tag-not35': ("{% if not foo or not bar %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, 'yes'),
-
- # AND and OR raises a TemplateSyntaxError
- 'if-tag-error01': ("{% if foo or bar and baz %}yes{% else %}no{% endif %}", {'foo': False, 'bar': False}, template.TemplateSyntaxError),
- 'if-tag-error02': ("{% if foo and %}yes{% else %}no{% endif %}", {'foo': True}, template.TemplateSyntaxError),
- 'if-tag-error03': ("{% if foo or %}yes{% else %}no{% endif %}", {'foo': True}, template.TemplateSyntaxError),
- 'if-tag-error04': ("{% if not foo and %}yes{% else %}no{% endif %}", {'foo': True}, template.TemplateSyntaxError),
- 'if-tag-error05': ("{% if not foo or %}yes{% else %}no{% endif %}", {'foo': True}, template.TemplateSyntaxError),
-
- ### IFCHANGED TAG #########################################################
- 'ifchanged01': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}', { 'num': (1,2,3) }, '123'),
- 'ifchanged02': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}', { 'num': (1,1,3) }, '13'),
- 'ifchanged03': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}', { 'num': (1,1,1) }, '1'),
- 'ifchanged04': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}{% endfor %}{% endfor %}', { 'num': (1, 2, 3), 'numx': (2, 2, 2)}, '122232'),
- 'ifchanged05': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}{% endfor %}{% endfor %}', { 'num': (1, 1, 1), 'numx': (1, 2, 3)}, '1123123123'),
- 'ifchanged06': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}{% endfor %}{% endfor %}', { 'num': (1, 1, 1), 'numx': (2, 2, 2)}, '1222'),
- 'ifchanged07': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}{% for y in numy %}{% ifchanged %}{{ y }}{% endifchanged %}{% endfor %}{% endfor %}{% endfor %}', { 'num': (1, 1, 1), 'numx': (2, 2, 2), 'numy': (3, 3, 3)}, '1233323332333'),
-
- # Test one parameter given to ifchanged.
- 'ifchanged-param01': ('{% for n in num %}{% ifchanged n %}..{% endifchanged %}{{ n }}{% endfor %}', { 'num': (1,2,3) }, '..1..2..3'),
- 'ifchanged-param02': ('{% for n in num %}{% for x in numx %}{% ifchanged n %}..{% endifchanged %}{{ x }}{% endfor %}{% endfor %}', { 'num': (1,2,3), 'numx': (5,6,7) }, '..567..567..567'),
-
- # Test multiple parameters to ifchanged.
- 'ifchanged-param03': ('{% for n in num %}{{ n }}{% for x in numx %}{% ifchanged x n %}{{ x }}{% endifchanged %}{% endfor %}{% endfor %}', { 'num': (1,1,2), 'numx': (5,6,6) }, '156156256'),
-
- # Test a date+hour like construct, where the hour of the last day
- # is the same but the date had changed, so print the hour anyway.
- 'ifchanged-param04': ('{% for d in days %}{% ifchanged %}{{ d.day }}{% endifchanged %}{% for h in d.hours %}{% ifchanged d h %}{{ h }}{% endifchanged %}{% endfor %}{% endfor %}', {'days':[{'day':1, 'hours':[1,2,3]},{'day':2, 'hours':[3]},] }, '112323'),
-
- # Logically the same as above, just written with explicit
- # ifchanged for the day.
- 'ifchanged-param04': ('{% for d in days %}{% ifchanged d.day %}{{ d.day }}{% endifchanged %}{% for h in d.hours %}{% ifchanged d.day h %}{{ h }}{% endifchanged %}{% endfor %}{% endfor %}', {'days':[{'day':1, 'hours':[1,2,3]},{'day':2, 'hours':[3]},] }, '112323'),
-
- ### IFEQUAL TAG ###########################################################
- 'ifequal01': ("{% ifequal a b %}yes{% endifequal %}", {"a": 1, "b": 2}, ""),
- 'ifequal02': ("{% ifequal a b %}yes{% endifequal %}", {"a": 1, "b": 1}, "yes"),
- 'ifequal03': ("{% ifequal a b %}yes{% else %}no{% endifequal %}", {"a": 1, "b": 2}, "no"),
- 'ifequal04': ("{% ifequal a b %}yes{% else %}no{% endifequal %}", {"a": 1, "b": 1}, "yes"),
- 'ifequal05': ("{% ifequal a 'test' %}yes{% else %}no{% endifequal %}", {"a": "test"}, "yes"),
- 'ifequal06': ("{% ifequal a 'test' %}yes{% else %}no{% endifequal %}", {"a": "no"}, "no"),
- 'ifequal07': ('{% ifequal a "test" %}yes{% else %}no{% endifequal %}', {"a": "test"}, "yes"),
- 'ifequal08': ('{% ifequal a "test" %}yes{% else %}no{% endifequal %}', {"a": "no"}, "no"),
- 'ifequal09': ('{% ifequal a "test" %}yes{% else %}no{% endifequal %}', {}, "no"),
- 'ifequal10': ('{% ifequal a b %}yes{% else %}no{% endifequal %}', {}, "yes"),
-
- # SMART SPLITTING
- 'ifequal-split01': ('{% ifequal a "test man" %}yes{% else %}no{% endifequal %}', {}, "no"),
- 'ifequal-split02': ('{% ifequal a "test man" %}yes{% else %}no{% endifequal %}', {'a': 'foo'}, "no"),
- 'ifequal-split03': ('{% ifequal a "test man" %}yes{% else %}no{% endifequal %}', {'a': 'test man'}, "yes"),
- 'ifequal-split04': ("{% ifequal a 'test man' %}yes{% else %}no{% endifequal %}", {'a': 'test man'}, "yes"),
- 'ifequal-split05': ("{% ifequal a 'i \"love\" you' %}yes{% else %}no{% endifequal %}", {'a': ''}, "no"),
- 'ifequal-split06': ("{% ifequal a 'i \"love\" you' %}yes{% else %}no{% endifequal %}", {'a': 'i "love" you'}, "yes"),
- 'ifequal-split07': ("{% ifequal a 'i \"love\" you' %}yes{% else %}no{% endifequal %}", {'a': 'i love you'}, "no"),
- 'ifequal-split08': (r"{% ifequal a 'I\'m happy' %}yes{% else %}no{% endifequal %}", {'a': "I'm happy"}, "yes"),
- 'ifequal-split09': (r"{% ifequal a 'slash\man' %}yes{% else %}no{% endifequal %}", {'a': r"slash\man"}, "yes"),
- 'ifequal-split10': (r"{% ifequal a 'slash\man' %}yes{% else %}no{% endifequal %}", {'a': r"slashman"}, "no"),
-
- # NUMERIC RESOLUTION
- 'ifequal-numeric01': ('{% ifequal x 5 %}yes{% endifequal %}', {'x': '5'}, ''),
- 'ifequal-numeric02': ('{% ifequal x 5 %}yes{% endifequal %}', {'x': 5}, 'yes'),
- 'ifequal-numeric03': ('{% ifequal x 5.2 %}yes{% endifequal %}', {'x': 5}, ''),
- 'ifequal-numeric04': ('{% ifequal x 5.2 %}yes{% endifequal %}', {'x': 5.2}, 'yes'),
- 'ifequal-numeric05': ('{% ifequal x 0.2 %}yes{% endifequal %}', {'x': .2}, 'yes'),
- 'ifequal-numeric06': ('{% ifequal x .2 %}yes{% endifequal %}', {'x': .2}, 'yes'),
- 'ifequal-numeric07': ('{% ifequal x 2. %}yes{% endifequal %}', {'x': 2}, ''),
- 'ifequal-numeric08': ('{% ifequal x "5" %}yes{% endifequal %}', {'x': 5}, ''),
- 'ifequal-numeric09': ('{% ifequal x "5" %}yes{% endifequal %}', {'x': '5'}, 'yes'),
- 'ifequal-numeric10': ('{% ifequal x -5 %}yes{% endifequal %}', {'x': -5}, 'yes'),
- 'ifequal-numeric11': ('{% ifequal x -5.2 %}yes{% endifequal %}', {'x': -5.2}, 'yes'),
- 'ifequal-numeric12': ('{% ifequal x +5 %}yes{% endifequal %}', {'x': 5}, 'yes'),
-
- ### IFNOTEQUAL TAG ########################################################
- 'ifnotequal01': ("{% ifnotequal a b %}yes{% endifnotequal %}", {"a": 1, "b": 2}, "yes"),
- 'ifnotequal02': ("{% ifnotequal a b %}yes{% endifnotequal %}", {"a": 1, "b": 1}, ""),
- 'ifnotequal03': ("{% ifnotequal a b %}yes{% else %}no{% endifnotequal %}", {"a": 1, "b": 2}, "yes"),
- 'ifnotequal04': ("{% ifnotequal a b %}yes{% else %}no{% endifnotequal %}", {"a": 1, "b": 1}, "no"),
-
- ### INCLUDE TAG ###########################################################
- 'include01': ('{% include "basic-syntax01" %}', {}, "something cool"),
- 'include02': ('{% include "basic-syntax02" %}', {'headline': 'Included'}, "Included"),
- 'include03': ('{% include template_name %}', {'template_name': 'basic-syntax02', 'headline': 'Included'}, "Included"),
- 'include04': ('a{% include "nonexistent" %}b', {}, "ab"),
-
- ### NAMED ENDBLOCKS #######################################################
-
- # Basic test
- 'namedendblocks01': ("1{% block first %}_{% block second %}2{% endblock second %}_{% endblock first %}3", {}, '1_2_3'),
-
- # Unbalanced blocks
- 'namedendblocks02': ("1{% block first %}_{% block second %}2{% endblock first %}_{% endblock second %}3", {}, template.TemplateSyntaxError),
- 'namedendblocks03': ("1{% block first %}_{% block second %}2{% endblock %}_{% endblock second %}3", {}, template.TemplateSyntaxError),
- 'namedendblocks04': ("1{% block first %}_{% block second %}2{% endblock second %}_{% endblock third %}3", {}, template.TemplateSyntaxError),
- 'namedendblocks05': ("1{% block first %}_{% block second %}2{% endblock first %}", {}, template.TemplateSyntaxError),
-
- # Mixed named and unnamed endblocks
- 'namedendblocks06': ("1{% block first %}_{% block second %}2{% endblock %}_{% endblock first %}3", {}, '1_2_3'),
- 'namedendblocks07': ("1{% block first %}_{% block second %}2{% endblock second %}_{% endblock %}3", {}, '1_2_3'),
-
- ### INHERITANCE ###########################################################
-
- # Standard template with no inheritance
- 'inheritance01': ("1{% block first %}_{% endblock %}3{% block second %}_{% endblock %}", {}, '1_3_'),
-
- # Standard two-level inheritance
- 'inheritance02': ("{% extends 'inheritance01' %}{% block first %}2{% endblock %}{% block second %}4{% endblock %}", {}, '1234'),
-
- # Three-level with no redefinitions on third level
- 'inheritance03': ("{% extends 'inheritance02' %}", {}, '1234'),
-
- # Two-level with no redefinitions on second level
- 'inheritance04': ("{% extends 'inheritance01' %}", {}, '1_3_'),
-
- # Two-level with double quotes instead of single quotes
- 'inheritance05': ('{% extends "inheritance02" %}', {}, '1234'),
-
- # Three-level with variable parent-template name
- 'inheritance06': ("{% extends foo %}", {'foo': 'inheritance02'}, '1234'),
-
- # Two-level with one block defined, one block not defined
- 'inheritance07': ("{% extends 'inheritance01' %}{% block second %}5{% endblock %}", {}, '1_35'),
-
- # Three-level with one block defined on this level, two blocks defined next level
- 'inheritance08': ("{% extends 'inheritance02' %}{% block second %}5{% endblock %}", {}, '1235'),
-
- # Three-level with second and third levels blank
- 'inheritance09': ("{% extends 'inheritance04' %}", {}, '1_3_'),
-
- # Three-level with space NOT in a block -- should be ignored
- 'inheritance10': ("{% extends 'inheritance04' %} ", {}, '1_3_'),
-
- # Three-level with both blocks defined on this level, but none on second level
- 'inheritance11': ("{% extends 'inheritance04' %}{% block first %}2{% endblock %}{% block second %}4{% endblock %}", {}, '1234'),
-
- # Three-level with this level providing one and second level providing the other
- 'inheritance12': ("{% extends 'inheritance07' %}{% block first %}2{% endblock %}", {}, '1235'),
-
- # Three-level with this level overriding second level
- 'inheritance13': ("{% extends 'inheritance02' %}{% block first %}a{% endblock %}{% block second %}b{% endblock %}", {}, '1a3b'),
-
- # A block defined only in a child template shouldn't be displayed
- 'inheritance14': ("{% extends 'inheritance01' %}{% block newblock %}NO DISPLAY{% endblock %}", {}, '1_3_'),
-
- # A block within another block
- 'inheritance15': ("{% extends 'inheritance01' %}{% block first %}2{% block inner %}inner{% endblock %}{% endblock %}", {}, '12inner3_'),
-
- # A block within another block (level 2)
- 'inheritance16': ("{% extends 'inheritance15' %}{% block inner %}out{% endblock %}", {}, '12out3_'),
-
- # {% load %} tag (parent -- setup for exception04)
- 'inheritance17': ("{% load testtags %}{% block first %}1234{% endblock %}", {}, '1234'),
-
- # {% load %} tag (standard usage, without inheritance)
- 'inheritance18': ("{% load testtags %}{% echo this that theother %}5678", {}, 'this that theother5678'),
-
- # {% load %} tag (within a child template)
- 'inheritance19': ("{% extends 'inheritance01' %}{% block first %}{% load testtags %}{% echo 400 %}5678{% endblock %}", {}, '140056783_'),
-
- # Two-level inheritance with {{ block.super }}
- 'inheritance20': ("{% extends 'inheritance01' %}{% block first %}{{ block.super }}a{% endblock %}", {}, '1_a3_'),
-
- # Three-level inheritance with {{ block.super }} from parent
- 'inheritance21': ("{% extends 'inheritance02' %}{% block first %}{{ block.super }}a{% endblock %}", {}, '12a34'),
-
- # Three-level inheritance with {{ block.super }} from grandparent
- 'inheritance22': ("{% extends 'inheritance04' %}{% block first %}{{ block.super }}a{% endblock %}", {}, '1_a3_'),
-
- # Three-level inheritance with {{ block.super }} from parent and grandparent
- 'inheritance23': ("{% extends 'inheritance20' %}{% block first %}{{ block.super }}b{% endblock %}", {}, '1_ab3_'),
-
- # Inheritance from local context without use of template loader
- 'inheritance24': ("{% extends context_template %}{% block first %}2{% endblock %}{% block second %}4{% endblock %}", {'context_template': template.Template("1{% block first %}_{% endblock %}3{% block second %}_{% endblock %}")}, '1234'),
-
- # Inheritance from local context with variable parent template
- 'inheritance25': ("{% extends context_template.1 %}{% block first %}2{% endblock %}{% block second %}4{% endblock %}", {'context_template': [template.Template("Wrong"), template.Template("1{% block first %}_{% endblock %}3{% block second %}_{% endblock %}")]}, '1234'),
-
- ### I18N ##################################################################
-
- # {% spaceless %} tag
- 'spaceless01': ("{% spaceless %} <b> <i> text </i> </b> {% endspaceless %}", {}, "<b> <i> text </i> </b>"),
- 'spaceless02': ("{% spaceless %} <b> \n <i> text </i> \n </b> {% endspaceless %}", {}, "<b> <i> text </i> </b>"),
- 'spaceless03': ("{% spaceless %}<b><i>text</i></b>{% endspaceless %}", {}, "<b><i>text</i></b>"),
-
- # simple translation of a string delimited by '
- 'i18n01': ("{% load i18n %}{% trans 'xxxyyyxxx' %}", {}, "xxxyyyxxx"),
-
- # simple translation of a string delimited by "
- 'i18n02': ('{% load i18n %}{% trans "xxxyyyxxx" %}', {}, "xxxyyyxxx"),
-
- # simple translation of a variable
- 'i18n03': ('{% load i18n %}{% blocktrans %}{{ anton }}{% endblocktrans %}', {'anton': 'xxxyyyxxx'}, "xxxyyyxxx"),
-
- # simple translation of a variable and filter
- 'i18n04': ('{% load i18n %}{% blocktrans with anton|lower as berta %}{{ berta }}{% endblocktrans %}', {'anton': 'XXXYYYXXX'}, "xxxyyyxxx"),
-
- # simple translation of a string with interpolation
- 'i18n05': ('{% load i18n %}{% blocktrans %}xxx{{ anton }}xxx{% endblocktrans %}', {'anton': 'yyy'}, "xxxyyyxxx"),
-
- # simple translation of a string to german
- 'i18n06': ('{% load i18n %}{% trans "Page not found" %}', {'LANGUAGE_CODE': 'de'}, "Seite nicht gefunden"),
-
- # translation of singular form
- 'i18n07': ('{% load i18n %}{% blocktrans count number as counter %}singular{% plural %}plural{% endblocktrans %}', {'number': 1}, "singular"),
-
- # translation of plural form
- 'i18n08': ('{% load i18n %}{% blocktrans count number as counter %}singular{% plural %}plural{% endblocktrans %}', {'number': 2}, "plural"),
-
- # simple non-translation (only marking) of a string to german
- 'i18n09': ('{% load i18n %}{% trans "Page not found" noop %}', {'LANGUAGE_CODE': 'de'}, "Page not found"),
-
- # translation of a variable with a translated filter
- 'i18n10': ('{{ bool|yesno:_("ja,nein") }}', {'bool': True}, 'ja'),
-
- # translation of a variable with a non-translated filter
- 'i18n11': ('{{ bool|yesno:"ja,nein" }}', {'bool': True}, 'ja'),
-
- # usage of the get_available_languages tag
- 'i18n12': ('{% load i18n %}{% get_available_languages as langs %}{% for lang in langs %}{% ifequal lang.0 "de" %}{{ lang.0 }}{% endifequal %}{% endfor %}', {}, 'de'),
-
- # translation of a constant string
- 'i18n13': ('{{ _("Page not found") }}', {'LANGUAGE_CODE': 'de'}, 'Seite nicht gefunden'),
-
- ### HANDLING OF TEMPLATE_TAG_IF_INVALID ###################################
-
- 'invalidstr01': ('{{ var|default:"Foo" }}', {}, ('Foo','INVALID')),
- 'invalidstr02': ('{{ var|default_if_none:"Foo" }}', {}, ('','INVALID')),
- 'invalidstr03': ('{% for v in var %}({{ v }}){% endfor %}', {}, ''),
- 'invalidstr04': ('{% if var %}Yes{% else %}No{% endif %}', {}, 'No'),
- 'invalidstr04': ('{% if var|default:"Foo" %}Yes{% else %}No{% endif %}', {}, 'Yes'),
-
- ### MULTILINE #############################################################
-
- 'multiline01': ("""
- Hello,
- boys.
- How
- are
- you
- gentlemen.
- """,
- {},
- """
- Hello,
- boys.
- How
- are
- you
- gentlemen.
- """),
-
- ### REGROUP TAG ###########################################################
- 'regroup01': ('{% regroup data by bar as grouped %}' + \
- '{% for group in grouped %}' + \
- '{{ group.grouper }}:' + \
- '{% for item in group.list %}' + \
- '{{ item.foo }}' + \
- '{% endfor %},' + \
- '{% endfor %}',
- {'data': [ {'foo':'c', 'bar':1},
- {'foo':'d', 'bar':1},
- {'foo':'a', 'bar':2},
- {'foo':'b', 'bar':2},
- {'foo':'x', 'bar':3} ]},
- '1:cd,2:ab,3:x,'),
-
- # Test for silent failure when target variable isn't found
- 'regroup02': ('{% regroup data by bar as grouped %}' + \
- '{% for group in grouped %}' + \
- '{{ group.grouper }}:' + \
- '{% for item in group.list %}' + \
- '{{ item.foo }}' + \
- '{% endfor %},' + \
- '{% endfor %}',
- {}, ''),
-
- ### TEMPLATETAG TAG #######################################################
- 'templatetag01': ('{% templatetag openblock %}', {}, '{%'),
- 'templatetag02': ('{% templatetag closeblock %}', {}, '%}'),
- 'templatetag03': ('{% templatetag openvariable %}', {}, '{{'),
- 'templatetag04': ('{% templatetag closevariable %}', {}, '}}'),
- 'templatetag05': ('{% templatetag %}', {}, template.TemplateSyntaxError),
- 'templatetag06': ('{% templatetag foo %}', {}, template.TemplateSyntaxError),
- 'templatetag07': ('{% templatetag openbrace %}', {}, '{'),
- 'templatetag08': ('{% templatetag closebrace %}', {}, '}'),
- 'templatetag09': ('{% templatetag openbrace %}{% templatetag openbrace %}', {}, '{{'),
- 'templatetag10': ('{% templatetag closebrace %}{% templatetag closebrace %}', {}, '}}'),
- 'templatetag11': ('{% templatetag opencomment %}', {}, '{#'),
- 'templatetag12': ('{% templatetag closecomment %}', {}, '#}'),
-
- ### WIDTHRATIO TAG ########################################################
- 'widthratio01': ('{% widthratio a b 0 %}', {'a':50,'b':100}, '0'),
- 'widthratio02': ('{% widthratio a b 100 %}', {'a':0,'b':0}, ''),
- 'widthratio03': ('{% widthratio a b 100 %}', {'a':0,'b':100}, '0'),
- 'widthratio04': ('{% widthratio a b 100 %}', {'a':50,'b':100}, '50'),
- 'widthratio05': ('{% widthratio a b 100 %}', {'a':100,'b':100}, '100'),
-
- # 62.5 should round to 63
- 'widthratio06': ('{% widthratio a b 100 %}', {'a':50,'b':80}, '63'),
-
- # 71.4 should round to 71
- 'widthratio07': ('{% widthratio a b 100 %}', {'a':50,'b':70}, '71'),
-
- # Raise exception if we don't have 3 args, last one an integer
- 'widthratio08': ('{% widthratio %}', {}, template.TemplateSyntaxError),
- 'widthratio09': ('{% widthratio a b %}', {'a':50,'b':100}, template.TemplateSyntaxError),
- 'widthratio10': ('{% widthratio a b 100.0 %}', {'a':50,'b':100}, template.TemplateSyntaxError),
-
- ### NOW TAG ########################################################
- # Simple case
- 'now01' : ('{% now "j n Y"%}', {}, str(datetime.now().day) + ' ' + str(datetime.now().month) + ' ' + str(datetime.now().year)),
-
- # Check parsing of escaped and special characters
- 'now02' : ('{% now "j "n" Y"%}', {}, template.TemplateSyntaxError),
- # 'now03' : ('{% now "j \"n\" Y"%}', {}, str(datetime.now().day) + '"' + str(datetime.now().month) + '"' + str(datetime.now().year)),
- # 'now04' : ('{% now "j \nn\n Y"%}', {}, str(datetime.now().day) + '\n' + str(datetime.now().month) + '\n' + str(datetime.now().year))
-
- ### TIMESINCE TAG ##################################################
- # Default compare with datetime.now()
- 'timesince01' : ('{{ a|timesince }}', {'a':datetime.now() + timedelta(minutes=-1, seconds = -10)}, '1 minute'),
- 'timesince02' : ('{{ a|timesince }}', {'a':(datetime.now() - timedelta(days=1, minutes = 1))}, '1 day'),
- 'timesince03' : ('{{ a|timesince }}', {'a':(datetime.now() -
- timedelta(hours=1, minutes=25, seconds = 10))}, '1 hour, 25 minutes'),
-
- # Compare to a given parameter
- 'timesince04' : ('{{ a|timesince:b }}', {'a':NOW + timedelta(days=2), 'b':NOW + timedelta(days=1)}, '1 day'),
- 'timesince05' : ('{{ a|timesince:b }}', {'a':NOW + timedelta(days=2, minutes=1), 'b':NOW + timedelta(days=2)}, '1 minute'),
-
- # Check that timezone is respected
- 'timesince06' : ('{{ a|timesince:b }}', {'a':NOW_tz + timedelta(hours=8), 'b':NOW_tz}, '8 hours'),
-
- ### TIMEUNTIL TAG ##################################################
- # Default compare with datetime.now()
- 'timeuntil01' : ('{{ a|timeuntil }}', {'a':datetime.now() + timedelta(minutes=2, seconds = 10)}, '2 minutes'),
- 'timeuntil02' : ('{{ a|timeuntil }}', {'a':(datetime.now() + timedelta(days=1, seconds = 10))}, '1 day'),
- 'timeuntil03' : ('{{ a|timeuntil }}', {'a':(datetime.now() + timedelta(hours=8, minutes=10, seconds = 10))}, '8 hours, 10 minutes'),
-
- # Compare to a given parameter
- 'timeuntil04' : ('{{ a|timeuntil:b }}', {'a':NOW - timedelta(days=1), 'b':NOW - timedelta(days=2)}, '1 day'),
- 'timeuntil05' : ('{{ a|timeuntil:b }}', {'a':NOW - timedelta(days=2), 'b':NOW - timedelta(days=2, minutes=1)}, '1 minute'),
-
- ### URL TAG ########################################################
- # Successes
- 'url01' : ('{% url regressiontests.templates.views.client client.id %}', {'client': {'id': 1}}, '/url_tag/client/1/'),
- 'url02' : ('{% url regressiontests.templates.views.client_action client.id,action="update" %}', {'client': {'id': 1}}, '/url_tag/client/1/update/'),
- 'url03' : ('{% url regressiontests.templates.views.index %}', {}, '/url_tag/'),
-
- # Failures
- 'url04' : ('{% url %}', {}, template.TemplateSyntaxError),
- 'url05' : ('{% url no_such_view %}', {}, ''),
- 'url06' : ('{% url regressiontests.templates.views.client no_such_param="value" %}', {}, ''),
- }
-
- # Register our custom template loader.
- def test_template_loader(template_name, template_dirs=None):
- "A custom template loader that loads the unit-test templates."
- try:
- return (TEMPLATE_TESTS[template_name][0] , "test:%s" % template_name)
- except KeyError:
- raise template.TemplateDoesNotExist, template_name
-
- old_template_loaders = loader.template_source_loaders
- loader.template_source_loaders = [test_template_loader]
-
- failures = []
- tests = TEMPLATE_TESTS.items()
- tests.sort()
-
- # Turn TEMPLATE_DEBUG off, because tests assume that.
- old_td, settings.TEMPLATE_DEBUG = settings.TEMPLATE_DEBUG, False
-
- # Set TEMPLATE_STRING_IF_INVALID to a known string
- old_invalid = settings.TEMPLATE_STRING_IF_INVALID
-
- for name, vals in tests:
- install()
-
- if isinstance(vals[2], tuple):
- normal_string_result = vals[2][0]
- invalid_string_result = vals[2][1]
- else:
- normal_string_result = vals[2]
- invalid_string_result = vals[2]
-
- if 'LANGUAGE_CODE' in vals[1]:
- activate(vals[1]['LANGUAGE_CODE'])
- else:
- activate('en-us')
-
- for invalid_str, result in [('', normal_string_result),
- ('INVALID', invalid_string_result)]:
- settings.TEMPLATE_STRING_IF_INVALID = invalid_str
- try:
- output = loader.get_template(name).render(template.Context(vals[1]))
- except Exception, e:
- if e.__class__ != result:
- failures.append("Template test (TEMPLATE_STRING_IF_INVALID='%s'): %s -- FAILED. Got %s, exception: %s" % (invalid_str, name, e.__class__, e))
- continue
- if output != result:
- failures.append("Template test (TEMPLATE_STRING_IF_INVALID='%s'): %s -- FAILED. Expected %r, got %r" % (invalid_str, name, result, output))
-
- if 'LANGUAGE_CODE' in vals[1]:
- deactivate()
-
- loader.template_source_loaders = old_template_loaders
- deactivate()
- settings.TEMPLATE_DEBUG = old_td
- settings.TEMPLATE_STRING_IF_INVALID = old_invalid
-
- self.assertEqual(failures, [], '\n'.join(failures))
-
-if __name__ == "__main__":
- unittest.main()
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/templates/urls.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,10 +0,0 @@
-from django.conf.urls.defaults import *
-from regressiontests.templates import views
-
-urlpatterns = patterns('',
-
- # Test urls for testing reverse lookups
- (r'^$', views.index),
- (r'^client/(\d+)/$', views.client),
- (r'^client/(\d+)/(?P<action>[^/]+)/$', views.client_action),
-)
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/templates/views.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,10 +0,0 @@
-# Fake views for testing url reverse lookup
-
-def index(request):
- pass
-
-def client(request, id):
- pass
-
-def client_action(request, id, action):
- pass
--- a/thirdparty/google_appengine/lib/django/tests/regressiontests/urlpatterns_reverse/tests.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,39 +0,0 @@
-"Unit tests for reverse URL lookup"
-
-from django.core.urlresolvers import reverse_helper, NoReverseMatch
-import re, unittest
-
-test_data = (
- ('^places/(\d+)/$', 'places/3/', [3], {}),
- ('^places/(\d+)/$', 'places/3/', ['3'], {}),
- ('^places/(\d+)/$', NoReverseMatch, ['a'], {}),
- ('^places/(\d+)/$', NoReverseMatch, [], {}),
- ('^places/(?P<id>\d+)/$', 'places/3/', [], {'id': 3}),
- ('^people/(?P<name>\w+)/$', 'people/adrian/', ['adrian'], {}),
- ('^people/(?P<name>\w+)/$', 'people/adrian/', [], {'name': 'adrian'}),
- ('^people/(?P<name>\w+)/$', NoReverseMatch, ['name with spaces'], {}),
- ('^people/(?P<name>\w+)/$', NoReverseMatch, [], {'name': 'name with spaces'}),
- ('^people/(?P<name>\w+)/$', NoReverseMatch, [], {}),
- ('^hardcoded/$', 'hardcoded/', [], {}),
- ('^hardcoded/$', 'hardcoded/', ['any arg'], {}),
- ('^hardcoded/$', 'hardcoded/', [], {'kwarg': 'foo'}),
- ('^people/(?P<state>\w\w)/(?P<name>\w+)/$', 'people/il/adrian/', [], {'state': 'il', 'name': 'adrian'}),
- ('^people/(?P<state>\w\w)/(?P<name>\d)/$', NoReverseMatch, [], {'state': 'il', 'name': 'adrian'}),
- ('^people/(?P<state>\w\w)/(?P<name>\w+)/$', NoReverseMatch, [], {'state': 'il'}),
- ('^people/(?P<state>\w\w)/(?P<name>\w+)/$', NoReverseMatch, [], {'name': 'adrian'}),
- ('^people/(?P<state>\w\w)/(\w+)/$', NoReverseMatch, ['il'], {'name': 'adrian'}),
- ('^people/(?P<state>\w\w)/(\w+)/$', 'people/il/adrian/', ['adrian'], {'state': 'il'}),
-)
-
-class URLPatternReverse(unittest.TestCase):
- def test_urlpattern_reverse(self):
- for regex, expected, args, kwargs in test_data:
- try:
- got = reverse_helper(re.compile(regex), *args, **kwargs)
- except NoReverseMatch, e:
- self.assertEqual(expected, NoReverseMatch)
- else:
- self.assertEquals(got, expected)
-
-if __name__ == "__main__":
- run_tests(1)
--- a/thirdparty/google_appengine/lib/django/tests/runtests.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,154 +0,0 @@
-#!/usr/bin/env python
-
-import os, sys, traceback
-import unittest
-
-MODEL_TESTS_DIR_NAME = 'modeltests'
-REGRESSION_TESTS_DIR_NAME = 'regressiontests'
-TEST_DATABASE_NAME = 'django_test_db'
-TEST_TEMPLATE_DIR = 'templates'
-
-MODEL_TEST_DIR = os.path.join(os.path.dirname(__file__), MODEL_TESTS_DIR_NAME)
-REGRESSION_TEST_DIR = os.path.join(os.path.dirname(__file__), REGRESSION_TESTS_DIR_NAME)
-
-ALWAYS_INSTALLED_APPS = [
- 'django.contrib.contenttypes',
- 'django.contrib.auth',
- 'django.contrib.sites',
- 'django.contrib.flatpages',
- 'django.contrib.redirects',
- 'django.contrib.sessions',
- 'django.contrib.comments',
- 'django.contrib.admin',
-]
-
-def get_test_models():
- models = []
- for loc, dirpath in (MODEL_TESTS_DIR_NAME, MODEL_TEST_DIR), (REGRESSION_TESTS_DIR_NAME, REGRESSION_TEST_DIR):
- for f in os.listdir(dirpath):
- if f.startswith('__init__') or f.startswith('.') or f.startswith('sql') or f.startswith('invalid'):
- continue
- models.append((loc, f))
- return models
-
-def get_invalid_models():
- models = []
- for loc, dirpath in (MODEL_TESTS_DIR_NAME, MODEL_TEST_DIR), (REGRESSION_TESTS_DIR_NAME, REGRESSION_TEST_DIR):
- for f in os.listdir(dirpath):
- if f.startswith('__init__') or f.startswith('.') or f.startswith('sql'):
- continue
- if f.startswith('invalid'):
- models.append((loc, f))
- return models
-
-class InvalidModelTestCase(unittest.TestCase):
- def __init__(self, model_label):
- unittest.TestCase.__init__(self)
- self.model_label = model_label
-
- def runTest(self):
- from django.core import management
- from django.db.models.loading import load_app
- from cStringIO import StringIO
-
- try:
- module = load_app(self.model_label)
- except Exception, e:
- self.fail('Unable to load invalid model module')
-
- s = StringIO()
- count = management.get_validation_errors(s, module)
- s.seek(0)
- error_log = s.read()
- actual = error_log.split('\n')
- expected = module.model_errors.split('\n')
-
- unexpected = [err for err in actual if err not in expected]
- missing = [err for err in expected if err not in actual]
-
- self.assert_(not unexpected, "Unexpected Errors: " + '\n'.join(unexpected))
- self.assert_(not missing, "Missing Errors: " + '\n'.join(missing))
-
-def django_tests(verbosity, tests_to_run):
- from django.conf import settings
-
- old_installed_apps = settings.INSTALLED_APPS
- old_test_database_name = settings.TEST_DATABASE_NAME
- old_root_urlconf = settings.ROOT_URLCONF
- old_template_dirs = settings.TEMPLATE_DIRS
- old_use_i18n = settings.USE_I18N
- old_middleware_classes = settings.MIDDLEWARE_CLASSES
-
- # Redirect some settings for the duration of these tests.
- settings.TEST_DATABASE_NAME = TEST_DATABASE_NAME
- settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS
- settings.ROOT_URLCONF = 'urls'
- settings.TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), TEST_TEMPLATE_DIR),)
- settings.USE_I18N = True
- settings.MIDDLEWARE_CLASSES = (
- 'django.contrib.sessions.middleware.SessionMiddleware',
- 'django.contrib.auth.middleware.AuthenticationMiddleware',
- 'django.middleware.common.CommonMiddleware',
- )
-
- # Load all the ALWAYS_INSTALLED_APPS.
- # (This import statement is intentionally delayed until after we
- # access settings because of the USE_I18N dependency.)
- from django.db.models.loading import get_apps, load_app
- get_apps()
-
- # Load all the test model apps.
- test_models = []
- for model_dir, model_name in get_test_models():
- model_label = '.'.join([model_dir, model_name])
- try:
- # if the model was named on the command line, or
- # no models were named (i.e., run all), import
- # this model and add it to the list to test.
- if not tests_to_run or model_name in tests_to_run:
- if verbosity >= 1:
- print "Importing model %s" % model_name
- mod = load_app(model_label)
- settings.INSTALLED_APPS.append(model_label)
- test_models.append(mod)
- except Exception, e:
- sys.stderr.write("Error while importing %s:" % model_name + ''.join(traceback.format_exception(*sys.exc_info())[1:]))
- continue
-
- # Add tests for invalid models.
- extra_tests = []
- for model_dir, model_name in get_invalid_models():
- model_label = '.'.join([model_dir, model_name])
- if not tests_to_run or model_name in tests_to_run:
- extra_tests.append(InvalidModelTestCase(model_label))
-
- # Run the test suite, including the extra validation tests.
- from django.test.simple import run_tests
- failures = run_tests(test_models, verbosity, extra_tests=extra_tests)
- if failures:
- sys.exit(failures)
-
- # Restore the old settings.
- settings.INSTALLED_APPS = old_installed_apps
- settings.TESTS_DATABASE_NAME = old_test_database_name
- settings.ROOT_URLCONF = old_root_urlconf
- settings.TEMPLATE_DIRS = old_template_dirs
- settings.USE_I18N = old_use_i18n
- settings.MIDDLEWARE_CLASSES = old_middleware_classes
-
-if __name__ == "__main__":
- from optparse import OptionParser
- usage = "%prog [options] [model model model ...]"
- parser = OptionParser(usage=usage)
- parser.add_option('-v','--verbosity', action='store', dest='verbosity', default='0',
- type='choice', choices=['0', '1', '2'],
- help='Verbosity level; 0=minimal output, 1=normal output, 2=all output')
- parser.add_option('--settings',
- help='Python path to settings module, e.g. "myproject.settings". If this isn\'t provided, the DJANGO_SETTINGS_MODULE environment variable will be used.')
- options, args = parser.parse_args()
- if options.settings:
- os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
- elif "DJANGO_SETTINGS_MODULE" not in os.environ:
- parser.error("DJANGO_SETTINGS_MODULE is not set in the environment. "
- "Set it or use --settings.")
- django_tests(int(options.verbosity), args)
--- a/thirdparty/google_appengine/lib/django/tests/templates/404.html Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,1 +0,0 @@
-Django Internal Tests: 404 Error
\ No newline at end of file
--- a/thirdparty/google_appengine/lib/django/tests/templates/500.html Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,1 +0,0 @@
-Django Internal Tests: 500 Error
\ No newline at end of file
--- a/thirdparty/google_appengine/lib/django/tests/templates/login.html Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,19 +0,0 @@
-<html>
-<head></head>
-<body>
-<h1>Django Internal Tests: Login</h1>
-{% if form.has_errors %}
-<p>Your username and password didn't match. Please try again.</p>
-{% endif %}
-
-<form method="post" action=".">
-<table>
-<tr><td><label for="id_username">Username:</label></td><td>{{ form.username }}</td></tr>
-<tr><td><label for="id_password">Password:</label></td><td>{{ form.password }}</td></tr>
-</table>
-
-<input type="submit" value="login" />
-<input type="hidden" name="next" value="{{ next }}" />
-</form>
-</body>
-</html>
\ No newline at end of file
--- a/thirdparty/google_appengine/lib/django/tests/urls.py Sun Sep 06 23:31:53 2009 +0200
+++ /dev/null Thu Jan 01 00:00:00 1970 +0000
@@ -1,13 +0,0 @@
-from django.conf.urls.defaults import *
-
-urlpatterns = patterns('',
- # test_client modeltest urls
- (r'^test_client/', include('modeltests.test_client.urls')),
-
- # Always provide the auth system login and logout views
- (r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}),
- (r'^accounts/logout/$', 'django.contrib.auth.views.logout'),
-
- # test urlconf for {% url %} template tag
- (r'^url_tag/', include('regressiontests.templates.urls')),
-)