# HG changeset patch # User Pawel Solyga # Date 1252273514 -7200 # Node ID a04b1e4126c42f720b803019a72ebbe7907b9571 # Parent 2e0b0af889bec18a8fa7f245cc12f1a0689197a6 Remove some left overs from recent Google App Engine 1.2.5 update. diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/MANIFEST.in --- 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 * diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/django/contrib/flatpages/README.TXT --- 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. diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/django/contrib/formtools/templates/formtools/form.html --- 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 %}

Please correct the following errors

{% else %}

Submit

{% endif %} - -
- -{{ form }} -
- -

-
- -{% endblock %} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/django/contrib/formtools/templates/formtools/preview.html --- 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 %} - -

Preview your submission

- - -{% for field in form %} - - - - -{% endfor %} -
{{ field.label }}:{{ field.data|escape }}
- -

Security hash: {{ hash_value }}

- -
-{% for field in form %}{{ field.as_hidden }} -{% endfor %} - - -

-
- -

Or edit it again

- -
- -{{ form }} -
- -

-
- -{% endblock %} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/django/contrib/redirects/README.TXT --- 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 diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/django/dispatch/license.txt --- 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. - diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/django/utils/simplejson/LICENSE.txt --- 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. diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/examples/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/examples/hello/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/examples/hello/urls.py --- 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'), -) diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/examples/hello/views.py --- 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('

Hello, world.

') - -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("

Here's a paragraph.

") - r.write("

Here's another paragraph.

") - return r - -def metadata(request): - "This view demonstrates how to retrieve request metadata, such as HTTP headers." - r = HttpResponse('

All about you

') - r.write("

Here's all known metadata about your request, according to request.META:

") - r.write('') - meta_items = request.META.items() - meta_items.sort() - for k, v in meta_items: - r.write('' % (k, v)) - r.write('
%s%r
') - return r - -def get_data(request): - "This view demonstrates how to retrieve GET data." - r = HttpResponse() - if request.GET: - r.write('

GET data found! Here it is:

') - r.write('' % ''.join(['
  • %s: %r
  • ' % (escape(k), escape(v)) for k, v in request.GET.items()])) - r.write('
    ') - r.write('

    First name:

    ') - r.write('

    Last name:

    ') - r.write('

    ') - r.write('
    ') - return r - -def post_data(request): - "This view demonstrates how to retrieve POST data." - r = HttpResponse() - if request.POST: - r.write('

    POST data found! Here it is:

    ') - r.write('' % ''.join(['
  • %s: %r
  • ' % (escape(k), escape(v)) for k, v in request.POST.items()])) - r.write('
    ') - r.write('

    First name:

    ') - r.write('

    Last name:

    ') - r.write('

    ') - r.write('
    ') - return r diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/examples/manage.py --- 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) diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/examples/settings.py --- 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' diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/examples/urls.py --- 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')), -) diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/examples/views.py --- 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('

    Django examples

    ') - return r diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/extras/README.TXT --- 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. diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/extras/django_bash_completion --- 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 diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/basic/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/basic/models.py --- 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() -[] - -# Django provides a rich database lookup API. ->>> Article.objects.get(id__exact=1) - ->>> Article.objects.get(headline__startswith='Area woman') - ->>> Article.objects.get(pub_date__year=2005) - ->>> Article.objects.get(pub_date__year=2005, pub_date__month=7) - ->>> Article.objects.get(pub_date__year=2005, pub_date__month=7, pub_date__day=28) - - -# The "__exact" lookup type can be omitted, as a shortcut. ->>> Article.objects.get(id=1) - ->>> Article.objects.get(headline='Area woman programs in Python') - - ->>> Article.objects.filter(pub_date__year=2005) -[] ->>> Article.objects.filter(pub_date__year=2004) -[] ->>> Article.objects.filter(pub_date__year=2005, pub_date__month=7) -[] - -# 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) - - -# pk can be used as a shortcut for the primary key name in any query ->>> Article.objects.filter(pk__in=[1]) -[] - -# 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 -[, ] ->>> 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.objects.all()[1:3] -[, ] ->>> s3 = Article.objects.filter(id__exact=3) ->>> (s1 | s2 | s3)[::2] -[, ] - -# Slices (without step) are lazy: ->>> Article.objects.all()[0:5].filter() -[, , , , ] - -# Slicing again works: ->>> Article.objects.all()[0:5][0:2] -[, ] ->>> Article.objects.all()[0:5][:2] -[, ] ->>> Article.objects.all()[0:5][4:] -[] ->>> Article.objects.all()[0:5][5:] -[] - -# Some more tests! ->>> Article.objects.all()[2:][0:2] -[, ] ->>> Article.objects.all()[2:][:2] -[, ] ->>> Article.objects.all()[2:][2:3] -[] - -# 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.objects.filter(id__lte=4).delete() ->>> Article.objects.all() -[, , , ] -"""} - -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") - - -# 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) -[, ] -""" diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/choices/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/choices/models.py --- 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' -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/custom_columns/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/custom_columns/models.py --- 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.objects.filter(first_name__exact='John') -[] - ->>> Author.objects.get(first_name__exact='John') - - ->>> 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() -[, ] - -# Get the articles for an author ->>> a.article_set.all() -[] - -# Query the authors across the m2m relation ->>> art.authors.filter(last_name='Jones') -[] - -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/custom_managers/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/custom_managers/models.py --- 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() -[] - -# 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() -[] - ->>> 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.fast_cars.all() -[] - -# 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') -[, ] -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/custom_methods/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/custom_methods/models.py --- 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() -[] ->>> a.articles_from_same_day_2() -[] ->>> b.articles_from_same_day_1() -[] ->>> b.articles_from_same_day_2() -[] -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/custom_pk/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/custom_pk/models.py --- 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() -[] - ->>> fran = Employee(employee_code='XYZ456', first_name='Fran', last_name='Bones') ->>> fran.save() ->>> Employee.objects.all() -[, ] - ->>> Employee.objects.get(pk='ABC123') - ->>> Employee.objects.get(pk='XYZ456') - ->>> 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') - - -# pk can be used as a substitute for the primary key. ->>> Employee.objects.filter(pk__in=['ABC123','XYZ456']) -[, ] - -# 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.objects.in_bulk(['ABC123', 'XYZ456']) -{'XYZ456': , 'ABC123': } - ->>> b = Business(name='Sears') ->>> b.save() ->>> b.employees.add(dan, fran) ->>> b.employees.all() -[, ] ->>> fran.business_set.all() -[] ->>> Business.objects.in_bulk(['Sears']) -{'Sears': } - ->>> Business.objects.filter(name__exact='Sears') -[] ->>> Business.objects.filter(pk='Sears') -[] - -# Queries across tables, involving primary key ->>> Employee.objects.filter(business__name__exact='Sears') -[, ] ->>> Employee.objects.filter(business__pk='Sears') -[, ] - ->>> Business.objects.filter(employees__employee_code__exact='ABC123') -[] ->>> Business.objects.filter(employees__pk='ABC123') -[] ->>> Business.objects.filter(employees__first_name__startswith='Fran') -[] - -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/empty/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/empty/models.py --- 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() - -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/field_defaults/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/field_defaults/models.py --- 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 -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/fixtures/__init__.py --- 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 @@ - - diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/fixtures/fixtures/fixture1.json --- 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 diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/fixtures/fixtures/fixture2.json --- 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 diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/fixtures/fixtures/fixture2.xml --- 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 @@ - - - - Poker on TV is great! - 2006-06-16 11:00:00 - - - XML identified as leading cause of cancer - 2006-06-16 16:00:00 - - \ No newline at end of file diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/fixtures/fixtures/fixture3.xml --- 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 @@ - - - - Poker on TV is great! - 2006-06-16 11:00:00 - - - XML identified as leading cause of cancer - 2006-06-16 16:00:00 - - \ No newline at end of file diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/fixtures/fixtures/initial_data.json --- 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 diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/fixtures/models.py --- 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() -[] - -# Load fixture 1. Single JSON file, with two objects. ->>> management.load_data(['fixture1.json'], verbosity=0) ->>> Article.objects.all() -[, , ] - -# Load fixture 2. JSON file imported by default. Overwrites some existing objects ->>> management.load_data(['fixture2.json'], verbosity=0) ->>> Article.objects.all() -[, , , ] - -# Load fixture 3, XML format. ->>> management.load_data(['fixture3.xml'], verbosity=0) ->>> Article.objects.all() -[, , , , ] - -# Load a fixture that doesn't exist ->>> management.load_data(['unknown.json'], verbosity=0) - -# object list is unaffected ->>> Article.objects.all() -[, , , , ] - -# Reset the database representation of this app. This will delete all data. ->>> management.flush(verbosity=0, interactive=False) ->>> Article.objects.all() -[] - -# Load fixture 1 again, using format discovery ->>> management.load_data(['fixture1'], verbosity=0) ->>> Article.objects.all() -[, , ] - -# 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() -[, , ] - -# 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()), "[, , , ]") diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/generic_relations/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/generic_relations/models.py --- 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") - ->>> bacon.tags.create(tag="salty") - ->>> lion.tags.create(tag="yellow") - ->>> lion.tags.create(tag="hairy") - - ->>> lion.tags.all() -[, ] ->>> bacon.tags.all() -[, ] - -# You can easily access the content object like a foreign key. ->>> t = TaggedItem.objects.get(tag="salty") ->>> t.content_object - - -# 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) -[, ] - -# You can set a generic foreign key in the way you'd expect. ->>> tag1.content_object = platypus ->>> tag1.save() ->>> platypus.tags.all() -[] ->>> TaggedItem.objects.filter(content_type__pk=ctype.id, object_id=quartz.id) -[] - -# 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', , 1), ('fatty', , 2), ('hairy', , 1), ('salty', , 2), ('shiny', , 2), ('yellow', , 1)] - ->>> lion.delete() ->>> [(t.tag, t.content_type, t.object_id) for t in TaggedItem.objects.all()] -[('clearish', , 1), ('fatty', , 2), ('salty', , 2), ('shiny', , 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', , 1), ('fatty', , 2), ('salty', , 2), ('shiny', , 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() -[] ->>> [(t.tag, t.content_type, t.object_id) for t in TaggedItem.objects.all()] -[('clearish', , 1), ('salty', , 2), ('shiny', , 2)] - -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/get_latest/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/get_latest/models.py --- 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() - - -# Get the latest Article that matches certain filters. ->>> Article.objects.filter(pub_date__lt=datetime(2005, 7, 27)).latest() - - -# 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.objects.filter(pub_date__gt=datetime(2005, 7, 26)).latest('expire_date') - - -# 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') - -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/get_object_or_404/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/get_object_or_404/models.py --- 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") - - -# We can also use the the Article manager through an Author object. ->>> get_object_or_404(a.article_set, title__contains="Run") - - -# 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!") - - -# get_list_or_404 can be used to get lists of objects ->>> get_list_or_404(a.article_set, title__icontains='Run') -[] - -# 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") -[] - -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/get_or_create/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/get_or_create/models.py --- 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 -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/invalid_models/__init__.py --- 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 @@ - diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/invalid_models/models.py --- 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'. -""" diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/lookup/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/lookup/models.py --- 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: , 2: } ->>> Article.objects.in_bulk([3]) -{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() - ->>> a2.get_next_by_pub_date() - ->>> a2.get_next_by_pub_date(headline__endswith='6') - ->>> a3.get_next_by_pub_date() - ->>> a4.get_next_by_pub_date() - ->>> a5.get_next_by_pub_date() -Traceback (most recent call last): - ... -DoesNotExist: Article matching query does not exist. ->>> a6.get_next_by_pub_date() - ->>> a7.get_next_by_pub_date() - - ->>> a7.get_previous_by_pub_date() - ->>> a6.get_previous_by_pub_date() - ->>> a5.get_previous_by_pub_date() - ->>> a4.get_previous_by_pub_date() - ->>> a3.get_previous_by_pub_date() - ->>> a2.get_previous_by_pub_date() - - -# 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.objects.filter(headline__startswith='Article_') -[] - ->>> a9 = Article(headline='Article% with percent sign', pub_date=datetime(2005, 11, 21)) ->>> a9.save() ->>> Article.objects.filter(headline__startswith='Article') -[, , , , , , , , ] ->>> Article.objects.filter(headline__startswith='Article%') -[] - -# exclude() is the opposite of filter() when doing lookups: ->>> Article.objects.filter(headline__contains='Article').exclude(headline__contains='with') -[, , , , , , ] ->>> Article.objects.exclude(headline__startswith="Article_") -[, , , , , , , ] ->>> Article.objects.exclude(headline="Article 7") -[, , , , , , , ] - -# 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='\\') -[] - -# 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=[]) -[, , , , , , , , , ] - -# 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 - -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/m2m_and_m2o/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/m2m_and_m2o/models.py --- 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.objects.filter(client=g.id) -[] ->>> Issue.objects.filter(cc__id__exact=g.id) -[] ->>> Issue.objects.filter(cc__id__exact=r.id) -[, ] - -# 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.objects.filter(cc__id__exact=r.id) | Issue.objects.filter(client=r.id) -[, , ] ->>> Issue.objects.filter(Q(client=r.id) | Q(cc__id__exact=r.id)) -[, , ] -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/m2m_intermediary/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/m2m_intermediary/models.py --- 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') -[, ] ->>> w1.reporter - ->>> w2.reporter - ->>> w1.article - ->>> w2.article - ->>> r1.writer_set.all() -[] -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/m2m_multiple/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/m2m_multiple/models.py --- 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() -[, ] - ->>> a2.primary_categories.all() -[, ] - ->>> a1.secondary_categories.all() -[] - - ->>> c1.primary_article_set.all() -[] ->>> c1.secondary_article_set.all() -[] ->>> c2.primary_article_set.all() -[, ] ->>> c2.secondary_article_set.all() -[] ->>> c3.primary_article_set.all() -[] ->>> c3.secondary_article_set.all() -[] ->>> c4.primary_article_set.all() -[] ->>> c4.secondary_article_set.all() -[, ] -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/m2m_recursive/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/m2m_recursive/models.py --- 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() -[, , ] - -# Who is friends with Bill? ->>> b.friends.all() -[] - -# Who is friends with Chuck? ->>> c.friends.all() -[, ] - -# Who is friends with David? ->>> d.friends.all() -[, ] - -# 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() -[, , ] - -# Who is friends with Bill? ->>> b.friends.all() -[] - -# Remove Anne from Bill's friends ->>> b.friends.remove(a) - -# Who is friends with Anne? ->>> a.friends.all() -[, ] - -# 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() -[] - -# Who is friends with David? ->>> d.friends.all() -[] - - -# 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() -[, , ] - -# Who is stalking Anne? ->>> a.stalkers.all() -[] - -# Who are Bill's idols? ->>> b.idols.all() -[] - -# Who is stalking Bill? ->>> b.stalkers.all() -[] - -# Who are Chuck's idols? ->>> c.idols.all() -[] - -# Who is stalking Chuck? ->>> c.stalkers.all() -[] - -# Who are David's idols? ->>> d.idols.all() -[] - -# Who is stalking David ->>> d.stalkers.all() -[, ] - -# 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() -[, , ] - -# Who is stalking Anne? -[] - -# Who are Bill's idols ->>> b.idols.all() -[] - -# Who is stalking Bill? ->>> b.stalkers.all() -[] - -# Remove Anne from Bill's list of stalkers ->>> b.stalkers.remove(a) - -# Who are Anne's idols? ->>> a.idols.all() -[, ] - -# Who is stalking Anne? ->>> a.stalkers.all() -[] - -# Who are Bill's idols? ->>> b.idols.all() -[] - -# 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() -[] - -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/m2o_recursive/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/m2o_recursive/models.py --- 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() -[] ->>> r.child_set.get(name__startswith='Child') - ->>> print r.parent -None - ->>> c.child_set.all() -[] ->>> c.parent - -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/m2o_recursive2/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/m2o_recursive2/models.py --- 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 - ->>> kid.father - ->>> dad.fathers_child_set.all() -[] ->>> mom.mothers_child_set.all() -[] ->>> kid.mothers_child_set.all() -[] ->>> kid.fathers_child_set.all() -[] -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/manipulators/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/manipulators/models.py --- 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() -[] ->>> [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.objects.get().musician - - -# 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') -[, ] ->>> a2 = Album.objects.get(pk=2) ->>> a2 - ->>> a2.release_date -datetime.date(2005, 2, 13) -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/many_to_many/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/many_to_many/models.py --- 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() -[] ->>> a2.publications.all() -[, , , ] - -# Publication objects have access to their related Article objects. ->>> p2.article_set.all() -[] ->>> p1.article_set.all() -[, ] ->>> Publication.objects.get(id=4).article_set.all() -[] - -# We can perform kwarg queries across m2m relationships ->>> Article.objects.filter(publications__id__exact=1) -[, ] ->>> Article.objects.filter(publications__pk=1) -[, ] ->>> Article.objects.filter(publications=1) -[, ] ->>> Article.objects.filter(publications=p1) -[, ] - ->>> Article.objects.filter(publications__title__startswith="Science") -[, ] - ->>> Article.objects.filter(publications__title__startswith="Science").distinct() -[] - -# 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.objects.filter(publications__in=[1,p2]).distinct() -[, ] ->>> Article.objects.filter(publications__in=[p1,p2]).distinct() -[, ] - -# Reverse m2m queries are supported (i.e., starting at the table that doesn't -# have a ManyToManyField). ->>> Publication.objects.filter(id__exact=1) -[] ->>> Publication.objects.filter(pk=1) -[] - ->>> Publication.objects.filter(article__headline__startswith="NASA") -[, , , ] - ->>> Publication.objects.filter(article__id__exact=1) -[] ->>> Publication.objects.filter(article__pk=1) -[] ->>> Publication.objects.filter(article=1) -[] ->>> Publication.objects.filter(article=a1) -[] - ->>> Publication.objects.filter(article__in=[1,2]).distinct() -[, , , ] ->>> Publication.objects.filter(article__in=[1,a2]).distinct() -[, , , ] ->>> Publication.objects.filter(article__in=[a1,a2]).distinct() -[, , , ] - -# If we delete a Publication, its Articles won't be able to access it. ->>> p1.delete() ->>> Publication.objects.all() -[, , ] ->>> 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() -[] ->>> 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() -[] ->>> a4.publications.all() -[] - -# Adding via the other end using keywords ->>> new_article = p2.article_set.create(headline='Oxygen-free diet works wonders') ->>> p2.article_set.all() -[, ] ->>> a5 = p2.article_set.all()[1] ->>> a5.publications.all() -[] - -# Removing publication from an article: ->>> a4.publications.remove(p2) ->>> p2.article_set.all() -[] ->>> 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() -[, ] ->>> a4.publications.all() -[] ->>> a4.publications = [p3] ->>> p2.article_set.all() -[] ->>> a4.publications.all() -[] - -# Relation sets can be cleared: ->>> p2.article_set.clear() ->>> p2.article_set.all() -[] ->>> a4.publications.all() -[] - -# And you can clear from the other end ->>> p2.article_set.add(a4, a5) ->>> p2.article_set.all() -[, ] ->>> a4.publications.all() -[, ] ->>> a4.publications.clear() ->>> a4.publications.all() -[] ->>> p2.article_set.all() -[] - -# Relation sets can also be set using primary key values ->>> p2.article_set = [a4.id, a5.id] ->>> p2.article_set.all() -[, ] ->>> a4.publications.all() -[] ->>> a4.publications = [p3.id] ->>> p2.article_set.all() -[] ->>> a4.publications.all() -[] - -# 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() -[, ] ->>> Article.objects.all() -[, , , ] ->>> a2.publications.all() -[] - -# Bulk delete some articles - references to deleted objects should go ->>> q = Article.objects.filter(headline__startswith='Django') ->>> print q -[] ->>> 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() -[] - -# 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() -[, ] ->>> a2.publications = [] ->>> a2.publications.all() -[] - -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/many_to_one/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/many_to_one/models.py --- 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 - - -# 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 - ->>> 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() -[, , ] - -# 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() -[, ] ->>> r2.article_set.all() -[] - -# Assign the article to the reporter directly using the descriptor ->>> new_article2.reporter = r ->>> new_article2.save() ->>> new_article2.reporter - ->>> new_article2.reporter.id -1 ->>> r.article_set.all() -[, , ] ->>> r2.article_set.all() -[] - -# Set the article back again using set descriptor. ->>> r2.article_set = [new_article, new_article2] ->>> r.article_set.all() -[] ->>> r2.article_set.all() -[, ] - -# 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() -[, ] ->>> r2.article_set.all() -[] - -# 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() -[, ] - ->>> r.article_set.filter(headline__startswith='This') -[] - ->>> r.article_set.count() -2 - ->>> r2.article_set.count() -1 - -# Get articles by id ->>> Article.objects.filter(id__exact=1) -[] ->>> Article.objects.filter(pk=1) -[] - -# Query on an article property ->>> Article.objects.filter(headline__startswith='This') -[] - -# 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') -[, ] - -# Check that implied __exact also works ->>> Article.objects.filter(reporter__first_name='John') -[, ] - -# Query twice over the related field. ->>> Article.objects.filter(reporter__first_name__exact='John', reporter__last_name__exact='Smith') -[, ] - -# 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'"]) -[, ] - -# 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.objects.filter(reporter__pk=1) -[, ] ->>> Article.objects.filter(reporter=1) -[, ] ->>> Article.objects.filter(reporter=r) -[, ] - ->>> Article.objects.filter(reporter__in=[1,2]).distinct() -[, , ] ->>> Article.objects.filter(reporter__in=[r,r2]).distinct() -[, , ] - -# 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 - - -# 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 - - -# Reporters can be queried ->>> Reporter.objects.filter(id__exact=1) -[] ->>> Reporter.objects.filter(pk=1) -[] ->>> Reporter.objects.filter(first_name__startswith='John') -[] - -# Reporters can query in opposite direction of ForeignKey definition ->>> Reporter.objects.filter(article__id__exact=1) -[] ->>> Reporter.objects.filter(article__pk=1) -[] ->>> Reporter.objects.filter(article=1) -[] ->>> Reporter.objects.filter(article=a) -[] - ->>> Reporter.objects.filter(article__in=[1,4]).distinct() -[] ->>> Reporter.objects.filter(article__in=[1,a3]).distinct() -[] ->>> Reporter.objects.filter(article__in=[a,a3]).distinct() -[] - ->>> Reporter.objects.filter(article__headline__startswith='This') -[, , ] ->>> Reporter.objects.filter(article__headline__startswith='This').distinct() -[] - -# 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.objects.filter(article__reporter__first_name__startswith='John').distinct() -[] ->>> Reporter.objects.filter(article__reporter__exact=r).distinct() -[] - -# Check that implied __exact also works ->>> Reporter.objects.filter(article__reporter=r).distinct() -[] - -# If you delete a reporter, his articles will be deleted. ->>> Article.objects.all() -[, , , , ] ->>> Reporter.objects.order_by('first_name') -[, ] ->>> r2.delete() ->>> Article.objects.all() -[, , , ] ->>> Reporter.objects.order_by('first_name') -[] - -# Deletes using a join in the query ->>> Reporter.objects.filter(article__headline__startswith='This').delete() ->>> Reporter.objects.all() -[] ->>> Article.objects.all() -[] - -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/many_to_one_null/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/many_to_one_null/models.py --- 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 - - -# 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 - ->>> a2.reporter.id -1 - -# Reporter objects have access to their related Article objects. ->>> r.article_set.all() -[, ] ->>> r.article_set.filter(headline__startswith='Fir') -[] ->>> 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) -[] - -# Set the reporter for the Third article ->>> r.article_set.add(a3) ->>> r.article_set.all() -[, , ] - -# Remove an article from the set, and check that it was removed. ->>> r.article_set.remove(a3) ->>> r.article_set.all() -[, ] ->>> Article.objects.filter(reporter__isnull=True) -[] - -# Create another article and reporter ->>> r2 = Reporter(name='Paul Jones') ->>> r2.save() ->>> a4 = r2.article_set.create(headline='Fourth') ->>> r2.article_set.all() -[] - -# Try to remove a4 from a set it does not belong to ->>> r.article_set.remove(a4) -Traceback (most recent call last): -... -DoesNotExist: is not related to . - ->>> r2.article_set.all() -[] - -# 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() -[, ] - -# Clear the rest of the set ->>> r.article_set.clear() ->>> r.article_set.all() -[] ->>> Article.objects.filter(reporter__isnull=True) -[, ] - -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/model_forms/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/model_forms/models.py --- 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 - - ->>> print f.as_ul() -
  • -
  • ->>> print f['name'] - - ->>> f = CategoryForm(auto_id=False) ->>> print f.as_ul() -
  • Name:
  • -
  • The URL:
  • - ->>> f = CategoryForm({'name': 'Entertainment', 'url': 'entertainment'}) ->>> f.is_valid() -True ->>> f.clean_data -{'url': u'entertainment', 'name': u'Entertainment'} ->>> obj = f.save() ->>> obj - ->>> Category.objects.all() -[] - ->>> 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.objects.all() -[, ] - -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.objects.all() -[, ] ->>> obj.save() ->>> Category.objects.all() -[, , ] - -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 -Headline: -Pub date: -Writer: -Article: -Categories:
    Hold down "Control", or "Command" on a Mac, to select more than one. - -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 -Name:
    Use both first and last names. - ->>> 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() -
  • Headline:
  • -
  • Pub date:
  • -
  • Writer:
  • -
  • Article:
  • -
  • Categories: Hold down "Control", or "Command" on a Mac, to select more than one.
  • ->>> 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() -[] ->>> TestArticleForm = form_for_instance(new_art) ->>> f = TestArticleForm(auto_id=False) ->>> print f.as_ul() -
  • Headline:
  • -
  • Pub date:
  • -
  • Writer:
  • -
  • Article:
  • -
  • Categories: Hold down "Control", or "Command" on a Mac, to select more than one.
  • - ->>> 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() -[, ] - -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() -[, ] - -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 - ->>> cat.id -3 ->>> sc = ShortCategory({'name': 'Third', 'url': '3rd'}) ->>> save_instance(sc, cat) - ->>> Category.objects.get(id=3) - - -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() -
  • Headline:
  • -
  • Pub date:
  • -
  • Writer:
  • -
  • Article:
  • -
  • Categories: Hold down "Control", or "Command" on a Mac, to select more than one.
  • ->>> Category.objects.create(name='Fourth', url='4th') - ->>> Writer.objects.create(name='Carl Bernstein') - ->>> print f.as_ul() -
  • Headline:
  • -
  • Pub date:
  • -
  • Writer:
  • -
  • Article:
  • -
  • Categories: Hold down "Control", or "Command" on a Mac, to select more than one.
  • - -# 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) - ->>> f.clean(2) - - -# 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') - ->>> f.clean(5) - - -# 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') - ->>> 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]) -[] ->>> f.clean([2]) -[] ->>> f.clean(['1']) -[] ->>> f.clean(['1', '2']) -[, ] ->>> f.clean([1, '2']) -[, ] ->>> f.clean((1, '2')) -[, ] ->>> 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') - ->>> f.clean([6]) -[] - -# 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'} -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/model_inheritance/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/model_inheritance/models.py --- 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() - - -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/mutually_referential/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/mutually_referential/models.py --- 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 diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/one_to_one/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/one_to_one/models.py --- 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 - - -# A Place can access its restaurant, if available. ->>> p1.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 - ->>> r.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 - - ->>> r = Restaurant.objects.get(pk=1) ->>> r.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() -[, ] - -# Place.objects.all() returns all Places, regardless of whether they have -# Restaurants. ->>> Place.objects.order_by('name') -[, ] - ->>> Restaurant.objects.get(place__id__exact=1) - ->>> Restaurant.objects.get(pk=1) - ->>> Restaurant.objects.get(place__exact=1) - ->>> Restaurant.objects.get(place__exact=p1) - ->>> Restaurant.objects.get(place=1) - ->>> Restaurant.objects.get(place=p1) - ->>> Restaurant.objects.get(place__pk=1) - ->>> Restaurant.objects.get(place__name__startswith="Demon") - - ->>> Place.objects.get(id__exact=1) - ->>> Place.objects.get(pk=1) - ->>> Place.objects.get(restaurant__place__exact=1) - ->>> Place.objects.get(restaurant__place__exact=p1) - ->>> Place.objects.get(restaurant__pk=1) - ->>> Place.objects.get(restaurant=1) - ->>> Place.objects.get(restaurant=r) - ->>> Place.objects.get(restaurant__exact=1) - ->>> Place.objects.get(restaurant__exact=r) - - -# Add a Waiter to the Restaurant. ->>> w = r.waiter_set.create(name='Joe') ->>> w.save() ->>> w - - -# Query the waiters ->>> Waiter.objects.filter(restaurant__place__pk=1) -[] ->>> Waiter.objects.filter(restaurant__place__exact=1) -[] ->>> Waiter.objects.filter(restaurant__place__exact=p1) -[] ->>> Waiter.objects.filter(restaurant__pk=1) -[] ->>> Waiter.objects.filter(id__exact=1) -[] ->>> Waiter.objects.filter(pk=1) -[] ->>> Waiter.objects.filter(restaurant=1) -[] ->>> Waiter.objects.filter(restaurant=r) -[] - -# 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() -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/or_lookups/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/or_lookups/models.py --- 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.objects.filter(Q(headline__startswith='Hello') | Q(headline__startswith='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.objects.filter(Q(headline__contains='bye'), headline__startswith='Hello') -[] - ->>> Article.objects.filter(headline__contains='Hello') | Article.objects.filter(headline__contains='bye') -[, , ] - ->>> Article.objects.filter(headline__iexact='Hello') | Article.objects.filter(headline__contains='ood') -[, , ] - ->>> Article.objects.filter(Q(pk=1) | Q(pk=2)) -[, ] - ->>> Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3)) -[, , ] - -# You could also use "in" to accomplish the same as above. ->>> Article.objects.filter(pk__in=[1,2,3]) -[, , ] - ->>> Article.objects.filter(pk__in=[1,2,3,4]) -[, , ] - -# 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')) -[, ] - -# Q arg objects are ANDed ->>> Article.objects.filter(Q(headline__startswith='Hello'), Q(headline__contains='bye')) -[] - -# Q arg AND order is irrelevant ->>> Article.objects.filter(Q(headline__contains='bye'), headline__startswith='Hello') -[] - -# Try some arg queries with operations other than get_list ->>> Article.objects.get(Q(headline__startswith='Hello'), Q(headline__contains='bye')) - - ->>> 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: } - -# Demonstrating exclude with a Q object ->>> Article.objects.exclude(Q(headline__startswith='Hello')) -[] - -# 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.objects.complex_filter(Q(pk=1) | Q(pk=2)) -[, ] -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/ordering/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/ordering/models.py --- 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() -[, , , ] - -# Override ordering with order_by, which is in the same format as the ordering -# attribute in models. ->>> Article.objects.order_by('headline') -[, , , ] ->>> Article.objects.order_by('pub_date', '-headline') -[, , , ] - -# Use the 'stop' part of slicing notation to limit the results. ->>> Article.objects.order_by('headline')[:2] -[, ] - -# Use the 'stop' and 'start' parts of slicing notation to offset the result list. ->>> Article.objects.order_by('headline')[1:3] -[, ] - -# Getting a single item should work too: ->>> Article.objects.all()[0] - - -# 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('?') -[...] -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/pagination/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/pagination/models.py --- 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) -[, , , , ] - -# get the second page ->>> paginator.get_page(1) -[, , , ] - -# 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 -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/properties/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/properties/models.py --- 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' -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/reserved_names/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/reserved_names/models.py --- 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') -[, ] ->>> v = Thing.objects.get(pk='a') ->>> print v.join -b ->>> print v.where -2005-01-01 ->>> Thing.objects.order_by('select.when') -[, ] - ->>> 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) -[] -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/reverse_lookup/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/reverse_lookup/models.py --- 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.objects.get(poll__question__exact="What's the second question?") - - ->>> # Reverse lookups by related_name: ->>> Poll.objects.get(poll_choice__name__exact="This is the answer.") - ->>> Poll.objects.get(related_choice__name__exact="This is the answer.") - - ->>> # 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 -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/save_delete_hooks/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/save_delete_hooks/models.py --- 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() -[] - ->>> p1.delete() -Before deletion -After deletion - ->>> Person.objects.all() -[] -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/select_related/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/select_related/models.py --- 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 - ->>> 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 - ->>> 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] -[, , , ] ->>> len(db.connection.queries) -9 - -# With select_related(): ->>> db.reset_queries() ->>> world = Species.objects.all().select_related() ->>> [o.genus.family for o in world] -[, , , ] ->>> 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 - - -# 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 - ->>> len(db.connection.queries) -3 - ->>> db.reset_queries() ->>> world = Species.objects.all().select_related(depth=2) ->>> [o.genus.family.order for o in world] -[, , , ] ->>> len(db.connection.queries) -5 - -# Reset DEBUG to where we found it. ->>> settings.DEBUG = False -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/serializers/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/serializers/models.py --- 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 - - - -# 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() -[, ] - -# But when I save, the data changes as you might except. ->>> objs[0].save() ->>> Article.objects.all() -[, ] - -# 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() -[, , ] - -# All the serializers work the same ->>> json = serializers.serialize("json", Article.objects.all()) ->>> for obj in serializers.deserialize("json", json): -... print obj - - - ->>> 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() -[, ] - -# 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 - - -# 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.categories.all() -[, ] ->>> article.author - - -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/str/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/str/models.py --- 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 - -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/test_client/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/test_client/fixtures/testdata.json --- 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 diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/test_client/models.py --- 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 = """BlinkMalcolm Gladwell""" - 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 diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/test_client/urls.py --- 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) -) diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/test_client/views.py --- 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.") diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/transactions/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/transactions/models.py --- 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() -[] - -# 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() -[, ] - -# 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() -[, ] - -# 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() -[] - -# 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() -[, ] - -# 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 diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/validation/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/modeltests/validation/models.py --- 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.']} - -"""} diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/bug639/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/bug639/models.py --- 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 diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/bug639/test.jpg Binary file thirdparty/google_appengine/lib/django/tests/regressiontests/bug639/test.jpg has changed diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/bug639/tests.py --- 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 diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/cache/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/cache/models.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/cache/tests.py --- 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 diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/datastructures/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/datastructures/models.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/datastructures/tests.py --- 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'] -""" diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/dateformat/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/dateformat/models.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/dateformat/tests.py --- 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) diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/db_typecasts/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/db_typecasts/models.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/db_typecasts/tests.py --- 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 diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/defaultfilters/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/defaultfilters/models.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/defaultfilters/tests.py --- 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('

    one two - three
    four
    five

    ', 0) -'' - ->>> truncatewords_html('

    one two - three
    four
    five

    ', 2) -'

    one two ...

    ' - ->>> truncatewords_html('

    one two - three
    four
    five

    ', 4) -'

    one two - three
    four ...

    ' - ->>> truncatewords_html('

    one two - three
    four
    five

    ', 5) -'

    one two - three
    four
    five

    ' - ->>> truncatewords_html('

    one two - three
    four
    five

    ', 100) -'

    one two - three
    four
    five

    ' - ->>> 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) -'http://short.com/' - ->>> urlizetrunc('http://www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search&meta=', 20) -'http://www.google.co...' - ->>> 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(' here') -'<some html & special characters > here' - ->>> linebreaks('line 1') -'

    line 1

    ' - ->>> linebreaks('line 1\nline 2') -'

    line 1
    line 2

    ' - ->>> removetags('some html with disallowed tags', 'script img') -'some html with alert("You smell") disallowed tags' - ->>> striptags('some html with disallowed 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
  • item 1
  • ' - ->>> unordered_list(['item 1', [['item 1.1', []]]]) -'\t
  • item 1\n\t
      \n\t\t
    • item 1.1
    • \n\t
    \n\t
  • ' - ->>> unordered_list(['item 1', [['item 1.1', []], ['item 1.2', []]]]) -'\t
  • item 1\n\t
      \n\t\t
    • item 1.1
    • \n\t\t
    • item 1.2
    • \n\t
    \n\t
  • ' - ->>> 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) -'

    123

    ' ->>> linebreaksbr(123) -'123' ->>> removetags(123, 'a') -'123' ->>> striptags(123) -'123' - -""" - -from django.template.defaultfilters import * -import datetime - -if __name__ == '__main__': - import doctest - doctest.testmod() diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/dispatch/__init__.py --- 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 -""" diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/dispatch/models.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/dispatch/tests/__init__.py --- 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 * diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/dispatch/tests/test_dispatcher.py --- 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 () diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/dispatch/tests/test_robustapply.py --- 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() - diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/dispatch/tests/test_saferef.py --- 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() diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/forms/__init__.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/forms/models.py diff -r 2e0b0af889be -r a04b1e4126c4 thirdparty/google_appengine/lib/django/tests/regressiontests/forms/tests.py --- 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'' ->>> w.render('email', None) -u'' ->>> w.render('email', 'test@example.com') -u'' ->>> w.render('email', 'some "quoted" & ampersanded value') -u'' ->>> w.render('email', 'test@example.com', attrs={'class': 'fun'}) -u'' - -# 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'' - -You can also pass 'attrs' to the constructor: ->>> w = TextInput(attrs={'class': 'fun'}) ->>> w.render('email', '') -u'' ->>> w.render('email', 'foo@example.com') -u'' - -'attrs' passed to render() get precedence over those passed to the constructor: ->>> w = TextInput(attrs={'class': 'pretty'}) ->>> w.render('email', '', attrs={'class': 'special'}) -u'' - -# PasswordInput Widget ############################################################ - ->>> w = PasswordInput() ->>> w.render('email', '') -u'' ->>> w.render('email', None) -u'' ->>> w.render('email', 'test@example.com') -u'' ->>> w.render('email', 'some "quoted" & ampersanded value') -u'' ->>> w.render('email', 'test@example.com', attrs={'class': 'fun'}) -u'' - -You can also pass 'attrs' to the constructor: ->>> w = PasswordInput(attrs={'class': 'fun'}) ->>> w.render('email', '') -u'' ->>> w.render('email', 'foo@example.com') -u'' - -'attrs' passed to render() get precedence over those passed to the constructor: ->>> w = PasswordInput(attrs={'class': 'pretty'}) ->>> w.render('email', '', attrs={'class': 'special'}) -u'' - ->>> w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}) -u'' - -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'' ->>> w = PasswordInput(render_value=False) ->>> w.render('email', '') -u'' ->>> w.render('email', None) -u'' ->>> w.render('email', 'secret') -u'' ->>> w = PasswordInput(attrs={'class': 'fun'}, render_value=False) ->>> w.render('email', 'secret') -u'' - -# HiddenInput Widget ############################################################ - ->>> w = HiddenInput() ->>> w.render('email', '') -u'' ->>> w.render('email', None) -u'' ->>> w.render('email', 'test@example.com') -u'' ->>> w.render('email', 'some "quoted" & ampersanded value') -u'' ->>> w.render('email', 'test@example.com', attrs={'class': 'fun'}) -u'' - -You can also pass 'attrs' to the constructor: ->>> w = HiddenInput(attrs={'class': 'fun'}) ->>> w.render('email', '') -u'' ->>> w.render('email', 'foo@example.com') -u'' - -'attrs' passed to render() get precedence over those passed to the constructor: ->>> w = HiddenInput(attrs={'class': 'pretty'}) ->>> w.render('email', '', attrs={'class': 'special'}) -u'' - ->>> w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}) -u'' - -'attrs' passed to render() get precedence over those passed to the constructor: ->>> w = HiddenInput(attrs={'class': 'pretty'}) ->>> w.render('email', '', attrs={'class': 'special'}) -u'' - -# MultipleHiddenInput Widget ################################################## - ->>> w = MultipleHiddenInput() ->>> w.render('email', []) -u'' ->>> w.render('email', None) -u'' ->>> w.render('email', ['test@example.com']) -u'' ->>> w.render('email', ['some "quoted" & ampersanded value']) -u'' ->>> w.render('email', ['test@example.com', 'foo@example.com']) -u'\n' ->>> w.render('email', ['test@example.com'], attrs={'class': 'fun'}) -u'' ->>> w.render('email', ['test@example.com', 'foo@example.com'], attrs={'class': 'fun'}) -u'\n' - -You can also pass 'attrs' to the constructor: ->>> w = MultipleHiddenInput(attrs={'class': 'fun'}) ->>> w.render('email', []) -u'' ->>> w.render('email', ['foo@example.com']) -u'' ->>> w.render('email', ['foo@example.com', 'test@example.com']) -u'\n' - -'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'' - ->>> w.render('email', ['ŠĐĆŽćžšđ'], attrs={'class': 'fun'}) -u'' - -'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'' - -# FileInput Widget ############################################################ - ->>> w = FileInput() ->>> w.render('email', '') -u'' ->>> w.render('email', None) -u'' ->>> w.render('email', 'test@example.com') -u'' ->>> w.render('email', 'some "quoted" & ampersanded value') -u'' ->>> w.render('email', 'test@example.com', attrs={'class': 'fun'}) -u'' - -You can also pass 'attrs' to the constructor: ->>> w = FileInput(attrs={'class': 'fun'}) ->>> w.render('email', '') -u'' ->>> w.render('email', 'foo@example.com') -u'' - ->>> w.render('email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}) -u'' - -# Textarea Widget ############################################################# - ->>> w = Textarea() ->>> w.render('msg', '') -u'' ->>> w.render('msg', None) -u'' ->>> w.render('msg', 'value') -u'' ->>> w.render('msg', 'some "quoted" & ampersanded value') -u'' ->>> w.render('msg', 'value', attrs={'class': 'pretty'}) -u'' - -You can also pass 'attrs' to the constructor: ->>> w = Textarea(attrs={'class': 'pretty'}) ->>> w.render('msg', '') -u'' ->>> w.render('msg', 'example') -u'' - -'attrs' passed to render() get precedence over those passed to the constructor: ->>> w = Textarea(attrs={'class': 'pretty'}) ->>> w.render('msg', '', attrs={'class': 'special'}) -u'' - ->>> w.render('msg', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'}) -u'' - -# CheckboxInput Widget ######################################################## - ->>> w = CheckboxInput() ->>> w.render('is_cool', '') -u'' ->>> w.render('is_cool', None) -u'' ->>> w.render('is_cool', False) -u'' ->>> w.render('is_cool', True) -u'' - -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'' - ->>> w.render('is_cool', False, attrs={'class': 'pretty'}) -u'' - -You can also pass 'attrs' to the constructor: ->>> w = CheckboxInput(attrs={'class': 'pretty'}) ->>> w.render('is_cool', '') -u'' - -'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'' - -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'' ->>> w.render('greeting', 'hello') -u'' ->>> w.render('greeting', 'hello there') -u'' ->>> w.render('greeting', 'hello & goodbye') -u'' - -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'' ->>> w.render('greeting', False) -u'' ->>> w.render('greeting', None) -u'' - -# Select Widget ############################################################### - ->>> w = Select() ->>> print w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) - - -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'))) - - -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'))) - - -The value is compared to its str(): ->>> print w.render('num', 2, choices=[('1', '1'), ('2', '2'), ('3', '3')]) - ->>> print w.render('num', '2', choices=[(1, 1), (2, 2), (3, 3)]) - ->>> print w.render('num', 2, choices=[(1, 1), (2, 2), (3, 3)]) - - -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()) - ->>> 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'' ->>> f.as_table() -u'' ->>> f = SomeForm({'somechoice': 2}) ->>> f.as_table() -u'' - -You can also pass 'choices' to the constructor: ->>> w = Select(choices=[(1, 1), (2, 2), (3, 3)]) ->>> print w.render('num', 2) - - -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)]) - - ->>> w.render('email', 'ŠĐĆŽćžšđ', choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]) -u'' - -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) - ->>> print w.render('num', 3) - - -# NullBooleanSelect Widget #################################################### - ->>> w = NullBooleanSelect() ->>> print w.render('is_cool', True) - ->>> print w.render('is_cool', False) - ->>> print w.render('is_cool', None) - ->>> print w.render('is_cool', '2') - ->>> print w.render('is_cool', '3') - - -# SelectMultiple Widget ####################################################### - ->>> w = SelectMultiple() ->>> print w.render('beatles', ['J'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) - ->>> print w.render('beatles', ['J', 'P'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) - ->>> print w.render('beatles', ['J', 'P', 'R'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) - - -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'))) - - -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'))) - - -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'))) - - -The value is compared to its str(): ->>> print w.render('nums', [2], choices=[('1', '1'), ('2', '2'), ('3', '3')]) - ->>> print w.render('nums', ['2'], choices=[(1, 1), (2, 2), (3, 3)]) - ->>> print w.render('nums', [2], choices=[(1, 1), (2, 2), (3, 3)]) - - -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()) - - -You can also pass 'choices' to the constructor: ->>> w = SelectMultiple(choices=[(1, 1), (2, 2), (3, 3)]) ->>> print w.render('nums', [2]) - - -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)]) - - ->>> w.render('nums', ['ŠĐĆŽćžšđ'], choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]) -u'' - -# RadioSelect Widget ########################################################## - ->>> w = RadioSelect() ->>> print w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -
      -
    • -
    • -
    • -
    • -
    - -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'))) -
      -
    • -
    • -
    • -
    • -
    - -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'))) -
      -
    • -
    • -
    • -
    • -
    - -The value is compared to its str(): ->>> print w.render('num', 2, choices=[('1', '1'), ('2', '2'), ('3', '3')]) -
      -
    • -
    • -
    • -
    ->>> print w.render('num', '2', choices=[(1, 1), (2, 2), (3, 3)]) -
      -
    • -
    • -
    • -
    ->>> print w.render('num', 2, choices=[(1, 1), (2, 2), (3, 3)]) -
      -
    • -
    • -
    • -
    - -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()) -
      -
    • -
    • -
    • -
    • -
    • -
    - -You can also pass 'choices' to the constructor: ->>> w = RadioSelect(choices=[(1, 1), (2, 2), (3, 3)]) ->>> print w.render('num', 2) -
      -
    • -
    • -
    • -
    - -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)]) -
      -
    • -
    • -
    • -
    • -
    • -
    - -The render() method returns a RadioFieldRenderer object, whose str() is a
      . -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 - - - - ->>> for inp in r: -... print '%s
      ' % inp -
      -
      -
      -
      ->>> for inp in r: -... print '

      %s %s

      ' % (inp.tag(), inp.choice_label) -

      John

      -

      Paul

      -

      George

      -

      Ringo

      ->>> 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] - ->>> print r[0] - ->>> 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'
        \n
      • \n
      • \n
      ' - -# CheckboxSelectMultiple Widget ############################################### - ->>> w = CheckboxSelectMultiple() ->>> print w.render('beatles', ['J'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -
        -
      • -
      • -
      • -
      • -
      ->>> print w.render('beatles', ['J', 'P'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -
        -
      • -
      • -
      • -
      • -
      ->>> print w.render('beatles', ['J', 'P', 'R'], choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) -
        -
      • -
      • -
      • -
      • -
      - -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'))) -
        -
      • -
      • -
      • -
      • -
      - -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'))) -
        -
      • -
      • -
      • -
      • -
      - -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'))) -
        -
      • -
      • -
      • -
      • -
      - -The value is compared to its str(): ->>> print w.render('nums', [2], choices=[('1', '1'), ('2', '2'), ('3', '3')]) -
        -
      • -
      • -
      • -
      ->>> print w.render('nums', ['2'], choices=[(1, 1), (2, 2), (3, 3)]) -
        -
      • -
      • -
      • -
      ->>> print w.render('nums', [2], choices=[(1, 1), (2, 2), (3, 3)]) -
        -
      • -
      • -
      • -
      - -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()) -
        -
      • -
      • -
      • -
      • -
      • -
      - -You can also pass 'choices' to the constructor: ->>> w = CheckboxSelectMultiple(choices=[(1, 1), (2, 2), (3, 3)]) ->>> print w.render('nums', [2]) -
        -
      • -
      • -
      • -
      - -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)]) -
        -
      • -
      • -
      • -
      • -
      • -
      - ->>> w.render('nums', ['ŠĐĆŽćžšđ'], choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')]) -u'
        \n
      • \n
      • \n
      • \n
      • \n
      • \n
      ' - -# MultiWidget ################################################################# - ->>> class MyMultiWidget(MultiWidget): -... def decompress(self, value): -... if value: -... return value.split('__') -... return ['', ''] -... def format_output(self, rendered_widgets): -... return u'
      '.join(rendered_widgets) ->>> w = MyMultiWidget(widgets=(TextInput(attrs={'class': 'big'}), TextInput(attrs={'class': 'small'}))) ->>> w.render('name', ['john', 'lennon']) -u'
      ' ->>> w.render('name', 'john__lennon') -u'
      ' - -# SplitDateTimeWidget ######################################################### - ->>> w = SplitDateTimeWidget() ->>> w.render('date', '') -u'' ->>> w.render('date', None) -u'' ->>> w.render('date', datetime.datetime(2006, 1, 10, 7, 30)) -u'' ->>> w.render('date', [datetime.date(2006, 1, 10), datetime.time(7, 30)]) -u'' - -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'' - -########## -# 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'] - ->>> print p['last_name'] - ->>> print p['birthday'] - ->>> print p['nonexistentfield'] -Traceback (most recent call last): -... -KeyError: "Key 'nonexistentfield' not found in Form" - ->>> for boundfield in p: -... print boundfield - - - ->>> for boundfield in p: -... print boundfield.label, boundfield.data -First name John -Last name Lennon -Birthday 1940-10-9 ->>> print p - - - - -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 -
      • This field is required.
      -
      • This field is required.
      -
      • This field is required.
      ->>> print p.as_table() -
      • This field is required.
      -
      • This field is required.
      -
      • This field is required.
      ->>> print p.as_ul() -
      • This field is required.
    • -
      • This field is required.
    • -
      • This field is required.
    • ->>> print p.as_p() -

      • This field is required.

      -

      -

      • This field is required.

      -

      -

      • This field is required.

      -

      - -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 - - - ->>> print p.as_table() - - - ->>> print p.as_ul() -
    • -
    • -
    • ->>> print p.as_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'\n\n' ->>> p.as_ul() -u'
    • \n
    • \n
    • ' ->>> p.as_p() -u'

      \n

      \n

      ' - ->>> 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'
      • first_name
        • This field is required.
      • birthday
        • This field is required.
      ' ->>> 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'
      • This field is required.
      ' ->>> p['first_name'].errors.as_text() -u'* This field is required.' - ->>> p = Person() ->>> print p['first_name'] - ->>> print p['last_name'] - ->>> print p['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