Replaced print statement by print function (forward compatibility syntax).

This commit is contained in:
Claude Paroz 2012-04-28 18:02:01 +02:00
parent fe43ad5707
commit 596cb9c7e2
61 changed files with 310 additions and 310 deletions

View File

@ -24,7 +24,7 @@ def gather_stats(p):
prof = stats.load(os.path.join(p, f)) prof = stats.load(os.path.join(p, f))
else: else:
continue continue
print "Processing %s" % f print("Processing %s" % f)
if path in profiles: if path in profiles:
profiles[path].add(prof) profiles[path].add(prof)
else: else:

View File

@ -11,7 +11,7 @@ def unique_messages():
elif os.path.isdir('locale'): elif os.path.isdir('locale'):
basedir = os.path.abspath('locale') basedir = os.path.abspath('locale')
else: else:
print "This script should be run from the Django Git tree or your project or app tree." print("This script should be run from the Django Git tree or your project or app tree.")
sys.exit(1) sys.exit(1)
for (dirpath, dirnames, filenames) in os.walk(basedir): for (dirpath, dirnames, filenames) in os.walk(basedir):

View File

@ -54,7 +54,7 @@ def create_permissions(app, created_models, verbosity, **kwargs):
auth_app.Permission.objects.bulk_create(objs) auth_app.Permission.objects.bulk_create(objs)
if verbosity >= 2: if verbosity >= 2:
for obj in objs: for obj in objs:
print "Adding permission '%s'" % obj print("Adding permission '%s'" % obj)
def create_superuser(app, created_models, verbosity, db, **kwargs): def create_superuser(app, created_models, verbosity, db, **kwargs):

View File

@ -39,7 +39,7 @@ def update_contenttypes(app, created_models, verbosity=2, **kwargs):
]) ])
if verbosity >= 2: if verbosity >= 2:
for ct in cts: for ct in cts:
print "Adding content type '%s | %s'" % (ct.app_label, ct.model) print("Adding content type '%s | %s'" % (ct.app_label, ct.model))
# Confirm that the content type is stale before deletion. # Confirm that the content type is stale before deletion.
if to_remove: if to_remove:
@ -63,11 +63,11 @@ If you're unsure, answer 'no'.
if ok_to_delete == 'yes': if ok_to_delete == 'yes':
for ct in to_remove: for ct in to_remove:
if verbosity >= 2: if verbosity >= 2:
print "Deleting stale content type '%s | %s'" % (ct.app_label, ct.model) print("Deleting stale content type '%s | %s'" % (ct.app_label, ct.model))
ct.delete() ct.delete()
else: else:
if verbosity >= 2: if verbosity >= 2:
print "Stale content types remain." print("Stale content types remain.")
def update_all_contenttypes(verbosity=2, **kwargs): def update_all_contenttypes(verbosity=2, **kwargs):
for app in get_apps(): for app in get_apps():

View File

@ -24,7 +24,7 @@ class SpatiaLiteCreation(DatabaseCreation):
test_db_repr = '' test_db_repr = ''
if verbosity >= 2: if verbosity >= 2:
test_db_repr = " ('%s')" % test_database_name test_db_repr = " ('%s')" % test_database_name
print "Creating test database for alias '%s'%s..." % (self.connection.alias, test_db_repr) print("Creating test database for alias '%s'%s..." % (self.connection.alias, test_db_repr))
self._create_test_db(verbosity, autoclobber) self._create_test_db(verbosity, autoclobber)

View File

@ -13,21 +13,21 @@
>>> from django.contrib.gis.gdal import OGRGeometry, OGRGeomType, SpatialReference >>> from django.contrib.gis.gdal import OGRGeometry, OGRGeomType, SpatialReference
>>> wkt1, wkt2 = 'POINT(-90 30)', 'POLYGON((0 0, 5 0, 5 5, 0 5)' >>> wkt1, wkt2 = 'POINT(-90 30)', 'POLYGON((0 0, 5 0, 5 5, 0 5)'
>>> pnt = OGRGeometry(wkt1) >>> pnt = OGRGeometry(wkt1)
>>> print pnt >>> print(pnt)
POINT (-90 30) POINT (-90 30)
>>> mpnt = OGRGeometry(OGRGeomType('MultiPoint'), SpatialReference('WGS84')) >>> mpnt = OGRGeometry(OGRGeomType('MultiPoint'), SpatialReference('WGS84'))
>>> mpnt.add(wkt1) >>> mpnt.add(wkt1)
>>> mpnt.add(wkt1) >>> mpnt.add(wkt1)
>>> print mpnt >>> print(mpnt)
MULTIPOINT (-90 30,-90 30) MULTIPOINT (-90 30,-90 30)
>>> print mpnt.srs.name >>> print(mpnt.srs.name)
WGS 84 WGS 84
>>> print mpnt.srs.proj >>> print(mpnt.srs.proj)
+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs
>>> mpnt.transform_to(SpatialReference('NAD27')) >>> mpnt.transform_to(SpatialReference('NAD27'))
>>> print mpnt.proj >>> print(mpnt.proj)
+proj=longlat +ellps=clrk66 +datum=NAD27 +no_defs +proj=longlat +ellps=clrk66 +datum=NAD27 +no_defs
>>> print mpnt >>> print(mpnt)
MULTIPOINT (-89.999930378602485 29.999797886557641,-89.999930378602485 29.999797886557641) MULTIPOINT (-89.999930378602485 29.999797886557641,-89.999930378602485 29.999797886557641)
The OGRGeomType class is to make it easy to specify an OGR geometry type: The OGRGeomType class is to make it easy to specify an OGR geometry type:
@ -35,8 +35,8 @@
>>> gt1 = OGRGeomType(3) # Using an integer for the type >>> gt1 = OGRGeomType(3) # Using an integer for the type
>>> gt2 = OGRGeomType('Polygon') # Using a string >>> gt2 = OGRGeomType('Polygon') # Using a string
>>> gt3 = OGRGeomType('POLYGON') # It's case-insensitive >>> gt3 = OGRGeomType('POLYGON') # It's case-insensitive
>>> print gt1 == 3, gt1 == 'Polygon' # Equivalence works w/non-OGRGeomType objects >>> print(gt1 == 3, gt1 == 'Polygon') # Equivalence works w/non-OGRGeomType objects
True True True
""" """
# Python library requisites. # Python library requisites.
import sys import sys

View File

@ -4,7 +4,7 @@
Example: Example:
>>> from django.contrib.gis.gdal import SpatialReference >>> from django.contrib.gis.gdal import SpatialReference
>>> srs = SpatialReference('WGS84') >>> srs = SpatialReference('WGS84')
>>> print srs >>> print(srs)
GEOGCS["WGS 84", GEOGCS["WGS 84",
DATUM["WGS_1984", DATUM["WGS_1984",
SPHEROID["WGS 84",6378137,298.257223563, SPHEROID["WGS 84",6378137,298.257223563,
@ -16,14 +16,14 @@
UNIT["degree",0.01745329251994328, UNIT["degree",0.01745329251994328,
AUTHORITY["EPSG","9122"]], AUTHORITY["EPSG","9122"]],
AUTHORITY["EPSG","4326"]] AUTHORITY["EPSG","4326"]]
>>> print srs.proj >>> print(srs.proj)
+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs
>>> print srs.ellipsoid >>> print(srs.ellipsoid)
(6378137.0, 6356752.3142451793, 298.25722356300003) (6378137.0, 6356752.3142451793, 298.25722356300003)
>>> print srs.projected, srs.geographic >>> print(srs.projected, srs.geographic)
False True False True
>>> srs.import_epsg(32140) >>> srs.import_epsg(32140)
>>> print srs.name >>> print(srs.name)
NAD83 / Texas South Central NAD83 / Texas South Central
""" """
from ctypes import byref, c_char_p, c_int from ctypes import byref, c_char_p, c_int
@ -103,19 +103,19 @@ class SpatialReference(GDALBase):
>>> wkt = 'GEOGCS["WGS 84", DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]]') >>> wkt = 'GEOGCS["WGS 84", DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]]')
>>> srs = SpatialReference(wkt) # could also use 'WGS84', or 4326 >>> srs = SpatialReference(wkt) # could also use 'WGS84', or 4326
>>> print srs['GEOGCS'] >>> print(srs['GEOGCS'])
WGS 84 WGS 84
>>> print srs['DATUM'] >>> print(srs['DATUM'])
WGS_1984 WGS_1984
>>> print srs['AUTHORITY'] >>> print(srs['AUTHORITY'])
EPSG EPSG
>>> print srs['AUTHORITY', 1] # The authority value >>> print(srs['AUTHORITY', 1]) # The authority value
4326 4326
>>> print srs['TOWGS84', 4] # the fourth value in this wkt >>> print(srs['TOWGS84', 4]) # the fourth value in this wkt
0 0
>>> print srs['UNIT|AUTHORITY'] # For the units authority, have to use the pipe symbole. >>> print(srs['UNIT|AUTHORITY']) # For the units authority, have to use the pipe symbole.
EPSG EPSG
>>> print srs['UNIT|AUTHORITY', 1] # The authority value for the untis >>> print(srs['UNIT|AUTHORITY', 1]) # The authority value for the untis
9122 9122
""" """
if isinstance(target, tuple): if isinstance(target, tuple):

View File

@ -59,7 +59,7 @@ class DataSourceTest(unittest.TestCase):
def test03a_layers(self): def test03a_layers(self):
"Testing Data Source Layers." "Testing Data Source Layers."
print "\nBEGIN - expecting out of range feature id error; safe to ignore.\n" print("\nBEGIN - expecting out of range feature id error; safe to ignore.\n")
for source in ds_list: for source in ds_list:
ds = DataSource(source.ds) ds = DataSource(source.ds)
@ -108,7 +108,7 @@ class DataSourceTest(unittest.TestCase):
# the feature values here while in this loop. # the feature values here while in this loop.
for fld_name in fld_names: for fld_name in fld_names:
self.assertEqual(source.field_values[fld_name][i], feat.get(fld_name)) self.assertEqual(source.field_values[fld_name][i], feat.get(fld_name))
print "\nEND - expecting out of range feature id error; safe to ignore." print("\nEND - expecting out of range feature id error; safe to ignore.")
def test03b_layer_slice(self): def test03b_layer_slice(self):
"Test indexing and slicing on Layers." "Test indexing and slicing on Layers."

View File

@ -234,7 +234,7 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
# Both rings in this geometry are not closed. # Both rings in this geometry are not closed.
poly = OGRGeometry('POLYGON((0 0, 5 0, 5 5, 0 5), (1 1, 2 1, 2 2, 2 1))') poly = OGRGeometry('POLYGON((0 0, 5 0, 5 5, 0 5), (1 1, 2 1, 2 2, 2 1))')
self.assertEqual(8, poly.point_count) self.assertEqual(8, poly.point_count)
print "\nBEGIN - expecting IllegalArgumentException; safe to ignore.\n" print("\nBEGIN - expecting IllegalArgumentException; safe to ignore.\n")
try: try:
c = poly.centroid c = poly.centroid
except OGRException: except OGRException:
@ -242,7 +242,7 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
pass pass
else: else:
self.fail('Should have raised an OGRException!') self.fail('Should have raised an OGRException!')
print "\nEND - expecting IllegalArgumentException; safe to ignore.\n" print("\nEND - expecting IllegalArgumentException; safe to ignore.\n")
# Closing the rings -- doesn't work on GDAL versions 1.4.1 and below: # Closing the rings -- doesn't work on GDAL versions 1.4.1 and below:
# http://trac.osgeo.org/gdal/ticket/1673 # http://trac.osgeo.org/gdal/ticket/1673

View File

@ -134,7 +134,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
def test01d_errors(self): def test01d_errors(self):
"Testing the Error handlers." "Testing the Error handlers."
# string-based # string-based
print "\nBEGIN - expecting GEOS_ERROR; safe to ignore.\n" print("\nBEGIN - expecting GEOS_ERROR; safe to ignore.\n")
for err in self.geometries.errors: for err in self.geometries.errors:
try: try:
g = fromstr(err.wkt) g = fromstr(err.wkt)
@ -144,7 +144,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
# Bad WKB # Bad WKB
self.assertRaises(GEOSException, GEOSGeometry, buffer('0')) self.assertRaises(GEOSException, GEOSGeometry, buffer('0'))
print "\nEND - expecting GEOS_ERROR; safe to ignore.\n" print("\nEND - expecting GEOS_ERROR; safe to ignore.\n")
class NotAGeometry(object): class NotAGeometry(object):
pass pass
@ -439,7 +439,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
def test05b_multipolygons(self): def test05b_multipolygons(self):
"Testing MultiPolygon objects." "Testing MultiPolygon objects."
print "\nBEGIN - expecting GEOS_NOTICE; safe to ignore.\n" print("\nBEGIN - expecting GEOS_NOTICE; safe to ignore.\n")
prev = fromstr('POINT (0 0)') prev = fromstr('POINT (0 0)')
for mp in self.geometries.multipolygons: for mp in self.geometries.multipolygons:
mpoly = fromstr(mp.wkt) mpoly = fromstr(mp.wkt)
@ -458,7 +458,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
self.assertEqual(p.valid, True) self.assertEqual(p.valid, True)
self.assertEqual(mpoly.wkt, MultiPolygon(*tuple(poly.clone() for poly in mpoly)).wkt) self.assertEqual(mpoly.wkt, MultiPolygon(*tuple(poly.clone() for poly in mpoly)).wkt)
print "\nEND - expecting GEOS_NOTICE; safe to ignore.\n" print("\nEND - expecting GEOS_NOTICE; safe to ignore.\n")
def test06a_memory_hijinks(self): def test06a_memory_hijinks(self):
"Testing Geometry __del__() on rings and polygons." "Testing Geometry __del__() on rings and polygons."
@ -995,7 +995,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
self.assertTrue(isinstance(g.valid_reason, basestring)) self.assertTrue(isinstance(g.valid_reason, basestring))
self.assertEqual(g.valid_reason, "Valid Geometry") self.assertEqual(g.valid_reason, "Valid Geometry")
print "\nBEGIN - expecting GEOS_NOTICE; safe to ignore.\n" print("\nBEGIN - expecting GEOS_NOTICE; safe to ignore.\n")
g = GEOSGeometry("LINESTRING(0 0, 0 0)") g = GEOSGeometry("LINESTRING(0 0, 0 0)")
@ -1003,7 +1003,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin):
self.assertTrue(isinstance(g.valid_reason, basestring)) self.assertTrue(isinstance(g.valid_reason, basestring))
self.assertTrue(g.valid_reason.startswith("Too few points in geometry component")) self.assertTrue(g.valid_reason.startswith("Too few points in geometry component"))
print "\nEND - expecting GEOS_NOTICE; safe to ignore.\n" print("\nEND - expecting GEOS_NOTICE; safe to ignore.\n")
def test28_geos_version(self): def test28_geos_version(self):
"Testing the GEOS version regular expression." "Testing the GEOS version regular expression."

View File

@ -22,19 +22,19 @@ def ogrinfo(data_source, num_features=10):
raise Exception('Data source parameter must be a string or a DataSource object.') raise Exception('Data source parameter must be a string or a DataSource object.')
for i, layer in enumerate(data_source): for i, layer in enumerate(data_source):
print "data source : %s" % data_source.name print("data source : %s" % data_source.name)
print "==== layer %s" % i print("==== layer %s" % i)
print " shape type: %s" % GEO_CLASSES[layer.geom_type.num].__name__ print(" shape type: %s" % GEO_CLASSES[layer.geom_type.num].__name__)
print " # features: %s" % len(layer) print(" # features: %s" % len(layer))
print " srs: %s" % layer.srs print(" srs: %s" % layer.srs)
extent_tup = layer.extent.tuple extent_tup = layer.extent.tuple
print " extent: %s - %s" % (extent_tup[0:2], extent_tup[2:4]) print(" extent: %s - %s" % (extent_tup[0:2], extent_tup[2:4]))
print "Displaying the first %s features ====" % num_features print("Displaying the first %s features ====" % num_features)
width = max(*map(len,layer.fields)) width = max(*map(len,layer.fields))
fmt = " %%%ss: %%s" % width fmt = " %%%ss: %%s" % width
for j, feature in enumerate(layer[:num_features]): for j, feature in enumerate(layer[:num_features]):
print "=== Feature %s" % j print("=== Feature %s" % j)
for fld_name in layer.fields: for fld_name in layer.fields:
type_name = feature[fld_name].type_name type_name = feature[fld_name].type_name
output = fmt % (fld_name, type_name) output = fmt % (fld_name, type_name)
@ -47,7 +47,7 @@ def ogrinfo(data_source, num_features=10):
output += val_fmt % val output += val_fmt % val
else: else:
output += ' (None)' output += ' (None)'
print output print(output)
# For backwards compatibility. # For backwards compatibility.
sample = ogrinfo sample = ogrinfo

View File

@ -68,8 +68,8 @@ def ogrinspect(*args, **kwargs):
shp_file = 'data/mapping_hacks/world_borders.shp' shp_file = 'data/mapping_hacks/world_borders.shp'
model_name = 'WorldBorders' model_name = 'WorldBorders'
print ogrinspect(shp_file, model_name, multi_geom=True, srid=4326, print(ogrinspect(shp_file, model_name, multi_geom=True, srid=4326,
geom_name='shapes', blank=True) geom_name='shapes', blank=True))
Required Arguments Required Arguments
`datasource` => string or DataSource object to file pointer `datasource` => string or DataSource object to file pointer

View File

@ -18,7 +18,7 @@ def create_default_site(app, created_models, verbosity, db, **kwargs):
# the next id will be 1, so we coerce it. See #15573 and #16353. This # the next id will be 1, so we coerce it. See #15573 and #16353. This
# can also crop up outside of tests - see #15346. # can also crop up outside of tests - see #15346.
if verbosity >= 2: if verbosity >= 2:
print "Creating example.com Site object" print("Creating example.com Site object")
Site(pk=1, domain="example.com", name="example.com").save(using=db) Site(pk=1, domain="example.com", name="example.com").save(using=db)
# We set an explicit pk instead of relying on auto-incrementation, # We set an explicit pk instead of relying on auto-incrementation,
@ -26,7 +26,7 @@ def create_default_site(app, created_models, verbosity, db, **kwargs):
sequence_sql = connections[db].ops.sequence_reset_sql(no_style(), [Site]) sequence_sql = connections[db].ops.sequence_reset_sql(no_style(), [Site])
if sequence_sql: if sequence_sql:
if verbosity >= 2: if verbosity >= 2:
print "Resetting sequence" print("Resetting sequence")
cursor = connections[db].cursor() cursor = connections[db].cursor()
for command in sequence_sql: for command in sequence_sql:
cursor.execute(command) cursor.execute(command)

View File

@ -299,7 +299,7 @@ class ManagementUtility(object):
# subcommand # subcommand
if cword == 1: if cword == 1:
print ' '.join(sorted(filter(lambda x: x.startswith(curr), subcommands))) print(' '.join(sorted(filter(lambda x: x.startswith(curr), subcommands))))
# subcommand options # subcommand options
# special case: the 'help' subcommand has no options # special case: the 'help' subcommand has no options
elif cwords[0] in subcommands and cwords[0] != 'help': elif cwords[0] in subcommands and cwords[0] != 'help':
@ -333,7 +333,7 @@ class ManagementUtility(object):
# append '=' to options which require args # append '=' to options which require args
if option[1]: if option[1]:
opt_label += '=' opt_label += '='
print opt_label print(opt_label)
sys.exit(1) sys.exit(1)
def execute(self): def execute(self):

View File

@ -173,7 +173,7 @@ def emit_post_sync_signal(created_models, verbosity, interactive, db):
for app in models.get_apps(): for app in models.get_apps():
app_name = app.__name__.split('.')[-2] app_name = app.__name__.split('.')[-2]
if verbosity >= 2: if verbosity >= 2:
print "Running post-sync handlers for application", app_name print("Running post-sync handlers for application %s" % app_name)
models.signals.post_syncdb.send(sender=app, app=app, models.signals.post_syncdb.send(sender=app, app=app,
created_models=created_models, verbosity=verbosity, created_models=created_models, verbosity=verbosity,
interactive=interactive, db=db) interactive=interactive, db=db)

View File

@ -82,9 +82,9 @@ Examples:
""" % FASTCGI_OPTIONS """ % FASTCGI_OPTIONS
def fastcgi_help(message=None): def fastcgi_help(message=None):
print FASTCGI_HELP print(FASTCGI_HELP)
if message: if message:
print message print(message)
return False return False
def runfastcgi(argset=[], **kwargs): def runfastcgi(argset=[], **kwargs):
@ -103,11 +103,11 @@ def runfastcgi(argset=[], **kwargs):
try: try:
import flup import flup
except ImportError as e: except ImportError as e:
print >> sys.stderr, "ERROR: %s" % e sys.stderr.write("ERROR: %s\n" % e)
print >> sys.stderr, " Unable to load the flup package. In order to run django" sys.stderr.write(" Unable to load the flup package. In order to run django\n")
print >> sys.stderr, " as a FastCGI application, you will need to get flup from" sys.stderr.write(" as a FastCGI application, you will need to get flup from\n")
print >> sys.stderr, " http://www.saddi.com/software/flup/ If you've already" sys.stderr.write(" http://www.saddi.com/software/flup/ If you've already\n")
print >> sys.stderr, " installed flup, then make sure you have it in your PYTHONPATH." sys.stderr.write(" installed flup, then make sure you have it in your PYTHONPATH.\n")
return False return False
flup_module = 'server.' + options['protocol'] flup_module = 'server.' + options['protocol']
@ -136,7 +136,7 @@ def runfastcgi(argset=[], **kwargs):
module = importlib.import_module('.%s' % flup_module, 'flup') module = importlib.import_module('.%s' % flup_module, 'flup')
WSGIServer = module.WSGIServer WSGIServer = module.WSGIServer
except Exception: except Exception:
print "Can't import flup." + flup_module print("Can't import flup." + flup_module)
return False return False
# Prep up and go # Prep up and go

View File

@ -256,8 +256,8 @@ class BaseDatabaseCreation(object):
test_db_repr = '' test_db_repr = ''
if verbosity >= 2: if verbosity >= 2:
test_db_repr = " ('%s')" % test_database_name test_db_repr = " ('%s')" % test_database_name
print "Creating test database for alias '%s'%s..." % ( print("Creating test database for alias '%s'%s..." % (
self.connection.alias, test_db_repr) self.connection.alias, test_db_repr))
self._create_test_db(verbosity, autoclobber) self._create_test_db(verbosity, autoclobber)
@ -339,8 +339,8 @@ class BaseDatabaseCreation(object):
if autoclobber or confirm == 'yes': if autoclobber or confirm == 'yes':
try: try:
if verbosity >= 1: if verbosity >= 1:
print ("Destroying old test database '%s'..." print("Destroying old test database '%s'..."
% self.connection.alias) % self.connection.alias)
cursor.execute( cursor.execute(
"DROP DATABASE %s" % qn(test_database_name)) "DROP DATABASE %s" % qn(test_database_name))
cursor.execute( cursor.execute(
@ -351,7 +351,7 @@ class BaseDatabaseCreation(object):
"Got an error recreating the test database: %s\n" % e) "Got an error recreating the test database: %s\n" % e)
sys.exit(2) sys.exit(2)
else: else:
print "Tests cancelled." print("Tests cancelled.")
sys.exit(1) sys.exit(1)
return test_database_name return test_database_name
@ -367,8 +367,8 @@ class BaseDatabaseCreation(object):
test_db_repr = '' test_db_repr = ''
if verbosity >= 2: if verbosity >= 2:
test_db_repr = " ('%s')" % test_database_name test_db_repr = " ('%s')" % test_database_name
print "Destroying test database for alias '%s'%s..." % ( print("Destroying test database for alias '%s'%s..." % (
self.connection.alias, test_db_repr) self.connection.alias, test_db_repr))
# Temporarily use a new connection and a copy of the settings dict. # Temporarily use a new connection and a copy of the settings dict.
# This prevents the production database from being exposed to potential # This prevents the production database from being exposed to potential

View File

@ -69,19 +69,19 @@ class DatabaseCreation(BaseDatabaseCreation):
if autoclobber or confirm == 'yes': if autoclobber or confirm == 'yes':
try: try:
if verbosity >= 1: if verbosity >= 1:
print "Destroying old test database '%s'..." % self.connection.alias print("Destroying old test database '%s'..." % self.connection.alias)
self._execute_test_db_destruction(cursor, parameters, verbosity) self._execute_test_db_destruction(cursor, parameters, verbosity)
self._execute_test_db_creation(cursor, parameters, verbosity) self._execute_test_db_creation(cursor, parameters, verbosity)
except Exception as e: except Exception as e:
sys.stderr.write("Got an error recreating the test database: %s\n" % e) sys.stderr.write("Got an error recreating the test database: %s\n" % e)
sys.exit(2) sys.exit(2)
else: else:
print "Tests cancelled." print("Tests cancelled.")
sys.exit(1) sys.exit(1)
if self._test_user_create(): if self._test_user_create():
if verbosity >= 1: if verbosity >= 1:
print "Creating test user..." print("Creating test user...")
try: try:
self._create_test_user(cursor, parameters, verbosity) self._create_test_user(cursor, parameters, verbosity)
except Exception as e: except Exception as e:
@ -91,16 +91,16 @@ class DatabaseCreation(BaseDatabaseCreation):
if autoclobber or confirm == 'yes': if autoclobber or confirm == 'yes':
try: try:
if verbosity >= 1: if verbosity >= 1:
print "Destroying old test user..." print("Destroying old test user...")
self._destroy_test_user(cursor, parameters, verbosity) self._destroy_test_user(cursor, parameters, verbosity)
if verbosity >= 1: if verbosity >= 1:
print "Creating test user..." print("Creating test user...")
self._create_test_user(cursor, parameters, verbosity) self._create_test_user(cursor, parameters, verbosity)
except Exception as e: except Exception as e:
sys.stderr.write("Got an error recreating the test user: %s\n" % e) sys.stderr.write("Got an error recreating the test user: %s\n" % e)
sys.exit(2) sys.exit(2)
else: else:
print "Tests cancelled." print("Tests cancelled.")
sys.exit(1) sys.exit(1)
self.connection.settings_dict['SAVED_USER'] = self.connection.settings_dict['USER'] self.connection.settings_dict['SAVED_USER'] = self.connection.settings_dict['USER']
@ -136,17 +136,17 @@ class DatabaseCreation(BaseDatabaseCreation):
time.sleep(1) # To avoid "database is being accessed by other users" errors. time.sleep(1) # To avoid "database is being accessed by other users" errors.
if self._test_user_create(): if self._test_user_create():
if verbosity >= 1: if verbosity >= 1:
print 'Destroying test user...' print('Destroying test user...')
self._destroy_test_user(cursor, parameters, verbosity) self._destroy_test_user(cursor, parameters, verbosity)
if self._test_database_create(): if self._test_database_create():
if verbosity >= 1: if verbosity >= 1:
print 'Destroying test database tables...' print('Destroying test database tables...')
self._execute_test_db_destruction(cursor, parameters, verbosity) self._execute_test_db_destruction(cursor, parameters, verbosity)
self.connection.close() self.connection.close()
def _execute_test_db_creation(self, cursor, parameters, verbosity): def _execute_test_db_creation(self, cursor, parameters, verbosity):
if verbosity >= 2: if verbosity >= 2:
print "_create_test_db(): dbname = %s" % parameters['dbname'] print("_create_test_db(): dbname = %s" % parameters['dbname'])
statements = [ statements = [
"""CREATE TABLESPACE %(tblspace)s """CREATE TABLESPACE %(tblspace)s
DATAFILE '%(tblspace)s.dbf' SIZE 20M DATAFILE '%(tblspace)s.dbf' SIZE 20M
@ -161,7 +161,7 @@ class DatabaseCreation(BaseDatabaseCreation):
def _create_test_user(self, cursor, parameters, verbosity): def _create_test_user(self, cursor, parameters, verbosity):
if verbosity >= 2: if verbosity >= 2:
print "_create_test_user(): username = %s" % parameters['user'] print("_create_test_user(): username = %s" % parameters['user'])
statements = [ statements = [
"""CREATE USER %(user)s """CREATE USER %(user)s
IDENTIFIED BY %(password)s IDENTIFIED BY %(password)s
@ -174,7 +174,7 @@ class DatabaseCreation(BaseDatabaseCreation):
def _execute_test_db_destruction(self, cursor, parameters, verbosity): def _execute_test_db_destruction(self, cursor, parameters, verbosity):
if verbosity >= 2: if verbosity >= 2:
print "_execute_test_db_destruction(): dbname=%s" % parameters['dbname'] print("_execute_test_db_destruction(): dbname=%s" % parameters['dbname'])
statements = [ statements = [
'DROP TABLESPACE %(tblspace)s INCLUDING CONTENTS AND DATAFILES CASCADE CONSTRAINTS', 'DROP TABLESPACE %(tblspace)s INCLUDING CONTENTS AND DATAFILES CASCADE CONSTRAINTS',
'DROP TABLESPACE %(tblspace_temp)s INCLUDING CONTENTS AND DATAFILES CASCADE CONSTRAINTS', 'DROP TABLESPACE %(tblspace_temp)s INCLUDING CONTENTS AND DATAFILES CASCADE CONSTRAINTS',
@ -183,8 +183,8 @@ class DatabaseCreation(BaseDatabaseCreation):
def _destroy_test_user(self, cursor, parameters, verbosity): def _destroy_test_user(self, cursor, parameters, verbosity):
if verbosity >= 2: if verbosity >= 2:
print "_destroy_test_user(): user=%s" % parameters['user'] print("_destroy_test_user(): user=%s" % parameters['user'])
print "Be patient. This can take some time..." print("Be patient. This can take some time...")
statements = [ statements = [
'DROP USER %(user)s CASCADE', 'DROP USER %(user)s CASCADE',
] ]
@ -194,7 +194,7 @@ class DatabaseCreation(BaseDatabaseCreation):
for template in statements: for template in statements:
stmt = template % parameters stmt = template % parameters
if verbosity >= 2: if verbosity >= 2:
print stmt print(stmt)
try: try:
cursor.execute(stmt) cursor.execute(stmt)
except Exception as err: except Exception as err:

View File

@ -50,7 +50,7 @@ class DatabaseCreation(BaseDatabaseCreation):
if test_database_name != ':memory:': if test_database_name != ':memory:':
# Erase the old test database # Erase the old test database
if verbosity >= 1: if verbosity >= 1:
print "Destroying old test database '%s'..." % self.connection.alias print("Destroying old test database '%s'..." % self.connection.alias)
if os.access(test_database_name, os.F_OK): if os.access(test_database_name, os.F_OK):
if not autoclobber: if not autoclobber:
confirm = raw_input("Type 'yes' if you would like to try deleting the test database '%s', or 'no' to cancel: " % test_database_name) confirm = raw_input("Type 'yes' if you would like to try deleting the test database '%s', or 'no' to cancel: " % test_database_name)
@ -61,7 +61,7 @@ class DatabaseCreation(BaseDatabaseCreation):
sys.stderr.write("Got an error deleting the old test database: %s\n" % e) sys.stderr.write("Got an error deleting the old test database: %s\n" % e)
sys.exit(2) sys.exit(2)
else: else:
print "Tests cancelled." print("Tests cancelled.")
sys.exit(1) sys.exit(1)
return test_database_name return test_database_name

View File

@ -122,9 +122,9 @@ class BoundMethodWeakref(object):
except Exception as e: except Exception as e:
try: try:
traceback.print_exc() traceback.print_exc()
except AttributeError as err: except AttributeError:
print '''Exception during saferef %s cleanup function %s: %s'''%( print('Exception during saferef %s cleanup function %s: %s' % (
self, function, e self, function, e)
) )
self.deletionMethods = [onDelete] self.deletionMethods = [onDelete]
self.key = self.calculateKey( target ) self.key = self.calculateKey( target )

View File

@ -878,7 +878,7 @@ class DocTestFinder:
add them to `tests`. add them to `tests`.
""" """
if self._verbose: if self._verbose:
print 'Finding tests in %s' % name print('Finding tests in %s' % name)
# If we've already processed this object, then ignore it. # If we've already processed this object, then ignore it.
if id(obj) in seen: if id(obj) in seen:
@ -1034,7 +1034,7 @@ class DocTestRunner:
>>> tests = DocTestFinder().find(_TestClass) >>> tests = DocTestFinder().find(_TestClass)
>>> runner = DocTestRunner(verbose=False) >>> runner = DocTestRunner(verbose=False)
>>> for test in tests: >>> for test in tests:
... print runner.run(test) ... print(runner.run(test))
(0, 2) (0, 2)
(0, 1) (0, 1)
(0, 2) (0, 2)
@ -1406,28 +1406,28 @@ class DocTestRunner:
failed.append(x) failed.append(x)
if verbose: if verbose:
if notests: if notests:
print len(notests), "items had no tests:" print("%d items had no tests:" % len(notests))
notests.sort() notests.sort()
for thing in notests: for thing in notests:
print " ", thing print(" %s" % thing)
if passed: if passed:
print len(passed), "items passed all tests:" print("%d items passed all tests:" % len(passed))
passed.sort() passed.sort()
for thing, count in passed: for thing, count in passed:
print " %3d tests in %s" % (count, thing) print(" %3d tests in %s" % (count, thing))
if failed: if failed:
print self.DIVIDER print(self.DIVIDER)
print len(failed), "items had failures:" print("%d items had failures:" % len(failed))
failed.sort() failed.sort()
for thing, (f, t) in failed: for thing, (f, t) in failed:
print " %3d of %3d in %s" % (f, t, thing) print(" %3d of %3d in %s" % (f, t, thing))
if verbose: if verbose:
print totalt, "tests in", len(self._name2ft), "items." print("%d tests in % d items" % (len(self._name2ft), totalt))
print totalt - totalf, "passed and", totalf, "failed." print("%d passed and %d failed." % (totalt - totalf, totalf))
if totalf: if totalf:
print "***Test Failed***", totalf, "failures." print("***Test Failed*** %d failures." % totalf)
elif verbose: elif verbose:
print "Test passed." print("Test passed.")
return totalf, totalt return totalf, totalt
#///////////////////////////////////////////////////////////////// #/////////////////////////////////////////////////////////////////
@ -1437,8 +1437,8 @@ class DocTestRunner:
d = self._name2ft d = self._name2ft
for name, (f, t) in other._name2ft.items(): for name, (f, t) in other._name2ft.items():
if name in d: if name in d:
print "*** DocTestRunner.merge: '" + name + "' in both" \ print("*** DocTestRunner.merge: '" + name + "' in both" \
" testers; summing outcomes." " testers; summing outcomes.")
f2, t2 = d[name] f2, t2 = d[name]
f = f + f2 f = f + f2
t = t + t2 t = t + t2
@ -2007,10 +2007,10 @@ class Tester:
def runstring(self, s, name): def runstring(self, s, name):
test = DocTestParser().get_doctest(s, self.globs, name, None, None) test = DocTestParser().get_doctest(s, self.globs, name, None, None)
if self.verbose: if self.verbose:
print "Running string", name print("Running string %s" % name)
(f,t) = self.testrunner.run(test) (f,t) = self.testrunner.run(test)
if self.verbose: if self.verbose:
print f, "of", t, "examples failed in string", name print("%s of %s examples failed in string %s" % (f, t, name))
return (f,t) return (f,t)
def rundoc(self, object, name=None, module=None): def rundoc(self, object, name=None, module=None):
@ -2442,7 +2442,7 @@ def script_from_examples(s):
... Ho hum ... Ho hum
... ''' ... '''
>>> print script_from_examples(text) >>> print(script_from_examples(text))
# Here are examples of simple math. # Here are examples of simple math.
# #
# Python has super accurate integer addition # Python has super accurate integer addition
@ -2533,7 +2533,7 @@ def debug_script(src, pm=False, globs=None):
try: try:
execfile(srcfilename, globs, globs) execfile(srcfilename, globs, globs)
except: except:
print sys.exc_info()[1] print(sys.exc_info()[1])
pdb.post_mortem(sys.exc_info()[2]) pdb.post_mortem(sys.exc_info()[2])
else: else:
# Note that %r is vital here. '%s' instead can, e.g., cause # Note that %r is vital here. '%s' instead can, e.g., cause
@ -2575,7 +2575,7 @@ class _TestClass:
"""val -> _TestClass object with associated value val. """val -> _TestClass object with associated value val.
>>> t = _TestClass(123) >>> t = _TestClass(123)
>>> print t.get() >>> print(t.get())
123 123
""" """
@ -2595,7 +2595,7 @@ class _TestClass:
"""get() -> return TestClass's associated value. """get() -> return TestClass's associated value.
>>> x = _TestClass(-42) >>> x = _TestClass(-42)
>>> print x.get() >>> print(x.get())
-42 -42
""" """
@ -2627,7 +2627,7 @@ __test__ = {"_TestClass": _TestClass,
"blank lines": r""" "blank lines": r"""
Blank lines can be marked with <BLANKLINE>: Blank lines can be marked with <BLANKLINE>:
>>> print 'foo\n\nbar\n' >>> print('foo\n\nbar\n')
foo foo
<BLANKLINE> <BLANKLINE>
bar bar
@ -2637,14 +2637,14 @@ __test__ = {"_TestClass": _TestClass,
"ellipsis": r""" "ellipsis": r"""
If the ellipsis flag is used, then '...' can be used to If the ellipsis flag is used, then '...' can be used to
elide substrings in the desired output: elide substrings in the desired output:
>>> print range(1000) #doctest: +ELLIPSIS >>> print(range(1000)) #doctest: +ELLIPSIS
[0, 1, 2, ..., 999] [0, 1, 2, ..., 999]
""", """,
"whitespace normalization": r""" "whitespace normalization": r"""
If the whitespace normalization flag is used, then If the whitespace normalization flag is used, then
differences in whitespace are ignored. differences in whitespace are ignored.
>>> print range(30) #doctest: +NORMALIZE_WHITESPACE >>> print(range(30)) #doctest: +NORMALIZE_WHITESPACE
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
27, 28, 29] 27, 28, 29]

View File

@ -6,7 +6,7 @@ Usage:
>>> import datetime >>> import datetime
>>> d = datetime.datetime.now() >>> d = datetime.datetime.now()
>>> df = DateFormat(d) >>> df = DateFormat(d)
>>> print df.format('jS F Y H:i') >>> print(df.format('jS F Y H:i'))
7th October 2003 11:39 7th October 2003 11:39
>>> >>>
""" """

View File

@ -33,10 +33,10 @@ def colorize(text='', opts=(), **kwargs):
colorize('hello', fg='red', bg='blue', opts=('blink',)) colorize('hello', fg='red', bg='blue', opts=('blink',))
colorize() colorize()
colorize('goodbye', opts=('underscore',)) colorize('goodbye', opts=('underscore',))
print colorize('first line', fg='red', opts=('noreset',)) print(colorize('first line', fg='red', opts=('noreset',)))
print 'this should be red too' print('this should be red too')
print colorize('and so should this') print(colorize('and so should this'))
print 'this should not be red' print('this should not be red')
""" """
code_list = [] code_list = []
if text == '' and len(opts) == 1 and opts[0] == 'reset': if text == '' and len(opts) == 1 and opts[0] == 'reset':
@ -59,7 +59,7 @@ def make_style(opts=(), **kwargs):
Example: Example:
bold_red = make_style(opts=('bold',), fg='red') bold_red = make_style(opts=('bold',), fg='red')
print bold_red('hello') print(bold_red('hello'))
KEYWORD = make_style(fg='yellow') KEYWORD = make_style(fg='yellow')
COMMENT = make_style(fg='blue', opts=('bold',)) COMMENT = make_style(fg='blue', opts=('bold',))
""" """

View File

@ -99,7 +99,7 @@ class TestProgram(object):
def usageExit(self, msg=None): def usageExit(self, msg=None):
if msg: if msg:
print msg print(msg)
usage = {'progName': self.progName, 'catchbreak': '', 'failfast': '', usage = {'progName': self.progName, 'catchbreak': '', 'failfast': '',
'buffer': ''} 'buffer': ''}
if self.failfast != False: if self.failfast != False:
@ -108,7 +108,7 @@ class TestProgram(object):
usage['catchbreak'] = CATCHBREAK usage['catchbreak'] = CATCHBREAK
if self.buffer != False: if self.buffer != False:
usage['buffer'] = BUFFEROUTPUT usage['buffer'] = BUFFEROUTPUT
print self.USAGE % usage print(self.USAGE % usage)
sys.exit(2) sys.exit(2)
def parseArgs(self, argv): def parseArgs(self, argv):

View File

@ -77,12 +77,12 @@ def main(argv=None):
target_found, lines = has_target(fn) target_found, lines = has_target(fn)
if not target_found: if not target_found:
if testing: if testing:
print '%s: %s' % (fn, lines[0]), print('%s: %s' % (fn, lines[0]))
else: else:
print "Adding xref to %s" % fn print("Adding xref to %s" % fn)
process_file(fn, lines) process_file(fn, lines)
else: else:
print "Skipping %s: already has a xref" % fn print "Skipping %s: already has a xref" % fn
if __name__ == '__main__': if __name__ == '__main__':
sys.exit(main()) sys.exit(main())

View File

@ -136,10 +136,10 @@ def colorize(text='', opts=(), **kwargs):
colorize('hello', fg='red', bg='blue', opts=('blink',)) colorize('hello', fg='red', bg='blue', opts=('blink',))
colorize() colorize()
colorize('goodbye', opts=('underscore',)) colorize('goodbye', opts=('underscore',))
print colorize('first line', fg='red', opts=('noreset',)) print(colorize('first line', fg='red', opts=('noreset',)))
print 'this should be red too' print('this should be red too')
print colorize('and so should this') print(colorize('and so should this'))
print 'this should not be red' print('this should not be red')
""" """
color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white') color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white')
foreground = dict([(color_names[x], '3%s' % x) for x in range(8)]) foreground = dict([(color_names[x], '3%s' % x) for x in range(8)])
@ -168,4 +168,4 @@ if __name__ == '__main__':
try: try:
fixliterals(sys.argv[1]) fixliterals(sys.argv[1])
except (KeyboardInterrupt, SystemExit): except (KeyboardInterrupt, SystemExit):
print print('')

View File

@ -55,7 +55,7 @@ We'd like to be able to do things like this in our models (we assume the
``hand`` attribute on the model is an instance of ``Hand``):: ``hand`` attribute on the model is an instance of ``Hand``)::
example = MyModel.objects.get(pk=1) example = MyModel.objects.get(pk=1)
print example.hand.north print(example.hand.north)
new_hand = Hand(north, east, south, west) new_hand = Hand(north, east, south, west)
example.hand = new_hand example.hand = new_hand

View File

@ -83,7 +83,7 @@ To verify that Django can be seen by Python, type ``python`` from your shell.
Then at the Python prompt, try to import Django:: Then at the Python prompt, try to import Django::
>>> import django >>> import django
>>> print django.get_version() >>> print(django.get_version())
1.4 1.4

View File

@ -76,7 +76,7 @@ transform procedure::
>>> z = Zipcode(code=78212, poly=poly_3084) >>> z = Zipcode(code=78212, poly=poly_3084)
>>> z.save() >>> z.save()
>>> from django.db import connection >>> from django.db import connection
>>> print connection.queries[-1]['sql'] # printing the last SQL statement executed (requires DEBUG=True) >>> print(connection.queries[-1]['sql']) # printing the last SQL statement executed (requires DEBUG=True)
INSERT INTO "geoapp_zipcode" ("code", "poly") VALUES (78212, ST_Transform(ST_GeomFromWKB('\\001 ... ', 3084), 4326)) INSERT INTO "geoapp_zipcode" ("code", "poly") VALUES (78212, ST_Transform(ST_GeomFromWKB('\\001 ... ', 3084), 4326))
Thus, geometry parameters may be passed in using the ``GEOSGeometry`` object, WKT Thus, geometry parameters may be passed in using the ``GEOSGeometry`` object, WKT

View File

@ -114,7 +114,7 @@ __ http://www.gdal.org/ogr/ogr_formats.html
information about each layer in a :class:`DataSource`:: information about each layer in a :class:`DataSource`::
>>> for layer in ds: >>> for layer in ds:
... print 'Layer "%s": %i %ss' % (layer.name, len(layer), layer.geom_type.name) ... print('Layer "%s": %i %ss' % (layer.name, len(layer), layer.geom_type.name))
... ...
Layer "cities": 3 Points Layer "cities": 3 Points
@ -200,7 +200,7 @@ __ http://www.gdal.org/ogr/ogr_formats.html
Property that returns the :class:`SpatialReference` associated Property that returns the :class:`SpatialReference` associated
with this layer:: with this layer::
>>> print layer.srs >>> print(layer.srs)
GEOGCS["GCS_WGS_1984", GEOGCS["GCS_WGS_1984",
DATUM["WGS_1984", DATUM["WGS_1984",
SPHEROID["WGS_1984",6378137,298.257223563]], SPHEROID["WGS_1984",6378137,298.257223563]],
@ -220,9 +220,9 @@ __ http://www.gdal.org/ogr/ogr_formats.html
other than ``None``, only features that intersect the filter will be other than ``None``, only features that intersect the filter will be
returned when iterating over the layer:: returned when iterating over the layer::
>>> print layer.spatial_filter >>> print(layer.spatial_filter)
None None
>>> print len(layer) >>> print(len(layer))
3 3
>>> [feat.get('Name') for feat in layer] >>> [feat.get('Name') for feat in layer]
['Pueblo', 'Lawrence', 'Houston'] ['Pueblo', 'Lawrence', 'Houston']
@ -814,7 +814,7 @@ systems and coordinate transformation::
>>> gt1 = OGRGeomType(3) # Using an integer for the type >>> gt1 = OGRGeomType(3) # Using an integer for the type
>>> gt2 = OGRGeomType('Polygon') # Using a string >>> gt2 = OGRGeomType('Polygon') # Using a string
>>> gt3 = OGRGeomType('POLYGON') # It's case-insensitive >>> gt3 = OGRGeomType('POLYGON') # It's case-insensitive
>>> print gt1 == 3, gt1 == 'Polygon' # Equivalence works w/non-OGRGeomType objects >>> print(gt1 == 3, gt1 == 'Polygon') # Equivalence works w/non-OGRGeomType objects
True True True True
.. attribute:: name .. attribute:: name
@ -927,19 +927,19 @@ Coordinate System Objects
>>> wkt = 'GEOGCS["WGS 84", DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]]') >>> wkt = 'GEOGCS["WGS 84", DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]]')
>>> srs = SpatialReference(wkt) # could also use 'WGS84', or 4326 >>> srs = SpatialReference(wkt) # could also use 'WGS84', or 4326
>>> print srs['GEOGCS'] >>> print(srs['GEOGCS'])
WGS 84 WGS 84
>>> print srs['DATUM'] >>> print(srs['DATUM'])
WGS_1984 WGS_1984
>>> print srs['AUTHORITY'] >>> print(srs['AUTHORITY'])
EPSG EPSG
>>> print srs['AUTHORITY', 1] # The authority value >>> print(srs['AUTHORITY', 1]) # The authority value
4326 4326
>>> print srs['TOWGS84', 4] # the fourth value in this wkt >>> print(srs['TOWGS84', 4]) # the fourth value in this wkt
0 0
>>> print srs['UNIT|AUTHORITY'] # For the units authority, have to use the pipe symbol. >>> print(srs['UNIT|AUTHORITY']) # For the units authority, have to use the pipe symbol.
EPSG EPSG
>>> print srs['UNIT|AUTHORITY', 1] # The authority value for the units >>> print(srs['UNIT|AUTHORITY', 1]) # The authority value for the units
9122 9122
.. method:: attr_value(target, index=0) .. method:: attr_value(target, index=0)

View File

@ -714,7 +714,7 @@ the distance from the `Tasmanian`__ city of Hobart to every other
:class:`PointField` in the ``AustraliaCity`` queryset is calculated:: :class:`PointField` in the ``AustraliaCity`` queryset is calculated::
>>> pnt = AustraliaCity.objects.get(name='Hobart').point >>> pnt = AustraliaCity.objects.get(name='Hobart').point
>>> for city in AustraliaCity.objects.distance(pnt): print city.name, city.distance >>> for city in AustraliaCity.objects.distance(pnt): print(city.name, city.distance)
Wollongong 990071.220408 m Wollongong 990071.220408 m
Shellharbour 972804.613941 m Shellharbour 972804.613941 m
Thirroul 1002334.36351 m Thirroul 1002334.36351 m
@ -874,9 +874,9 @@ Example::
>>> qs = Zipcode.objects.all().transform() # Transforms to WGS84 >>> qs = Zipcode.objects.all().transform() # Transforms to WGS84
>>> qs = Zipcode.objects.all().transform(32140) # Transforming to "NAD83 / Texas South Central" >>> qs = Zipcode.objects.all().transform(32140) # Transforming to "NAD83 / Texas South Central"
>>> print qs[0].poly.srid >>> print(qs[0].poly.srid)
32140 32140
>>> print qs[0].poly >>> print(qs[0].poly)
POLYGON ((234055.1698884720099159 4937796.9232223574072123 ... POLYGON ((234055.1698884720099159 4937796.9232223574072123 ...
``translate`` ``translate``
@ -990,7 +990,7 @@ Attaches a ``gml`` attribute to every model in the queryset that contains the
Example:: Example::
>>> qs = Zipcode.objects.all().gml() >>> qs = Zipcode.objects.all().gml()
>>> print qs[0].gml >>> print(qs[0].gml)
<gml:Polygon srsName="EPSG:4326"><gml:OuterBoundaryIs>-147.78711,70.245363 ... -147.78711,70.245363</gml:OuterBoundaryIs></gml:Polygon> <gml:Polygon srsName="EPSG:4326"><gml:OuterBoundaryIs>-147.78711,70.245363 ... -147.78711,70.245363</gml:OuterBoundaryIs></gml:Polygon>
===================== ===================================================== ===================== =====================================================
@ -1023,7 +1023,7 @@ necessary.
Example:: Example::
>>> qs = Zipcode.objects.all().kml() >>> qs = Zipcode.objects.all().kml()
>>> print qs[0].kml >>> print(qs[0].kml)
<Polygon><outerBoundaryIs><LinearRing><coordinates>-103.04135,36.217596,0 ... -103.04135,36.217596,0</coordinates></LinearRing></outerBoundaryIs></Polygon> <Polygon><outerBoundaryIs><LinearRing><coordinates>-103.04135,36.217596,0 ... -103.04135,36.217596,0</coordinates></LinearRing></outerBoundaryIs></Polygon>
===================== ===================================================== ===================== =====================================================
@ -1128,7 +1128,7 @@ lower left coordinate and the upper right coordinate.
Example:: Example::
>>> qs = City.objects.filter(name__in=('Houston', 'Dallas')) >>> qs = City.objects.filter(name__in=('Houston', 'Dallas'))
>>> print qs.extent() >>> print(qs.extent())
(-96.8016128540039, 29.7633724212646, -95.3631439208984, 32.782058715820) (-96.8016128540039, 29.7633724212646, -95.3631439208984, 32.782058715820)
``extent3d`` ``extent3d``
@ -1146,7 +1146,7 @@ the lower left coordinate and upper right coordinate.
Example:: Example::
>>> qs = City.objects.filter(name__in=('Houston', 'Dallas')) >>> qs = City.objects.filter(name__in=('Houston', 'Dallas'))
>>> print qs.extent3d() >>> print(qs.extent3d())
(-96.8016128540039, 29.7633724212646, 0, -95.3631439208984, 32.782058715820, 0) (-96.8016128540039, 29.7633724212646, 0, -95.3631439208984, 32.782058715820, 0)
``make_line`` ``make_line``
@ -1161,7 +1161,7 @@ Returns a ``LineString`` constructed from the point field geometries in the
Example:: Example::
>>> print City.objects.filter(name__in=('Houston', 'Dallas')).make_line() >>> print(City.objects.filter(name__in=('Houston', 'Dallas')).make_line())
LINESTRING (-95.3631510000000020 29.7633739999999989, -96.8016109999999941 32.7820570000000018) LINESTRING (-95.3631510000000020 29.7633739999999989, -96.8016109999999941 32.7820570000000018)
``unionagg`` ``unionagg``

View File

@ -231,7 +231,7 @@ Property that may be used to retrieve or set the SRID associated with the
geometry. For example:: geometry. For example::
>>> pnt = Point(5, 23) >>> pnt = Point(5, 23)
>>> print pnt.srid >>> print(pnt.srid)
None None
>>> pnt.srid = 4326 >>> pnt.srid = 4326
>>> pnt.srid >>> pnt.srid

View File

@ -39,13 +39,13 @@ Example
>>> from django.contrib.gis.gdal import DataSource >>> from django.contrib.gis.gdal import DataSource
>>> ds = DataSource('test_poly.shp') >>> ds = DataSource('test_poly.shp')
>>> layer = ds[0] >>> layer = ds[0]
>>> print layer.fields # Exploring the fields in the layer, we only want the 'str' field. >>> print(layer.fields) # Exploring the fields in the layer, we only want the 'str' field.
['float', 'int', 'str'] ['float', 'int', 'str']
>>> print len(layer) # getting the number of features in the layer (should be 3) >>> print(len(layer)) # getting the number of features in the layer (should be 3)
3 3
>>> print layer.geom_type # Should be 'Polygon' >>> print(layer.geom_type) # Should be 'Polygon'
Polygon Polygon
>>> print layer.srs # WGS84 in WKT >>> print(layer.srs) # WGS84 in WKT
GEOGCS["GCS_WGS_1984", GEOGCS["GCS_WGS_1984",
DATUM["WGS_1984", DATUM["WGS_1984",
SPHEROID["WGS_1984",6378137,298.257223563]], SPHEROID["WGS_1984",6378137,298.257223563]],

View File

@ -22,41 +22,41 @@ instantiated in units of kilometers (``km``) and miles (``mi``)::
>>> from django.contrib.gis.measure import Distance, D >>> from django.contrib.gis.measure import Distance, D
>>> d1 = Distance(km=5) >>> d1 = Distance(km=5)
>>> print d1 >>> print(d1)
5.0 km 5.0 km
>>> d2 = D(mi=5) # `D` is an alias for `Distance` >>> d2 = D(mi=5) # `D` is an alias for `Distance`
>>> print d2 >>> print(d2)
5.0 mi 5.0 mi
Conversions are easy, just access the preferred unit attribute to get a Conversions are easy, just access the preferred unit attribute to get a
converted distance quantity:: converted distance quantity::
>>> print d1.mi # Converting 5 kilometers to miles >>> print(d1.mi) # Converting 5 kilometers to miles
3.10685596119 3.10685596119
>>> print d2.km # Converting 5 miles to kilometers >>> print(d2.km) # Converting 5 miles to kilometers
8.04672 8.04672
Moreover, arithmetic operations may be performed between the distance Moreover, arithmetic operations may be performed between the distance
objects:: objects::
>>> print d1 + d2 # Adding 5 miles to 5 kilometers >>> print(d1 + d2) # Adding 5 miles to 5 kilometers
13.04672 km 13.04672 km
>>> print d2 - d1 # Subtracting 5 kilometers from 5 miles >>> print(d2 - d1) # Subtracting 5 kilometers from 5 miles
1.89314403881 mi 1.89314403881 mi
Two :class:`Distance` objects multiplied together will yield an :class:`Area` Two :class:`Distance` objects multiplied together will yield an :class:`Area`
object, which uses squared units of measure:: object, which uses squared units of measure::
>>> a = d1 * d2 # Returns an Area object. >>> a = d1 * d2 # Returns an Area object.
>>> print a >>> print(a)
40.2336 sq_km 40.2336 sq_km
To determine what the attribute abbreviation of a unit is, the ``unit_attname`` To determine what the attribute abbreviation of a unit is, the ``unit_attname``
class method may be used:: class method may be used::
>>> print Distance.unit_attname('US Survey Foot') >>> print(Distance.unit_attname('US Survey Foot'))
survey_ft survey_ft
>>> print Distance.unit_attname('centimeter') >>> print(Distance.unit_attname('centimeter'))
cm cm
.. _supported_units: .. _supported_units:
@ -127,7 +127,7 @@ Measurement API
Returns the distance value in units corresponding to the given unit Returns the distance value in units corresponding to the given unit
attribute. For example:: attribute. For example::
>>> print dist.km >>> print(dist.km)
8.04672 8.04672
.. classmethod:: unit_attname(unit_name) .. classmethod:: unit_attname(unit_name)
@ -159,7 +159,7 @@ Measurement API
Returns the area value in units corresponding to the given unit Returns the area value in units corresponding to the given unit
attribute. For example:: attribute. For example::
>>> print a.sq_km >>> print(a.sq_km)
12.949940551680001 12.949940551680001
.. classmethod:: unit_attname(unit_name) .. classmethod:: unit_attname(unit_name)

View File

@ -362,24 +362,24 @@ Now, the world borders shapefile may be opened using GeoDjango's
>>> from django.contrib.gis.gdal import DataSource >>> from django.contrib.gis.gdal import DataSource
>>> ds = DataSource(world_shp) >>> ds = DataSource(world_shp)
>>> print ds >>> print(ds)
/ ... /geodjango/world/data/TM_WORLD_BORDERS-0.3.shp (ESRI Shapefile) / ... /geodjango/world/data/TM_WORLD_BORDERS-0.3.shp (ESRI Shapefile)
Data source objects can have different layers of geospatial features; however, Data source objects can have different layers of geospatial features; however,
shapefiles are only allowed to have one layer:: shapefiles are only allowed to have one layer::
>>> print len(ds) >>> print(len(ds))
1 1
>>> lyr = ds[0] >>> lyr = ds[0]
>>> print lyr >>> print(lyr)
TM_WORLD_BORDERS-0.3 TM_WORLD_BORDERS-0.3
You can see what the geometry type of the layer is and how many features it You can see what the geometry type of the layer is and how many features it
contains:: contains::
>>> print lyr.geom_type >>> print(lyr.geom_type)
Polygon Polygon
>>> print len(lyr) >>> print(len(lyr))
246 246
.. note:: .. note::
@ -397,7 +397,7 @@ system associated with it -- if it does, the ``srs`` attribute will return a
:class:`~django.contrib.gis.gdal.SpatialReference` object:: :class:`~django.contrib.gis.gdal.SpatialReference` object::
>>> srs = lyr.srs >>> srs = lyr.srs
>>> print srs >>> print(srs)
GEOGCS["GCS_WGS_1984", GEOGCS["GCS_WGS_1984",
DATUM["WGS_1984", DATUM["WGS_1984",
SPHEROID["WGS_1984",6378137.0,298.257223563]], SPHEROID["WGS_1984",6378137.0,298.257223563]],
@ -413,7 +413,7 @@ latitude.
In addition, shapefiles also support attribute fields that may contain In addition, shapefiles also support attribute fields that may contain
additional data. Here are the fields on the World Borders layer: additional data. Here are the fields on the World Borders layer:
>>> print lyr.fields >>> print(lyr.fields)
['FIPS', 'ISO2', 'ISO3', 'UN', 'NAME', 'AREA', 'POP2005', 'REGION', 'SUBREGION', 'LON', 'LAT'] ['FIPS', 'ISO2', 'ISO3', 'UN', 'NAME', 'AREA', 'POP2005', 'REGION', 'SUBREGION', 'LON', 'LAT']
Here we are examining the OGR types (e.g., whether a field is an integer or Here we are examining the OGR types (e.g., whether a field is an integer or
@ -428,7 +428,7 @@ feature's attribute fields (whose **values** are accessed via ``get()``
method):: method)::
>>> for feat in lyr: >>> for feat in lyr:
... print feat.get('NAME'), feat.geom.num_points ... print(feat.get('NAME'), feat.geom.num_points)
... ...
Guernsey 18 Guernsey 18
Jersey 26 Jersey 26
@ -443,16 +443,16 @@ method)::
And individual features may be retrieved by their feature ID:: And individual features may be retrieved by their feature ID::
>>> feat = lyr[234] >>> feat = lyr[234]
>>> print feat.get('NAME') >>> print(feat.get('NAME'))
San Marino San Marino
Here the boundary geometry for San Marino is extracted and looking Here the boundary geometry for San Marino is extracted and looking
exported to WKT and GeoJSON:: exported to WKT and GeoJSON::
>>> geom = feat.geom >>> geom = feat.geom
>>> print geom.wkt >>> print(geom.wkt)
POLYGON ((12.415798 43.957954,12.450554 ... POLYGON ((12.415798 43.957954,12.450554 ...
>>> print geom.json >>> print(geom.json)
{ "type": "Polygon", "coordinates": [ [ [ 12.415798, 43.957954 ], [ 12.450554, 43.979721 ], ... { "type": "Polygon", "coordinates": [ [ [ 12.415798, 43.957954 ], [ 12.450554, 43.979721 ], ...
@ -659,7 +659,7 @@ in transformation SQL, allowing the developer to work at a higher level
of abstraction:: of abstraction::
>>> qs = WorldBorder.objects.filter(mpoly__intersects=pnt) >>> qs = WorldBorder.objects.filter(mpoly__intersects=pnt)
>>> print qs.query # Generating the SQL >>> print(qs.query) # Generating the SQL
SELECT "world_worldborder"."id", "world_worldborder"."name", "world_worldborder"."area", SELECT "world_worldborder"."id", "world_worldborder"."name", "world_worldborder"."area",
"world_worldborder"."pop2005", "world_worldborder"."fips", "world_worldborder"."iso2", "world_worldborder"."pop2005", "world_worldborder"."fips", "world_worldborder"."iso2",
"world_worldborder"."iso3", "world_worldborder"."un", "world_worldborder"."region", "world_worldborder"."iso3", "world_worldborder"."un", "world_worldborder"."region",

View File

@ -891,7 +891,7 @@ For example, to create an Atom 1.0 feed and print it to standard output::
... link=u"http://www.example.com/entries/1/", ... link=u"http://www.example.com/entries/1/",
... pubdate=datetime.now(), ... pubdate=datetime.now(),
... description=u"<p>Today I had a Vienna Beef hot dog. It was pink, plump and perfect.</p>") ... description=u"<p>Today I had a Vienna Beef hot dog. It was pink, plump and perfect.</p>")
>>> print f.writeString('UTF-8') >>> print(f.writeString('UTF-8'))
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"> <feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
... ...

View File

@ -161,7 +161,7 @@ and the latter gets precedence::
... url = forms.URLField() ... url = forms.URLField()
... comment = forms.CharField() ... comment = forms.CharField()
>>> f = CommentForm(initial={'name': 'instance'}, auto_id=False) >>> f = CommentForm(initial={'name': 'instance'}, auto_id=False)
>>> print f >>> print(f)
<tr><th>Name:</th><td><input type="text" name="name" value="instance" /></td></tr> <tr><th>Name:</th><td><input type="text" name="name" value="instance" /></td></tr>
<tr><th>Url:</th><td><input type="text" name="url" /></td></tr> <tr><th>Url:</th><td><input type="text" name="url" /></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr> <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
@ -266,7 +266,7 @@ The second task of a ``Form`` object is to render itself as HTML. To do so,
simply ``print`` it:: simply ``print`` it::
>>> f = ContactForm() >>> f = ContactForm()
>>> print f >>> print(f)
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr> <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr> <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>
<tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr> <tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr>
@ -283,7 +283,7 @@ include ``checked="checked"`` if appropriate::
... 'sender': 'foo@example.com', ... 'sender': 'foo@example.com',
... 'cc_myself': True} ... 'cc_myself': True}
>>> f = ContactForm(data) >>> f = ContactForm(data)
>>> print f >>> print(f)
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" value="hello" /></td></tr> <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" value="hello" /></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" value="Hi there" /></td></tr> <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" value="Hi there" /></td></tr>
<tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" value="foo@example.com" /></td></tr> <tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" value="foo@example.com" /></td></tr>
@ -331,7 +331,7 @@ a form object, and each rendering method returns a Unicode object.
>>> f = ContactForm() >>> f = ContactForm()
>>> f.as_p() >>> f.as_p()
u'<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p>\n<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>\n<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></p>\n<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>' u'<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p>\n<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>\n<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></p>\n<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>'
>>> print f.as_p() >>> print(f.as_p())
<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p> <p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p>
<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p> <p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>
<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></p> <p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></p>
@ -350,7 +350,7 @@ a form object, and each rendering method returns a Unicode object.
>>> f = ContactForm() >>> f = ContactForm()
>>> f.as_ul() >>> f.as_ul()
u'<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li>\n<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>\n<li><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></li>\n<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>' u'<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li>\n<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>\n<li><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></li>\n<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>'
>>> print f.as_ul() >>> print(f.as_ul())
<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li> <li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li>
<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li> <li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>
<li><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></li> <li><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></li>
@ -368,7 +368,7 @@ a form object, and each rendering method returns a Unicode object.
>>> f = ContactForm() >>> f = ContactForm()
>>> f.as_table() >>> f.as_table()
u'<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>\n<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>\n<tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr>\n<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>' u'<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>\n<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>\n<tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr>\n<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>'
>>> print f.as_table() >>> print(f.as_table())
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr> <tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr> <tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>
<tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr> <tr><th><label for="id_sender">Sender:</label></th><td><input type="text" name="sender" id="id_sender" /></td></tr>
@ -398,7 +398,7 @@ Once you've done that, rows will be given ``"error"`` and/or ``"required"``
classes, as needed. The HTML will look something like:: classes, as needed. The HTML will look something like::
>>> f = ContactForm(data) >>> f = ContactForm(data)
>>> print f.as_table() >>> print(f.as_table())
<tr class="required"><th><label for="id_subject">Subject:</label> ... <tr class="required"><th><label for="id_subject">Subject:</label> ...
<tr class="required"><th><label for="id_message">Message:</label> ... <tr class="required"><th><label for="id_message">Message:</label> ...
<tr class="required error"><th><label for="id_sender">Sender:</label> ... <tr class="required error"><th><label for="id_sender">Sender:</label> ...
@ -426,17 +426,17 @@ If ``auto_id`` is ``False``, then the form output will not include ``<label>``
tags nor ``id`` attributes:: tags nor ``id`` attributes::
>>> f = ContactForm(auto_id=False) >>> f = ContactForm(auto_id=False)
>>> print f.as_table() >>> print(f.as_table())
<tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" /></td></tr> <tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" /></td></tr>
<tr><th>Message:</th><td><input type="text" name="message" /></td></tr> <tr><th>Message:</th><td><input type="text" name="message" /></td></tr>
<tr><th>Sender:</th><td><input type="text" name="sender" /></td></tr> <tr><th>Sender:</th><td><input type="text" name="sender" /></td></tr>
<tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr> <tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr>
>>> print f.as_ul() >>> print(f.as_ul())
<li>Subject: <input type="text" name="subject" maxlength="100" /></li> <li>Subject: <input type="text" name="subject" maxlength="100" /></li>
<li>Message: <input type="text" name="message" /></li> <li>Message: <input type="text" name="message" /></li>
<li>Sender: <input type="text" name="sender" /></li> <li>Sender: <input type="text" name="sender" /></li>
<li>Cc myself: <input type="checkbox" name="cc_myself" /></li> <li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
>>> print f.as_p() >>> print(f.as_p())
<p>Subject: <input type="text" name="subject" maxlength="100" /></p> <p>Subject: <input type="text" name="subject" maxlength="100" /></p>
<p>Message: <input type="text" name="message" /></p> <p>Message: <input type="text" name="message" /></p>
<p>Sender: <input type="text" name="sender" /></p> <p>Sender: <input type="text" name="sender" /></p>
@ -447,17 +447,17 @@ If ``auto_id`` is set to ``True``, then the form output *will* include
field:: field::
>>> f = ContactForm(auto_id=True) >>> f = ContactForm(auto_id=True)
>>> print f.as_table() >>> print(f.as_table())
<tr><th><label for="subject">Subject:</label></th><td><input id="subject" type="text" name="subject" maxlength="100" /></td></tr> <tr><th><label for="subject">Subject:</label></th><td><input id="subject" type="text" name="subject" maxlength="100" /></td></tr>
<tr><th><label for="message">Message:</label></th><td><input type="text" name="message" id="message" /></td></tr> <tr><th><label for="message">Message:</label></th><td><input type="text" name="message" id="message" /></td></tr>
<tr><th><label for="sender">Sender:</label></th><td><input type="text" name="sender" id="sender" /></td></tr> <tr><th><label for="sender">Sender:</label></th><td><input type="text" name="sender" id="sender" /></td></tr>
<tr><th><label for="cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="cc_myself" /></td></tr> <tr><th><label for="cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="cc_myself" /></td></tr>
>>> print f.as_ul() >>> print(f.as_ul())
<li><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" /></li> <li><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" /></li>
<li><label for="message">Message:</label> <input type="text" name="message" id="message" /></li> <li><label for="message">Message:</label> <input type="text" name="message" id="message" /></li>
<li><label for="sender">Sender:</label> <input type="text" name="sender" id="sender" /></li> <li><label for="sender">Sender:</label> <input type="text" name="sender" id="sender" /></li>
<li><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself" /></li> <li><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself" /></li>
>>> print f.as_p() >>> print(f.as_p())
<p><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" /></p> <p><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" /></p>
<p><label for="message">Message:</label> <input type="text" name="message" id="message" /></p> <p><label for="message">Message:</label> <input type="text" name="message" id="message" /></p>
<p><label for="sender">Sender:</label> <input type="text" name="sender" id="sender" /></p> <p><label for="sender">Sender:</label> <input type="text" name="sender" id="sender" /></p>
@ -470,17 +470,17 @@ attributes based on the format string. For example, for a format string
``'field_subject'``. Continuing our example:: ``'field_subject'``. Continuing our example::
>>> f = ContactForm(auto_id='id_for_%s') >>> f = ContactForm(auto_id='id_for_%s')
>>> print f.as_table() >>> print(f.as_table())
<tr><th><label for="id_for_subject">Subject:</label></th><td><input id="id_for_subject" type="text" name="subject" maxlength="100" /></td></tr> <tr><th><label for="id_for_subject">Subject:</label></th><td><input id="id_for_subject" type="text" name="subject" maxlength="100" /></td></tr>
<tr><th><label for="id_for_message">Message:</label></th><td><input type="text" name="message" id="id_for_message" /></td></tr> <tr><th><label for="id_for_message">Message:</label></th><td><input type="text" name="message" id="id_for_message" /></td></tr>
<tr><th><label for="id_for_sender">Sender:</label></th><td><input type="text" name="sender" id="id_for_sender" /></td></tr> <tr><th><label for="id_for_sender">Sender:</label></th><td><input type="text" name="sender" id="id_for_sender" /></td></tr>
<tr><th><label for="id_for_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></td></tr> <tr><th><label for="id_for_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></td></tr>
>>> print f.as_ul() >>> print(f.as_ul())
<li><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li> <li><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li>
<li><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" /></li> <li><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" /></li>
<li><label for="id_for_sender">Sender:</label> <input type="text" name="sender" id="id_for_sender" /></li> <li><label for="id_for_sender">Sender:</label> <input type="text" name="sender" id="id_for_sender" /></li>
<li><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li> <li><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li>
>>> print f.as_p() >>> print(f.as_p())
<p><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></p> <p><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></p>
<p><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" /></p> <p><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" /></p>
<p><label for="id_for_sender">Sender:</label> <input type="text" name="sender" id="id_for_sender" /></p> <p><label for="id_for_sender">Sender:</label> <input type="text" name="sender" id="id_for_sender" /></p>
@ -496,13 +496,13 @@ rendered. It's possible to change the colon to another character, or omit it
entirely, using the ``label_suffix`` parameter:: entirely, using the ``label_suffix`` parameter::
>>> f = ContactForm(auto_id='id_for_%s', label_suffix='') >>> f = ContactForm(auto_id='id_for_%s', label_suffix='')
>>> print f.as_ul() >>> print(f.as_ul())
<li><label for="id_for_subject">Subject</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li> <li><label for="id_for_subject">Subject</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li>
<li><label for="id_for_message">Message</label> <input type="text" name="message" id="id_for_message" /></li> <li><label for="id_for_message">Message</label> <input type="text" name="message" id="id_for_message" /></li>
<li><label for="id_for_sender">Sender</label> <input type="text" name="sender" id="id_for_sender" /></li> <li><label for="id_for_sender">Sender</label> <input type="text" name="sender" id="id_for_sender" /></li>
<li><label for="id_for_cc_myself">Cc myself</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li> <li><label for="id_for_cc_myself">Cc myself</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li>
>>> f = ContactForm(auto_id='id_for_%s', label_suffix=' ->') >>> f = ContactForm(auto_id='id_for_%s', label_suffix=' ->')
>>> print f.as_ul() >>> print(f.as_ul())
<li><label for="id_for_subject">Subject -></label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li> <li><label for="id_for_subject">Subject -></label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li>
<li><label for="id_for_message">Message -></label> <input type="text" name="message" id="id_for_message" /></li> <li><label for="id_for_message">Message -></label> <input type="text" name="message" id="id_for_message" /></li>
<li><label for="id_for_sender">Sender -></label> <input type="text" name="sender" id="id_for_sender" /></li> <li><label for="id_for_sender">Sender -></label> <input type="text" name="sender" id="id_for_sender" /></li>
@ -534,17 +534,17 @@ method you're using::
... 'sender': 'invalid email address', ... 'sender': 'invalid email address',
... 'cc_myself': True} ... 'cc_myself': True}
>>> f = ContactForm(data, auto_id=False) >>> f = ContactForm(data, auto_id=False)
>>> print f.as_table() >>> print(f.as_table())
<tr><th>Subject:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="subject" maxlength="100" /></td></tr> <tr><th>Subject:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="subject" maxlength="100" /></td></tr>
<tr><th>Message:</th><td><input type="text" name="message" value="Hi there" /></td></tr> <tr><th>Message:</th><td><input type="text" name="message" value="Hi there" /></td></tr>
<tr><th>Sender:</th><td><ul class="errorlist"><li>Enter a valid e-mail address.</li></ul><input type="text" name="sender" value="invalid email address" /></td></tr> <tr><th>Sender:</th><td><ul class="errorlist"><li>Enter a valid e-mail address.</li></ul><input type="text" name="sender" value="invalid email address" /></td></tr>
<tr><th>Cc myself:</th><td><input checked="checked" type="checkbox" name="cc_myself" /></td></tr> <tr><th>Cc myself:</th><td><input checked="checked" type="checkbox" name="cc_myself" /></td></tr>
>>> print f.as_ul() >>> print(f.as_ul())
<li><ul class="errorlist"><li>This field is required.</li></ul>Subject: <input type="text" name="subject" maxlength="100" /></li> <li><ul class="errorlist"><li>This field is required.</li></ul>Subject: <input type="text" name="subject" maxlength="100" /></li>
<li>Message: <input type="text" name="message" value="Hi there" /></li> <li>Message: <input type="text" name="message" value="Hi there" /></li>
<li><ul class="errorlist"><li>Enter a valid e-mail address.</li></ul>Sender: <input type="text" name="sender" value="invalid email address" /></li> <li><ul class="errorlist"><li>Enter a valid e-mail address.</li></ul>Sender: <input type="text" name="sender" value="invalid email address" /></li>
<li>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></li> <li>Cc myself: <input checked="checked" type="checkbox" name="cc_myself" /></li>
>>> print f.as_p() >>> print(f.as_p())
<p><ul class="errorlist"><li>This field is required.</li></ul></p> <p><ul class="errorlist"><li>This field is required.</li></ul></p>
<p>Subject: <input type="text" name="subject" maxlength="100" /></p> <p>Subject: <input type="text" name="subject" maxlength="100" /></p>
<p>Message: <input type="text" name="message" value="Hi there" /></p> <p>Message: <input type="text" name="message" value="Hi there" /></p>
@ -593,13 +593,13 @@ To retrieve a single ``BoundField``, use dictionary lookup syntax on your form
using the field's name as the key:: using the field's name as the key::
>>> form = ContactForm() >>> form = ContactForm()
>>> print form['subject'] >>> print(form['subject'])
<input id="id_subject" type="text" name="subject" maxlength="100" /> <input id="id_subject" type="text" name="subject" maxlength="100" />
To retrieve all ``BoundField`` objects, iterate the form:: To retrieve all ``BoundField`` objects, iterate the form::
>>> form = ContactForm() >>> form = ContactForm()
>>> for boundfield in form: print boundfield >>> for boundfield in form: print(boundfield)
<input id="id_subject" type="text" name="subject" maxlength="100" /> <input id="id_subject" type="text" name="subject" maxlength="100" />
<input type="text" name="message" id="id_message" /> <input type="text" name="message" id="id_message" />
<input type="text" name="sender" id="id_sender" /> <input type="text" name="sender" id="id_sender" />
@ -608,10 +608,10 @@ To retrieve all ``BoundField`` objects, iterate the form::
The field-specific output honors the form object's ``auto_id`` setting:: The field-specific output honors the form object's ``auto_id`` setting::
>>> f = ContactForm(auto_id=False) >>> f = ContactForm(auto_id=False)
>>> print f['message'] >>> print(f['message'])
<input type="text" name="message" /> <input type="text" name="message" />
>>> f = ContactForm(auto_id='id_%s') >>> f = ContactForm(auto_id='id_%s')
>>> print f['message'] >>> print(f['message'])
<input type="text" name="message" id="id_message" /> <input type="text" name="message" id="id_message" />
For a field's list of errors, access the field's ``errors`` attribute. For a field's list of errors, access the field's ``errors`` attribute.
@ -623,15 +623,15 @@ For a field's list of errors, access the field's ``errors`` attribute.
>>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''} >>> data = {'subject': 'hi', 'message': '', 'sender': '', 'cc_myself': ''}
>>> f = ContactForm(data, auto_id=False) >>> f = ContactForm(data, auto_id=False)
>>> print f['message'] >>> print(f['message'])
<input type="text" name="message" /> <input type="text" name="message" />
>>> f['message'].errors >>> f['message'].errors
[u'This field is required.'] [u'This field is required.']
>>> print f['message'].errors >>> print(f['message'].errors)
<ul class="errorlist"><li>This field is required.</li></ul> <ul class="errorlist"><li>This field is required.</li></ul>
>>> f['subject'].errors >>> f['subject'].errors
[] []
>>> print f['subject'].errors >>> print(f['subject'].errors)
>>> str(f['subject'].errors) >>> str(f['subject'].errors)
'' ''
@ -667,9 +667,9 @@ by a ``Widget``::
>>> initial = {'subject': 'welcome'} >>> initial = {'subject': 'welcome'}
>>> unbound_form = ContactForm(initial=initial) >>> unbound_form = ContactForm(initial=initial)
>>> bound_form = ContactForm(data, initial=initial) >>> bound_form = ContactForm(data, initial=initial)
>>> print unbound_form['subject'].value() >>> print(unbound_form['subject'].value())
welcome welcome
>>> print bound_form['subject'].value() >>> print(bound_form['subject'].value())
hi hi
.. _binding-uploaded-files: .. _binding-uploaded-files:
@ -753,7 +753,7 @@ fields are ordered first::
>>> class ContactFormWithPriority(ContactForm): >>> class ContactFormWithPriority(ContactForm):
... priority = forms.CharField() ... priority = forms.CharField()
>>> f = ContactFormWithPriority(auto_id=False) >>> f = ContactFormWithPriority(auto_id=False)
>>> print f.as_ul() >>> print(f.as_ul())
<li>Subject: <input type="text" name="subject" maxlength="100" /></li> <li>Subject: <input type="text" name="subject" maxlength="100" /></li>
<li>Message: <input type="text" name="message" /></li> <li>Message: <input type="text" name="message" /></li>
<li>Sender: <input type="text" name="sender" /></li> <li>Sender: <input type="text" name="sender" /></li>
@ -773,7 +773,7 @@ classes::
>>> class BeatleForm(PersonForm, InstrumentForm): >>> class BeatleForm(PersonForm, InstrumentForm):
... haircut_type = CharField() ... haircut_type = CharField()
>>> b = BeatleForm(auto_id=False) >>> b = BeatleForm(auto_id=False)
>>> print b.as_ul() >>> print(b.as_ul())
<li>First name: <input type="text" name="first_name" /></li> <li>First name: <input type="text" name="first_name" /></li>
<li>Last name: <input type="text" name="last_name" /></li> <li>Last name: <input type="text" name="last_name" /></li>
<li>Instrument: <input type="text" name="instrument" /></li> <li>Instrument: <input type="text" name="instrument" /></li>
@ -791,9 +791,9 @@ You can put several Django forms inside one ``<form>`` tag. To give each
>>> mother = PersonForm(prefix="mother") >>> mother = PersonForm(prefix="mother")
>>> father = PersonForm(prefix="father") >>> father = PersonForm(prefix="father")
>>> print mother.as_ul() >>> print(mother.as_ul())
<li><label for="id_mother-first_name">First name:</label> <input type="text" name="mother-first_name" id="id_mother-first_name" /></li> <li><label for="id_mother-first_name">First name:</label> <input type="text" name="mother-first_name" id="id_mother-first_name" /></li>
<li><label for="id_mother-last_name">Last name:</label> <input type="text" name="mother-last_name" id="id_mother-last_name" /></li> <li><label for="id_mother-last_name">Last name:</label> <input type="text" name="mother-last_name" id="id_mother-last_name" /></li>
>>> print father.as_ul() >>> print(father.as_ul())
<li><label for="id_father-first_name">First name:</label> <input type="text" name="father-first_name" id="id_father-first_name" /></li> <li><label for="id_father-first_name">First name:</label> <input type="text" name="father-first_name" id="id_father-first_name" /></li>
<li><label for="id_father-last_name">Last name:</label> <input type="text" name="father-last_name" id="id_father-last_name" /></li> <li><label for="id_father-last_name">Last name:</label> <input type="text" name="father-last_name" id="id_father-last_name" /></li>

View File

@ -112,7 +112,7 @@ We've specified ``auto_id=False`` to simplify the output::
... url = forms.URLField(label='Your Web site', required=False) ... url = forms.URLField(label='Your Web site', required=False)
... comment = forms.CharField() ... comment = forms.CharField()
>>> f = CommentForm(auto_id=False) >>> f = CommentForm(auto_id=False)
>>> print f >>> print(f)
<tr><th>Your name:</th><td><input type="text" name="name" /></td></tr> <tr><th>Your name:</th><td><input type="text" name="name" /></td></tr>
<tr><th>Your Web site:</th><td><input type="text" name="url" /></td></tr> <tr><th>Your Web site:</th><td><input type="text" name="url" /></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr> <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
@ -135,7 +135,7 @@ field is initialized to a particular value. For example::
... url = forms.URLField(initial='http://') ... url = forms.URLField(initial='http://')
... comment = forms.CharField() ... comment = forms.CharField()
>>> f = CommentForm(auto_id=False) >>> f = CommentForm(auto_id=False)
>>> print f >>> print(f)
<tr><th>Name:</th><td><input type="text" name="name" value="Your name" /></td></tr> <tr><th>Name:</th><td><input type="text" name="name" value="Your name" /></td></tr>
<tr><th>Url:</th><td><input type="text" name="url" value="http://" /></td></tr> <tr><th>Url:</th><td><input type="text" name="url" value="http://" /></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr> <tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>
@ -150,7 +150,7 @@ and the HTML output will include any validation errors::
... comment = forms.CharField() ... comment = forms.CharField()
>>> default_data = {'name': 'Your name', 'url': 'http://'} >>> default_data = {'name': 'Your name', 'url': 'http://'}
>>> f = CommentForm(default_data, auto_id=False) >>> f = CommentForm(default_data, auto_id=False)
>>> print f >>> print(f)
<tr><th>Name:</th><td><input type="text" name="name" value="Your name" /></td></tr> <tr><th>Name:</th><td><input type="text" name="name" value="Your name" /></td></tr>
<tr><th>Url:</th><td><ul class="errorlist"><li>Enter a valid URL.</li></ul><input type="text" name="url" value="http://" /></td></tr> <tr><th>Url:</th><td><ul class="errorlist"><li>Enter a valid URL.</li></ul><input type="text" name="url" value="http://" /></td></tr>
<tr><th>Comment:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="comment" /></td></tr> <tr><th>Comment:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="comment" /></td></tr>
@ -179,7 +179,7 @@ Instead of a constant, you can also pass any callable::
>>> import datetime >>> import datetime
>>> class DateForm(forms.Form): >>> class DateForm(forms.Form):
... day = forms.DateField(initial=datetime.date.today) ... day = forms.DateField(initial=datetime.date.today)
>>> print DateForm() >>> print(DateForm())
<tr><th>Day:</th><td><input type="text" name="day" value="12/23/2008" /><td></tr> <tr><th>Day:</th><td><input type="text" name="day" value="12/23/2008" /><td></tr>
The callable will be evaluated only when the unbound form is displayed, not when it is defined. The callable will be evaluated only when the unbound form is displayed, not when it is defined.
@ -211,17 +211,17 @@ fields. We've specified ``auto_id=False`` to simplify the output::
... sender = forms.EmailField(help_text='A valid email address, please.') ... sender = forms.EmailField(help_text='A valid email address, please.')
... cc_myself = forms.BooleanField(required=False) ... cc_myself = forms.BooleanField(required=False)
>>> f = HelpTextContactForm(auto_id=False) >>> f = HelpTextContactForm(auto_id=False)
>>> print f.as_table() >>> print(f.as_table())
<tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" /><br /><span class="helptext">100 characters max.</span></td></tr> <tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" /><br /><span class="helptext">100 characters max.</span></td></tr>
<tr><th>Message:</th><td><input type="text" name="message" /></td></tr> <tr><th>Message:</th><td><input type="text" name="message" /></td></tr>
<tr><th>Sender:</th><td><input type="text" name="sender" /><br />A valid email address, please.</td></tr> <tr><th>Sender:</th><td><input type="text" name="sender" /><br />A valid email address, please.</td></tr>
<tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr> <tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr>
>>> print f.as_ul() >>> print(f.as_ul()))
<li>Subject: <input type="text" name="subject" maxlength="100" /> <span class="helptext">100 characters max.</span></li> <li>Subject: <input type="text" name="subject" maxlength="100" /> <span class="helptext">100 characters max.</span></li>
<li>Message: <input type="text" name="message" /></li> <li>Message: <input type="text" name="message" /></li>
<li>Sender: <input type="text" name="sender" /> A valid email address, please.</li> <li>Sender: <input type="text" name="sender" /> A valid email address, please.</li>
<li>Cc myself: <input type="checkbox" name="cc_myself" /></li> <li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
>>> print f.as_p() >>> print(f.as_p())
<p>Subject: <input type="text" name="subject" maxlength="100" /> <span class="helptext">100 characters max.</span></p> <p>Subject: <input type="text" name="subject" maxlength="100" /> <span class="helptext">100 characters max.</span></p>
<p>Message: <input type="text" name="message" /></p> <p>Message: <input type="text" name="message" /></p>
<p>Sender: <input type="text" name="sender" /> A valid email address, please.</p> <p>Sender: <input type="text" name="sender" /> A valid email address, please.</p>

View File

@ -327,7 +327,7 @@ Once the object has been saved, you must reload the object in order to access
the actual value that was applied to the updated field:: the actual value that was applied to the updated field::
>>> product = Products.objects.get(pk=product.pk) >>> product = Products.objects.get(pk=product.pk)
>>> print product.number_sold >>> print(product.number_sold)
42 42
For more details, see the documentation on :ref:`F() expressions For more details, see the documentation on :ref:`F() expressions

View File

@ -29,7 +29,7 @@ You can evaluate a ``QuerySet`` in the following ways:
the headline of all entries in the database:: the headline of all entries in the database::
for e in Entry.objects.all(): for e in Entry.objects.all():
print e.headline print(e.headline)
* **Slicing.** As explained in :ref:`limiting-querysets`, a ``QuerySet`` can * **Slicing.** As explained in :ref:`limiting-querysets`, a ``QuerySet`` can
be sliced, using Python's array-slicing syntax. Slicing an unevaluated be sliced, using Python's array-slicing syntax. Slicing an unevaluated
@ -71,7 +71,7 @@ You can evaluate a ``QuerySet`` in the following ways:
``True``, otherwise ``False``. For example:: ``True``, otherwise ``False``. For example::
if Entry.objects.filter(headline="Test"): if Entry.objects.filter(headline="Test"):
print "There is at least one Entry with the headline Test" print("There is at least one Entry with the headline Test")
Note: *Don't* use this if all you want to do is determine if at least one Note: *Don't* use this if all you want to do is determine if at least one
result exists, and don't need the actual objects. It's more efficient to result exists, and don't need the actual objects. It's more efficient to
@ -1251,7 +1251,7 @@ The :exc:`~django.core.exceptions.DoesNotExist` exception inherits from
e = Entry.objects.get(id=3) e = Entry.objects.get(id=3)
b = Blog.objects.get(id=1) b = Blog.objects.get(id=1)
except ObjectDoesNotExist: except ObjectDoesNotExist:
print "Either the entry or blog doesn't exist." print("Either the entry or blog doesn't exist.")
create create
~~~~~~ ~~~~~~

View File

@ -215,18 +215,18 @@ the content of the response manually::
# Set up a rendered TemplateResponse # Set up a rendered TemplateResponse
>>> t = TemplateResponse(request, 'original.html', {}) >>> t = TemplateResponse(request, 'original.html', {})
>>> t.render() >>> t.render()
>>> print t.content >>> print(t.content)
Original content Original content
# Re-rendering doesn't change content # Re-rendering doesn't change content
>>> t.template_name = 'new.html' >>> t.template_name = 'new.html'
>>> t.render() >>> t.render()
>>> print t.content >>> print(t.content)
Original content Original content
# Assigning content does change, no render() call required # Assigning content does change, no render() call required
>>> t.content = t.rendered_content >>> t.content = t.rendered_content
>>> print t.content >>> print(t.content)
New content New content
Post-render callbacks Post-render callbacks

View File

@ -69,7 +69,7 @@ takes one argument -- the raw template code::
>>> from django.template import Template >>> from django.template import Template
>>> t = Template("My name is {{ my_name }}.") >>> t = Template("My name is {{ my_name }}.")
>>> print t >>> print(t)
<django.template.Template instance> <django.template.Template instance>
.. admonition:: Behind the scenes .. admonition:: Behind the scenes

View File

@ -714,11 +714,11 @@ Django provides two functions in :mod:`django.contrib.auth`:
user = authenticate(username='john', password='secret') user = authenticate(username='john', password='secret')
if user is not None: if user is not None:
if user.is_active: if user.is_active:
print "You provided a correct username and password!" print("You provided a correct username and password!")
else: else:
print "Your account has been disabled!" print("Your account has been disabled!")
else: else:
print "Your username and password were incorrect." print("Your username and password were incorrect.")
.. function:: login() .. function:: login()

View File

@ -263,14 +263,14 @@ Bulk delete some Publications - references to deleted publications should go::
Bulk delete some articles - references to deleted objects should go:: Bulk delete some articles - references to deleted objects should go::
>>> q = Article.objects.filter(headline__startswith='Django') >>> q = Article.objects.filter(headline__startswith='Django')
>>> print q >>> print(q)
[<Article: Django lets you build Web apps easily>] [<Article: Django lets you build Web apps easily>]
>>> q.delete() >>> q.delete()
After the delete, the QuerySet cache needs to be cleared, and the referenced After the delete, the QuerySet cache needs to be cleared, and the referenced
objects should be gone:: objects should be gone::
>>> print q >>> print(q)
[] []
>>> p1.article_set.all() >>> p1.article_set.all()
[<Article: NASA uses Python>] [<Article: NASA uses Python>]

View File

@ -284,10 +284,10 @@ actually run the query until the :class:`~django.db.models.query.QuerySet` is
>>> q = Entry.objects.filter(headline__startswith="What") >>> q = Entry.objects.filter(headline__startswith="What")
>>> q = q.filter(pub_date__lte=datetime.now()) >>> q = q.filter(pub_date__lte=datetime.now())
>>> q = q.exclude(body_text__icontains="food") >>> q = q.exclude(body_text__icontains="food")
>>> print q >>> print(q)
Though this looks like three database hits, in fact it hits the database only Though this looks like three database hits, in fact it hits the database only
once, at the last line (``print q``). In general, the results of a once, at the last line (``print(q)``). In general, the results of a
:class:`~django.db.models.query.QuerySet` aren't fetched from the database :class:`~django.db.models.query.QuerySet` aren't fetched from the database
until you "ask" for them. When you do, the until you "ask" for them. When you do, the
:class:`~django.db.models.query.QuerySet` is *evaluated* by accessing the :class:`~django.db.models.query.QuerySet` is *evaluated* by accessing the
@ -720,8 +720,8 @@ your :class:`~django.db.models.query.QuerySet`\s correctly. For example, the
following will create two :class:`~django.db.models.query.QuerySet`\s, evaluate following will create two :class:`~django.db.models.query.QuerySet`\s, evaluate
them, and throw them away:: them, and throw them away::
>>> print [e.headline for e in Entry.objects.all()] >>> print([e.headline for e in Entry.objects.all()])
>>> print [e.pub_date for e in Entry.objects.all()] >>> print([e.pub_date for e in Entry.objects.all()])
That means the same database query will be executed twice, effectively doubling That means the same database query will be executed twice, effectively doubling
your database load. Also, there's a possibility the two lists may not include your database load. Also, there's a possibility the two lists may not include
@ -732,8 +732,8 @@ To avoid this problem, simply save the
:class:`~django.db.models.query.QuerySet` and reuse it:: :class:`~django.db.models.query.QuerySet` and reuse it::
>>> queryset = Entry.objects.all() >>> queryset = Entry.objects.all()
>>> print [p.headline for p in queryset] # Evaluate the query set. >>> print([p.headline for p in queryset]) # Evaluate the query set.
>>> print [p.pub_date for p in queryset] # Re-use the cache from the evaluation. >>> print([p.pub_date for p in queryset]) # Re-use the cache from the evaluation.
.. _complex-lookups-with-q: .. _complex-lookups-with-q:
@ -1055,16 +1055,16 @@ related object is accessed. Subsequent accesses to the foreign key on the same
object instance are cached. Example:: object instance are cached. Example::
>>> e = Entry.objects.get(id=2) >>> e = Entry.objects.get(id=2)
>>> print e.blog # Hits the database to retrieve the associated Blog. >>> print(e.blog) # Hits the database to retrieve the associated Blog.
>>> print e.blog # Doesn't hit the database; uses cached version. >>> print(e.blog) # Doesn't hit the database; uses cached version.
Note that the :meth:`~django.db.models.query.QuerySet.select_related` Note that the :meth:`~django.db.models.query.QuerySet.select_related`
:class:`~django.db.models.query.QuerySet` method recursively prepopulates the :class:`~django.db.models.query.QuerySet` method recursively prepopulates the
cache of all one-to-many relationships ahead of time. Example:: cache of all one-to-many relationships ahead of time. Example::
>>> e = Entry.objects.select_related().get(id=2) >>> e = Entry.objects.select_related().get(id=2)
>>> print e.blog # Doesn't hit the database; uses cached version. >>> print(e.blog) # Doesn't hit the database; uses cached version.
>>> print e.blog # Doesn't hit the database; uses cached version. >>> print(e.blog) # Doesn't hit the database; uses cached version.
.. _backwards-related-objects: .. _backwards-related-objects:

View File

@ -40,7 +40,7 @@ This is best illustrated with an example. Suppose you've got the following model
You could then execute custom SQL like so:: You could then execute custom SQL like so::
>>> for p in Person.objects.raw('SELECT * FROM myapp_person'): >>> for p in Person.objects.raw('SELECT * FROM myapp_person'):
... print p ... print(p)
John Smith John Smith
Jane Jones Jane Jones
@ -128,8 +128,8 @@ The ``Person`` objects returned by this query will be deferred model instances
fields that are omitted from the query will be loaded on demand. For example:: fields that are omitted from the query will be loaded on demand. For example::
>>> for p in Person.objects.raw('SELECT id, first_name FROM myapp_person'): >>> for p in Person.objects.raw('SELECT id, first_name FROM myapp_person'):
... print p.first_name, # This will be retrieved by the original query ... print(p.first_name, # This will be retrieved by the original query
... print p.last_name # This will be retrieved on demand ... p.last_name) # This will be retrieved on demand
... ...
John Smith John Smith
Jane Jones Jane Jones
@ -153,7 +153,7 @@ of people with their ages calculated by the database::
>>> people = Person.objects.raw('SELECT *, age(birth_date) AS age FROM myapp_person') >>> people = Person.objects.raw('SELECT *, age(birth_date) AS age FROM myapp_person')
>>> for p in people: >>> for p in people:
... print "%s is %s." % (p.first_name, p.age) ... print("%s is %s." % (p.first_name, p.age))
John is 37. John is 37.
Jane is 42. Jane is 42.
... ...

View File

@ -24,7 +24,7 @@ would with a regular form::
>>> formset = ArticleFormSet() >>> formset = ArticleFormSet()
>>> for form in formset: >>> for form in formset:
... print form.as_table() ... print(form.as_table())
<tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" id="id_form-0-title" /></td></tr> <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" id="id_form-0-title" /></td></tr>
<tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" id="id_form-0-pub_date" /></td></tr> <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" id="id_form-0-pub_date" /></td></tr>
@ -42,7 +42,7 @@ the formset you iterated over the ``forms`` attribute::
>>> formset = ArticleFormSet() >>> formset = ArticleFormSet()
>>> for form in formset.forms: >>> for form in formset.forms:
... print form.as_table() ... print(form.as_table())
Iterating over ``formset.forms`` will render the forms in the order Iterating over ``formset.forms`` will render the forms in the order
they were created. The default formset iterator also renders the forms they were created. The default formset iterator also renders the forms
@ -71,7 +71,7 @@ example::
... ]) ... ])
>>> for form in formset: >>> for form in formset:
... print form.as_table() ... print(form.as_table())
<tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" value="Django is now open source" id="id_form-0-title" /></td></tr> <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" value="Django is now open source" id="id_form-0-title" /></td></tr>
<tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" value="2008-05-12" id="id_form-0-pub_date" /></td></tr> <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" value="2008-05-12" id="id_form-0-pub_date" /></td></tr>
<tr><th><label for="id_form-1-title">Title:</label></th><td><input type="text" name="form-1-title" id="id_form-1-title" /></td></tr> <tr><th><label for="id_form-1-title">Title:</label></th><td><input type="text" name="form-1-title" id="id_form-1-title" /></td></tr>
@ -98,7 +98,7 @@ limit the maximum number of empty forms the formset will display::
>>> ArticleFormSet = formset_factory(ArticleForm, extra=2, max_num=1) >>> ArticleFormSet = formset_factory(ArticleForm, extra=2, max_num=1)
>>> formset = ArticleFormset() >>> formset = ArticleFormset()
>>> for form in formset: >>> for form in formset:
... print form.as_table() ... print(form.as_table())
<tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" id="id_form-0-title" /></td></tr> <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" id="id_form-0-title" /></td></tr>
<tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" id="id_form-0-pub_date" /></td></tr> <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" id="id_form-0-pub_date" /></td></tr>
@ -283,7 +283,7 @@ Lets you create a formset with the ability to order::
... {'title': u'Article #2', 'pub_date': datetime.date(2008, 5, 11)}, ... {'title': u'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
... ]) ... ])
>>> for form in formset: >>> for form in formset:
... print form.as_table() ... print(form.as_table())
<tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" value="Article #1" id="id_form-0-title" /></td></tr> <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" value="Article #1" id="id_form-0-title" /></td></tr>
<tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" value="2008-05-10" id="id_form-0-pub_date" /></td></tr> <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" value="2008-05-10" id="id_form-0-pub_date" /></td></tr>
<tr><th><label for="id_form-0-ORDER">Order:</label></th><td><input type="text" name="form-0-ORDER" value="1" id="id_form-0-ORDER" /></td></tr> <tr><th><label for="id_form-0-ORDER">Order:</label></th><td><input type="text" name="form-0-ORDER" value="1" id="id_form-0-ORDER" /></td></tr>
@ -321,7 +321,7 @@ happen when the user changes these values::
>>> formset.is_valid() >>> formset.is_valid()
True True
>>> for form in formset.ordered_forms: >>> for form in formset.ordered_forms:
... print form.cleaned_data ... print(form.cleaned_data)
{'pub_date': datetime.date(2008, 5, 1), 'ORDER': 0, 'title': u'Article #3'} {'pub_date': datetime.date(2008, 5, 1), 'ORDER': 0, 'title': u'Article #3'}
{'pub_date': datetime.date(2008, 5, 11), 'ORDER': 1, 'title': u'Article #2'} {'pub_date': datetime.date(2008, 5, 11), 'ORDER': 1, 'title': u'Article #2'}
{'pub_date': datetime.date(2008, 5, 10), 'ORDER': 2, 'title': u'Article #1'} {'pub_date': datetime.date(2008, 5, 10), 'ORDER': 2, 'title': u'Article #1'}
@ -339,7 +339,7 @@ Lets you create a formset with the ability to delete::
... {'title': u'Article #2', 'pub_date': datetime.date(2008, 5, 11)}, ... {'title': u'Article #2', 'pub_date': datetime.date(2008, 5, 11)},
... ]) ... ])
>>> for form in formset: >>> for form in formset:
.... print form.as_table() .... print(form.as_table())
<input type="hidden" name="form-TOTAL_FORMS" value="3" id="id_form-TOTAL_FORMS" /><input type="hidden" name="form-INITIAL_FORMS" value="2" id="id_form-INITIAL_FORMS" /><input type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS" /> <input type="hidden" name="form-TOTAL_FORMS" value="3" id="id_form-TOTAL_FORMS" /><input type="hidden" name="form-INITIAL_FORMS" value="2" id="id_form-INITIAL_FORMS" /><input type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS" />
<tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" value="Article #1" id="id_form-0-title" /></td></tr> <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" value="Article #1" id="id_form-0-title" /></td></tr>
<tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" value="2008-05-10" id="id_form-0-pub_date" /></td></tr> <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" value="2008-05-10" id="id_form-0-pub_date" /></td></tr>
@ -393,7 +393,7 @@ default fields/attributes of the order and deletion fields::
>>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet) >>> ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet)
>>> formset = ArticleFormSet() >>> formset = ArticleFormSet()
>>> for form in formset: >>> for form in formset:
... print form.as_table() ... print(form.as_table())
<tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" id="id_form-0-title" /></td></tr> <tr><th><label for="id_form-0-title">Title:</label></th><td><input type="text" name="form-0-title" id="id_form-0-title" /></td></tr>
<tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" id="id_form-0-pub_date" /></td></tr> <tr><th><label for="id_form-0-pub_date">Pub date:</label></th><td><input type="text" name="form-0-pub_date" id="id_form-0-pub_date" /></td></tr>
<tr><th><label for="id_form-0-my_field">My field:</label></th><td><input type="text" name="form-0-my_field" id="id_form-0-my_field" /></td></tr> <tr><th><label for="id_form-0-my_field">My field:</label></th><td><input type="text" name="form-0-my_field" id="id_form-0-my_field" /></td></tr>

View File

@ -64,7 +64,7 @@ named ``media``. The media for a CalendarWidget instance can be retrieved
through this property:: through this property::
>>> w = CalendarWidget() >>> w = CalendarWidget()
>>> print w.media >>> print(w.media)
<link href="http://media.example.com/pretty.css" type="text/css" media="all" rel="stylesheet" /> <link href="http://media.example.com/pretty.css" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="http://media.example.com/animations.js"></script> <script type="text/javascript" src="http://media.example.com/animations.js"></script>
<script type="text/javascript" src="http://media.example.com/actions.js"></script> <script type="text/javascript" src="http://media.example.com/actions.js"></script>
@ -139,7 +139,7 @@ basic Calendar widget from the example above::
... js = ('whizbang.js',) ... js = ('whizbang.js',)
>>> w = FancyCalendarWidget() >>> w = FancyCalendarWidget()
>>> print w.media >>> print(w.media)
<link href="http://media.example.com/pretty.css" type="text/css" media="all" rel="stylesheet" /> <link href="http://media.example.com/pretty.css" type="text/css" media="all" rel="stylesheet" />
<link href="http://media.example.com/fancy.css" type="text/css" media="all" rel="stylesheet" /> <link href="http://media.example.com/fancy.css" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="http://media.example.com/animations.js"></script> <script type="text/javascript" src="http://media.example.com/animations.js"></script>
@ -159,7 +159,7 @@ declaration to the media declaration::
... js = ('whizbang.js',) ... js = ('whizbang.js',)
>>> w = FancyCalendarWidget() >>> w = FancyCalendarWidget()
>>> print w.media >>> print(w.media)
<link href="http://media.example.com/fancy.css" type="text/css" media="all" rel="stylesheet" /> <link href="http://media.example.com/fancy.css" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="http://media.example.com/whizbang.js"></script> <script type="text/javascript" src="http://media.example.com/whizbang.js"></script>
@ -221,7 +221,7 @@ was ``None``::
... js = ('animations.js', 'http://othersite.com/actions.js') ... js = ('animations.js', 'http://othersite.com/actions.js')
>>> w = CalendarWidget() >>> w = CalendarWidget()
>>> print w.media >>> print(w.media)
<link href="/css/pretty.css" type="text/css" media="all" rel="stylesheet" /> <link href="/css/pretty.css" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="http://uploads.example.com/animations.js"></script> <script type="text/javascript" src="http://uploads.example.com/animations.js"></script>
<script type="text/javascript" src="http://othersite.com/actions.js"></script> <script type="text/javascript" src="http://othersite.com/actions.js"></script>
@ -229,7 +229,7 @@ was ``None``::
But if :setting:`STATIC_URL` is ``'http://static.example.com/'``:: But if :setting:`STATIC_URL` is ``'http://static.example.com/'``::
>>> w = CalendarWidget() >>> w = CalendarWidget()
>>> print w.media >>> print(w.media)
<link href="/css/pretty.css" type="text/css" media="all" rel="stylesheet" /> <link href="/css/pretty.css" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="http://static.example.com/animations.js"></script> <script type="text/javascript" src="http://static.example.com/animations.js"></script>
<script type="text/javascript" src="http://othersite.com/actions.js"></script> <script type="text/javascript" src="http://othersite.com/actions.js"></script>
@ -252,12 +252,12 @@ If you only want media of a particular type, you can use the subscript operator
to filter out a medium of interest. For example:: to filter out a medium of interest. For example::
>>> w = CalendarWidget() >>> w = CalendarWidget()
>>> print w.media >>> print(w.media)
<link href="http://media.example.com/pretty.css" type="text/css" media="all" rel="stylesheet" /> <link href="http://media.example.com/pretty.css" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="http://media.example.com/animations.js"></script> <script type="text/javascript" src="http://media.example.com/animations.js"></script>
<script type="text/javascript" src="http://media.example.com/actions.js"></script> <script type="text/javascript" src="http://media.example.com/actions.js"></script>
>>> print w.media['css'] >>> print(w.media)['css']
<link href="http://media.example.com/pretty.css" type="text/css" media="all" rel="stylesheet" /> <link href="http://media.example.com/pretty.css" type="text/css" media="all" rel="stylesheet" />
When you use the subscript operator, the value that is returned is a new When you use the subscript operator, the value that is returned is a new
@ -282,7 +282,7 @@ the resulting Media object contains the union of the media from both files::
>>> w1 = CalendarWidget() >>> w1 = CalendarWidget()
>>> w2 = OtherWidget() >>> w2 = OtherWidget()
>>> print w1.media + w2.media >>> print(w1.media + w2.media)
<link href="http://media.example.com/pretty.css" type="text/css" media="all" rel="stylesheet" /> <link href="http://media.example.com/pretty.css" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="http://media.example.com/animations.js"></script> <script type="text/javascript" src="http://media.example.com/animations.js"></script>
<script type="text/javascript" src="http://media.example.com/actions.js"></script> <script type="text/javascript" src="http://media.example.com/actions.js"></script>

View File

@ -556,7 +556,7 @@ This will create a formset that is capable of working with the data associated
with the ``Author`` model. It works just like a regular formset:: with the ``Author`` model. It works just like a regular formset::
>>> formset = AuthorFormSet() >>> formset = AuthorFormSet()
>>> print formset >>> print(formset)
<input type="hidden" name="form-TOTAL_FORMS" value="1" id="id_form-TOTAL_FORMS" /><input type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS" /><input type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS" /> <input type="hidden" name="form-TOTAL_FORMS" value="1" id="id_form-TOTAL_FORMS" /><input type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS" /><input type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS" />
<tr><th><label for="id_form-0-name">Name:</label></th><td><input id="id_form-0-name" type="text" name="form-0-name" maxlength="100" /></td></tr> <tr><th><label for="id_form-0-name">Name:</label></th><td><input id="id_form-0-name" type="text" name="form-0-name" maxlength="100" /></td></tr>
<tr><th><label for="id_form-0-title">Title:</label></th><td><select name="form-0-title" id="id_form-0-title"> <tr><th><label for="id_form-0-title">Title:</label></th><td><select name="form-0-title" id="id_form-0-title">
@ -692,7 +692,7 @@ so long as the total number of forms does not exceed ``max_num``::
>>> AuthorFormSet = modelformset_factory(Author, max_num=4, extra=2) >>> AuthorFormSet = modelformset_factory(Author, max_num=4, extra=2)
>>> formset = AuthorFormSet(queryset=Author.objects.order_by('name')) >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))
>>> for form in formset: >>> for form in formset:
... print form.as_table() ... print(form.as_table())
<tr><th><label for="id_form-0-name">Name:</label></th><td><input id="id_form-0-name" type="text" name="form-0-name" value="Charles Baudelaire" maxlength="100" /><input type="hidden" name="form-0-id" value="1" id="id_form-0-id" /></td></tr> <tr><th><label for="id_form-0-name">Name:</label></th><td><input id="id_form-0-name" type="text" name="form-0-name" value="Charles Baudelaire" maxlength="100" /><input type="hidden" name="form-0-id" value="1" id="id_form-0-id" /></td></tr>
<tr><th><label for="id_form-1-name">Name:</label></th><td><input id="id_form-1-name" type="text" name="form-1-name" value="Paul Verlaine" maxlength="100" /><input type="hidden" name="form-1-id" value="3" id="id_form-1-id" /></td></tr> <tr><th><label for="id_form-1-name">Name:</label></th><td><input id="id_form-1-name" type="text" name="form-1-name" value="Paul Verlaine" maxlength="100" /><input type="hidden" name="form-1-id" value="3" id="id_form-1-id" /></td></tr>
<tr><th><label for="id_form-2-name">Name:</label></th><td><input id="id_form-2-name" type="text" name="form-2-name" value="Walt Whitman" maxlength="100" /><input type="hidden" name="form-2-id" value="2" id="id_form-2-id" /></td></tr> <tr><th><label for="id_form-2-name">Name:</label></th><td><input id="id_form-2-name" type="text" name="form-2-name" value="Walt Whitman" maxlength="100" /><input type="hidden" name="form-2-id" value="2" id="id_form-2-id" /></td></tr>

View File

@ -964,7 +964,7 @@ information about the URL pattern that matches a URL::
# Resolve a URL # Resolve a URL
match = resolve('/some/path/') match = resolve('/some/path/')
# Print the URL pattern that matches the URL # Print the URL pattern that matches the URL
print match.url_name print(match.url_name)
A :class:`ResolverMatch` object can also be assigned to a triple:: A :class:`ResolverMatch` object can also be assigned to a triple::

View File

@ -436,7 +436,7 @@ languages::
>>> from django.utils.translation import get_language_info >>> from django.utils.translation import get_language_info
>>> li = get_language_info('de') >>> li = get_language_info('de')
>>> print li['name'], li['name_local'], li['bidi'] >>> print(li['name'], li['name_local'], li['bidi'])
German Deutsch False German Deutsch False
The ``name`` and ``name_local`` attributes of the dictionary contain the name of The ``name`` and ``name_local`` attributes of the dictionary contain the name of

View File

@ -172,7 +172,7 @@ This file should also be located in your ``site-packages`` directory.
.. code-block:: bash .. code-block:: bash
python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()" python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"
(Note that this should be run from a shell prompt, not a Python interactive (Note that this should be run from a shell prompt, not a Python interactive
prompt.) prompt.)

View File

@ -83,7 +83,7 @@ function or method:
.. code-block:: python .. code-block:: python
def my_callback(sender, **kwargs): def my_callback(sender, **kwargs):
print "Request finished!" print("Request finished!")
Notice that the function takes a ``sender`` argument, along with wildcard Notice that the function takes a ``sender`` argument, along with wildcard
keyword arguments (``**kwargs``); all signal handlers must take these arguments. keyword arguments (``**kwargs``); all signal handlers must take these arguments.
@ -125,7 +125,7 @@ receiver:
@receiver(request_finished) @receiver(request_finished)
def my_callback(sender, **kwargs): def my_callback(sender, **kwargs):
print "Request finished!" print("Request finished!")
Now, our ``my_callback`` function will be called each time a request finishes. Now, our ``my_callback`` function will be called each time a request finishes.

View File

@ -64,7 +64,7 @@ If the signature or value have been altered in any way, a
>>> try: >>> try:
... original = signer.unsign(value) ... original = signer.unsign(value)
... except signing.BadSignature: ... except signing.BadSignature:
... print "Tampering detected!" ... print("Tampering detected!")
By default, the ``Signer`` class uses the :setting:`SECRET_KEY` setting to By default, the ``Signer`` class uses the :setting:`SECRET_KEY` setting to
generate signatures. You can use a different secret by passing it to the generate signatures. You can use a different secret by passing it to the

View File

@ -319,29 +319,29 @@ def main(pythonpaths):
found = search_python_list(python_code, to_search) found = search_python_list(python_code, to_search)
# Display: # Display:
print t.absolute_filename print(t.absolute_filename)
for r in t.relative_filenames: for r in t.relative_filenames:
print u" AKA %s" % r print(" AKA %s" % r)
print u" POST forms: %s" % num_post_forms print(" POST forms: %s" % num_post_forms)
print u" With token: %s" % (num_post_forms - len(form_lines_without_token)) print(" With token: %s" % (num_post_forms - len(form_lines_without_token)))
if form_lines_without_token: if form_lines_without_token:
print u" Without token:" print(" Without token:")
for ln in form_lines_without_token: for ln in form_lines_without_token:
print "%s:%d:" % (t.absolute_filename, ln) print("%s:%d:" % (t.absolute_filename, ln))
print print('')
print u" Searching for:" print(" Searching for:")
for r in to_search: for r in to_search:
print u" " + r print(" " + r)
print print('')
print u" Found:" print(" Found:")
if len(found) == 0: if len(found) == 0:
print " Nothing" print(" Nothing")
else: else:
for fn, ln in found: for fn, ln in found:
print "%s:%d:" % (fn, ln) print("%s:%d:" % (fn, ln))
print print('')
print "----" print("----")
parser = OptionParser(usage=USAGE) parser = OptionParser(usage=USAGE)
@ -356,7 +356,7 @@ if __name__ == '__main__':
settings = getattr(options, 'settings', None) settings = getattr(options, 'settings', None)
if settings is None: if settings is None:
if os.environ.get("DJANGO_SETTINGS_MODULE", None) is None: if os.environ.get("DJANGO_SETTINGS_MODULE", None) is None:
print "You need to set DJANGO_SETTINGS_MODULE or use the '--settings' parameter" print("You need to set DJANGO_SETTINGS_MODULE or use the '--settings' parameter")
sys.exit(1) sys.exit(1)
else: else:
os.environ["DJANGO_SETTINGS_MODULE"] = settings os.environ["DJANGO_SETTINGS_MODULE"] = settings

View File

@ -7,5 +7,5 @@ class Command(AppCommand):
args = '[appname ...]' args = '[appname ...]'
def handle_app(self, app, **options): def handle_app(self, app, **options):
print 'EXECUTE:AppCommand app=%s, options=%s' % (app, sorted(options.items())) print('EXECUTE:AppCommand app=%s, options=%s' % (app, sorted(options.items())))

View File

@ -14,4 +14,4 @@ class Command(BaseCommand):
args = '[labels ...]' args = '[labels ...]'
def handle(self, *labels, **options): def handle(self, *labels, **options):
print 'EXECUTE:BaseCommand labels=%s, options=%s' % (labels, sorted(options.items())) print('EXECUTE:BaseCommand labels=%s, options=%s' % (labels, sorted(options.items())))

View File

@ -7,4 +7,4 @@ class Command(LabelCommand):
args = '<label>' args = '<label>'
def handle_label(self, label, **options): def handle_label(self, label, **options):
print 'EXECUTE:LabelCommand label=%s, options=%s' % (label, sorted(options.items())) print('EXECUTE:LabelCommand label=%s, options=%s' % (label, sorted(options.items())))

View File

@ -7,4 +7,4 @@ class Command(NoArgsCommand):
def handle_noargs(self, **options): def handle_noargs(self, **options):
print 'EXECUTE:NoArgsCommand options=%s' % sorted(options.items()) print('EXECUTE:NoArgsCommand options=%s' % sorted(options.items()))

View File

@ -166,7 +166,7 @@ class CustomOptionsTestRunner(simple.DjangoTestSuiteRunner):
self.option_c = option_c self.option_c = option_c
def run_tests(self, test_labels, extra_tests=None, **kwargs): def run_tests(self, test_labels, extra_tests=None, **kwargs):
print "%s:%s:%s" % (self.option_a, self.option_b, self.option_c) print("%s:%s:%s" % (self.option_a, self.option_b, self.option_c))
class CustomTestRunnerOptionsTests(AdminScriptTestCase): class CustomTestRunnerOptionsTests(AdminScriptTestCase):

View File

@ -126,7 +126,7 @@ def setup(verbosity, test_labels):
# this module and add it to the list to test. # this module and add it to the list to test.
if not test_labels or module_name in test_labels_set: if not test_labels or module_name in test_labels_set:
if verbosity >= 2: if verbosity >= 2:
print "Importing application %s" % module_name print("Importing application %s" % module_name)
mod = load_app(module_label) mod = load_app(module_label)
if mod: if mod:
if module_label not in settings.INSTALLED_APPS: if module_label not in settings.INSTALLED_APPS:
@ -178,7 +178,7 @@ def bisect_tests(bisection_label, options, test_labels):
from django.db.models.loading import get_apps from django.db.models.loading import get_apps
test_labels = [app.__name__.split('.')[-2] for app in get_apps()] test_labels = [app.__name__.split('.')[-2] for app in get_apps()]
print '***** Bisecting test suite:',' '.join(test_labels) print('***** Bisecting test suite: %s' % ' '.join(test_labels))
# Make sure the bisection point isn't in the test list # Make sure the bisection point isn't in the test list
# Also remove tests that need to be run in specific combinations # Also remove tests that need to be run in specific combinations
@ -202,44 +202,44 @@ def bisect_tests(bisection_label, options, test_labels):
midpoint = len(test_labels)/2 midpoint = len(test_labels)/2
test_labels_a = test_labels[:midpoint] + [bisection_label] test_labels_a = test_labels[:midpoint] + [bisection_label]
test_labels_b = test_labels[midpoint:] + [bisection_label] test_labels_b = test_labels[midpoint:] + [bisection_label]
print '***** Pass %da: Running the first half of the test suite' % iteration print('***** Pass %da: Running the first half of the test suite' % iteration)
print '***** Test labels:',' '.join(test_labels_a) print('***** Test labels: %s' % ' '.join(test_labels_a))
failures_a = subprocess.call(subprocess_args + test_labels_a) failures_a = subprocess.call(subprocess_args + test_labels_a)
print '***** Pass %db: Running the second half of the test suite' % iteration print('***** Pass %db: Running the second half of the test suite' % iteration)
print '***** Test labels:',' '.join(test_labels_b) print('***** Test labels: %s' % ' '.join(test_labels_b))
print print('')
failures_b = subprocess.call(subprocess_args + test_labels_b) failures_b = subprocess.call(subprocess_args + test_labels_b)
if failures_a and not failures_b: if failures_a and not failures_b:
print "***** Problem found in first half. Bisecting again..." print("***** Problem found in first half. Bisecting again...")
iteration = iteration + 1 iteration = iteration + 1
test_labels = test_labels_a[:-1] test_labels = test_labels_a[:-1]
elif failures_b and not failures_a: elif failures_b and not failures_a:
print "***** Problem found in second half. Bisecting again..." print("***** Problem found in second half. Bisecting again...")
iteration = iteration + 1 iteration = iteration + 1
test_labels = test_labels_b[:-1] test_labels = test_labels_b[:-1]
elif failures_a and failures_b: elif failures_a and failures_b:
print "***** Multiple sources of failure found" print("***** Multiple sources of failure found")
break break
else: else:
print "***** No source of failure found... try pair execution (--pair)" print("***** No source of failure found... try pair execution (--pair)")
break break
if len(test_labels) == 1: if len(test_labels) == 1:
print "***** Source of error:",test_labels[0] print("***** Source of error: %s" % test_labels[0])
teardown(state) teardown(state)
def paired_tests(paired_test, options, test_labels): def paired_tests(paired_test, options, test_labels):
state = setup(int(options.verbosity), test_labels) state = setup(int(options.verbosity), test_labels)
if not test_labels: if not test_labels:
print "" print("")
# Get the full list of test labels to use for bisection # Get the full list of test labels to use for bisection
from django.db.models.loading import get_apps from django.db.models.loading import get_apps
test_labels = [app.__name__.split('.')[-2] for app in get_apps()] test_labels = [app.__name__.split('.')[-2] for app in get_apps()]
print '***** Trying paired execution' print('***** Trying paired execution')
# Make sure the constant member of the pair isn't in the test list # Make sure the constant member of the pair isn't in the test list
# Also remove tests that need to be run in specific combinations # Also remove tests that need to be run in specific combinations
@ -259,14 +259,14 @@ def paired_tests(paired_test, options, test_labels):
subprocess_args.append('--noinput') subprocess_args.append('--noinput')
for i, label in enumerate(test_labels): for i, label in enumerate(test_labels):
print '***** %d of %d: Check test pairing with %s' % ( print('***** %d of %d: Check test pairing with %s' % (
i+1, len(test_labels), label) i + 1, len(test_labels), label))
failures = subprocess.call(subprocess_args + [label, paired_test]) failures = subprocess.call(subprocess_args + [label, paired_test])
if failures: if failures:
print '***** Found problem pair with',label print('***** Found problem pair with %s' % label)
return return
print '***** No problem pair found' print('***** No problem pair found')
teardown(state) teardown(state)
if __name__ == "__main__": if __name__ == "__main__":