Changed a whole bunch of places to raise exception instances instead of old-style raising exception classes plus a comma. Good for the future Python 3 conversion

git-svn-id: http://code.djangoproject.com/svn/django/trunk@12180 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Adrian Holovaty 2010-01-10 18:36:20 +00:00
parent bef891399e
commit 5ceed0a053
46 changed files with 120 additions and 124 deletions

View File

@ -46,7 +46,7 @@ class LazySettings(LazyObject):
argument must support attribute access (__getattr__)).
"""
if self._wrapped != None:
raise RuntimeError, 'Settings already configured.'
raise RuntimeError('Settings already configured.')
holder = UserSettingsHolder(default_settings)
for name, value in options.items():
setattr(holder, name, value)
@ -72,7 +72,7 @@ class Settings(object):
try:
mod = importlib.import_module(self.SETTINGS_MODULE)
except ImportError, e:
raise ImportError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e)
raise ImportError("Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e))
# Settings that should be converted into tuples if they're mistakenly entered
# as strings.

View File

@ -44,14 +44,14 @@ class DoGetAdminLog:
def __call__(self, parser, token):
tokens = token.contents.split()
if len(tokens) < 4:
raise template.TemplateSyntaxError, "'%s' statements require two arguments" % self.tag_name
raise template.TemplateSyntaxError("'%s' statements require two arguments" % self.tag_name)
if not tokens[1].isdigit():
raise template.TemplateSyntaxError, "First argument in '%s' must be an integer" % self.tag_name
raise template.TemplateSyntaxError("First argument in '%s' must be an integer" % self.tag_name)
if tokens[2] != 'as':
raise template.TemplateSyntaxError, "Second argument in '%s' must be 'as'" % self.tag_name
raise template.TemplateSyntaxError("Second argument in '%s' must be 'as'" % self.tag_name)
if len(tokens) > 4:
if tokens[4] != 'for_user':
raise template.TemplateSyntaxError, "Fourth argument in '%s' must be 'for_user'" % self.tag_name
raise template.TemplateSyntaxError("Fourth argument in '%s' must be 'for_user'" % self.tag_name)
return AdminLogNode(limit=tokens[1], varname=tokens[3], user=(len(tokens) > 5 and tokens[5] or None))
register.tag('get_admin_log', DoGetAdminLog('get_admin_log'))

View File

@ -76,4 +76,4 @@ class TemplateValidatorForm(forms.Form):
error = e
template.builtins.remove(register)
if error:
raise forms.ValidationError, e.args
raise forms.ValidationError(e.args)

View File

@ -187,14 +187,14 @@ def model_detail(request, app_label, model_name):
try:
app_mod = models.get_app(app_label)
except ImproperlyConfigured:
raise Http404, _("App %r not found") % app_label
raise Http404(_("App %r not found") % app_label)
model = None
for m in models.get_models(app_mod):
if m._meta.object_name.lower() == model_name:
model = m
break
if model is None:
raise Http404, _("Model %(model_name)r not found in app %(app_label)r") % {'model_name': model_name, 'app_label': app_label}
raise Http404(_("Model %(model_name)r not found in app %(app_label)r") % {'model_name': model_name, 'app_label': app_label})
opts = model._meta
@ -353,7 +353,7 @@ def extract_views_from_urlpatterns(urlpatterns, base=''):
continue
views.extend(extract_views_from_urlpatterns(patterns, base + p.regex.pattern))
else:
raise TypeError, _("%s does not appear to be a urlpattern object") % p
raise TypeError(_("%s does not appear to be a urlpattern object") % p)
return views
named_group_matcher = re.compile(r'\(\?P(<\w+>).+?\)')

View File

@ -13,13 +13,13 @@ def load_backend(path):
try:
mod = import_module(module)
except ImportError, e:
raise ImproperlyConfigured, 'Error importing authentication backend %s: "%s"' % (module, e)
raise ImproperlyConfigured('Error importing authentication backend %s: "%s"' % (module, e))
except ValueError, e:
raise ImproperlyConfigured, 'Error importing authentication backends. Is AUTHENTICATION_BACKENDS a correctly defined list or tuple?'
raise ImproperlyConfigured('Error importing authentication backends. Is AUTHENTICATION_BACKENDS a correctly defined list or tuple?')
try:
cls = getattr(mod, attr)
except AttributeError:
raise ImproperlyConfigured, 'Module "%s" does not define a "%s" authentication backend' % (module, attr)
raise ImproperlyConfigured('Module "%s" does not define a "%s" authentication backend' % (module, attr))
try:
getattr(cls, 'supports_object_permissions')
except AttributeError:

View File

@ -83,7 +83,7 @@ class GenericForeignKey(object):
def __set__(self, instance, value):
if instance is None:
raise AttributeError, u"%s must be accessed via instance" % self.related.opts.object_name
raise AttributeError(u"%s must be accessed via instance" % self.related.opts.object_name)
ct = None
fk = None
@ -210,7 +210,7 @@ class ReverseGenericRelatedObjectsDescriptor(object):
def __set__(self, instance, value):
if instance is None:
raise AttributeError, "Manager must be accessed via instance"
raise AttributeError("Manager must be accessed via instance")
manager = self.__get__(instance)
manager.clear()
@ -252,7 +252,7 @@ def create_generic_related_manager(superclass):
def add(self, *objs):
for obj in objs:
if not isinstance(obj, self.model):
raise TypeError, "'%s' instance expected" % self.model._meta.object_name
raise TypeError("'%s' instance expected" % self.model._meta.object_name)
setattr(obj, self.content_type_field_name, self.content_type)
setattr(obj, self.object_id_field_name, self.pk_val)
obj.save(using=self.instance._state.db)

View File

@ -39,7 +39,7 @@ class DatabaseWrapper(SqliteDatabaseWrapper):
settings_dict = self.settings_dict
if not settings_dict['NAME']:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured, "Please fill out the database NAME in the settings module before using the database."
raise ImproperlyConfigured("Please fill out the database NAME in the settings module before using the database.")
kwargs = {
'database': settings_dict['NAME'],
'detect_types': Database.PARSE_DECLTYPES | Database.PARSE_COLNAMES,

View File

@ -19,7 +19,7 @@ class GeometryCollection(GEOSGeometry):
# Checking the arguments
if not args:
raise TypeError, 'Must provide at least one Geometry to initialize %s.' % self.__class__.__name__
raise TypeError('Must provide at least one Geometry to initialize %s.' % self.__class__.__name__)
if len(args) == 1:
# If only one geometry provided or a list of geometries is provided

View File

@ -12,7 +12,7 @@ class TestGeom:
if not self.bad:
m = wkt_regex.match(wkt)
if not m:
raise Exception, 'Improper WKT: "%s"' % wkt
raise Exception('Improper WKT: "%s"' % wkt)
self.geo_type = m.group('type')
for key, value in kwargs.items():

View File

@ -19,7 +19,7 @@ def ogrinfo(data_source, num_features=10):
elif isinstance(data_source, DataSource):
pass
else:
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):
print "data source : %s" % data_source.name

View File

@ -97,13 +97,13 @@ class ESIdentityCardNumberField(RegexField):
if letter2 == nif_get_checksum(number):
return value
else:
raise ValidationError, self.error_messages['invalid_nif']
raise ValidationError(self.error_messages['invalid_nif'])
elif letter1 in self.nie_types and letter2:
# NIE
if letter2 == nif_get_checksum(number):
return value
else:
raise ValidationError, self.error_messages['invalid_nie']
raise ValidationError(self.error_messages['invalid_nie'])
elif not self.only_nif and letter1 in self.cif_types and len(number) in [7, 8]:
# CIF
if not letter2:
@ -112,9 +112,9 @@ class ESIdentityCardNumberField(RegexField):
if letter2 in (checksum, self.cif_control[checksum]):
return value
else:
raise ValidationError, self.error_messages['invalid_cif']
raise ValidationError(self.error_messages['invalid_cif'])
else:
raise ValidationError, self.error_messages['invalid']
raise ValidationError(self.error_messages['invalid'])
class ESCCCField(RegexField):
"""
@ -159,7 +159,7 @@ class ESCCCField(RegexField):
if get_checksum('00' + entity + office) + get_checksum(account) == checksum:
return value
else:
raise ValidationError, self.error_messages['checksum']
raise ValidationError(self.error_messages['checksum'])
class ESRegionSelect(Select):
"""

View File

@ -26,7 +26,7 @@ def textile(value):
import textile
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError, "Error in {% textile %} filter: The Python textile library isn't installed."
raise template.TemplateSyntaxError("Error in {% textile %} filter: The Python textile library isn't installed.")
return force_unicode(value)
else:
return mark_safe(force_unicode(textile.textile(smart_str(value), encoding='utf-8', output='utf-8')))
@ -53,7 +53,7 @@ def markdown(value, arg=''):
import markdown
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError, "Error in {% markdown %} filter: The Python markdown library isn't installed."
raise template.TemplateSyntaxError("Error in {% markdown %} filter: The Python markdown library isn't installed.")
return force_unicode(value)
else:
# markdown.version was first added in 1.6b. The only version of markdown
@ -81,7 +81,7 @@ def restructuredtext(value):
from docutils.core import publish_parts
except ImportError:
if settings.DEBUG:
raise template.TemplateSyntaxError, "Error in {% restructuredtext %} filter: The Python docutils library isn't installed."
raise template.TemplateSyntaxError("Error in {% restructuredtext %} filter: The Python docutils library isn't installed.")
return force_unicode(value)
else:
docutils_settings = getattr(settings, "RESTRUCTUREDTEXT_FILTER_SETTINGS", {})

View File

@ -58,7 +58,7 @@ class Session(models.Model):
pickled, tamper_check = encoded_data[:-32], encoded_data[-32:]
if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:
from django.core.exceptions import SuspiciousOperation
raise SuspiciousOperation, "User tampered with session cookie."
raise SuspiciousOperation("User tampered with session cookie.")
try:
return pickle.loads(pickled)
# Unpickling can cause a variety of exceptions. If something happens,

View File

@ -14,7 +14,7 @@ class CurrentSiteManager(models.Manager):
try:
self.model._meta.get_field(self.__field_name)
except FieldDoesNotExist:
raise ValueError, "%s couldn't find a field named %s in %s." % \
(self.__class__.__name__, self.__field_name, self.model._meta.object_name)
raise ValueError("%s couldn't find a field named %s in %s." % \
(self.__class__.__name__, self.__field_name, self.model._meta.object_name))
self.__is_validated = True
return super(CurrentSiteManager, self).get_query_set().filter(**{self.__field_name + '__id__exact': settings.SITE_ID})

View File

@ -38,7 +38,7 @@ class Feed(object):
try:
return item.get_absolute_url()
except AttributeError:
raise ImproperlyConfigured, "Give your %s class a get_absolute_url() method, or define an item_link() method in your Feed class." % item.__class__.__name__
raise ImproperlyConfigured("Give your %s class a get_absolute_url() method, or define an item_link() method in your Feed class." % item.__class__.__name__)
def __get_dynamic_attr(self, attname, obj, default=None):
try:

View File

@ -3,7 +3,7 @@ from django.http import HttpResponse, Http404
def feed(request, url, feed_dict=None):
if not feed_dict:
raise Http404, "No feeds are registered."
raise Http404("No feeds are registered.")
try:
slug, param = url.split('/', 1)
@ -13,12 +13,12 @@ def feed(request, url, feed_dict=None):
try:
f = feed_dict[slug]
except KeyError:
raise Http404, "Slug %r isn't registered." % slug
raise Http404("Slug %r isn't registered." % slug)
try:
feedgen = f(slug, request).get_feed(param)
except feeds.FeedDoesNotExist:
raise Http404, "Invalid feed parameters. Slug %r is valid, but other parameters, or lack thereof, are not." % slug
raise Http404("Invalid feed parameters. Slug %r is valid, but other parameters, or lack thereof, are not." % slug)
response = HttpResponse(mimetype=feedgen.mime_type)
feedgen.write(response, 'utf-8')

View File

@ -39,10 +39,10 @@ def parse_backend_uri(backend_uri):
(scheme, host, params) tuple.
"""
if backend_uri.find(':') == -1:
raise InvalidCacheBackendError, "Backend URI must start with scheme://"
raise InvalidCacheBackendError("Backend URI must start with scheme://")
scheme, rest = backend_uri.split(':', 1)
if not rest.startswith('//'):
raise InvalidCacheBackendError, "Backend URI must start with scheme://"
raise InvalidCacheBackendError("Backend URI must start with scheme://")
host = rest[2:]
qpos = rest.find('?')

View File

@ -71,7 +71,7 @@ class BaseCache(object):
ValueError exception.
"""
if key not in self:
raise ValueError, "Key '%s' not found" % key
raise ValueError("Key '%s' not found" % key)
new_value = self.get(key) + delta
self.set(key, new_value)
return new_value

View File

@ -129,7 +129,7 @@ class CacheClass(BaseCache):
try:
os.makedirs(self._dir)
except OSError:
raise EnvironmentError, "Cache directory '%s' does not exist and could not be created'" % self._dir
raise EnvironmentError("Cache directory '%s' does not exist and could not be created'" % self._dir)
def _key_to_file(self, key):
"""

View File

@ -34,16 +34,16 @@ class BaseHandler(object):
try:
dot = middleware_path.rindex('.')
except ValueError:
raise exceptions.ImproperlyConfigured, '%s isn\'t a middleware module' % middleware_path
raise exceptions.ImproperlyConfigured('%s isn\'t a middleware module' % middleware_path)
mw_module, mw_classname = middleware_path[:dot], middleware_path[dot+1:]
try:
mod = import_module(mw_module)
except ImportError, e:
raise exceptions.ImproperlyConfigured, 'Error importing middleware %s: "%s"' % (mw_module, e)
raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e))
try:
mw_class = getattr(mod, mw_classname)
except AttributeError:
raise exceptions.ImproperlyConfigured, 'Middleware module "%s" does not define a "%s" class' % (mw_module, mw_classname)
raise exceptions.ImproperlyConfigured('Middleware module "%s" does not define a "%s" class' % (mw_module, mw_classname))
try:
mw_instance = mw_class()
@ -113,7 +113,7 @@ class BaseHandler(object):
view_name = callback.func_name # If it's a function
except AttributeError:
view_name = callback.__class__.__name__ + '.__call__' # If it's a class
raise ValueError, "The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name)
raise ValueError("The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name))
return response
except http.Http404, e:

View File

@ -152,7 +152,7 @@ def call_command(name, *args, **options):
else:
klass = load_command_class(app_name, name)
except KeyError:
raise CommandError, "Unknown command: %r" % name
raise CommandError("Unknown command: %r" % name)
# Grab out a list of defaults from the options. optparse does this for us
# when the script runs from the command line, but since call_command can

View File

@ -530,7 +530,7 @@ class WSGIServer(HTTPServer):
try:
HTTPServer.server_bind(self)
except Exception, e:
raise WSGIServerException, e
raise WSGIServerException(e)
self.setup_environ()
def setup_environ(self):

View File

@ -135,10 +135,10 @@ class RegexURLPattern(object):
self._callback = get_callable(self._callback_str)
except ImportError, e:
mod_name, _ = get_mod_func(self._callback_str)
raise ViewDoesNotExist, "Could not import %s. Error was: %s" % (mod_name, str(e))
raise ViewDoesNotExist("Could not import %s. Error was: %s" % (mod_name, str(e)))
except AttributeError, e:
mod_name, func_name = get_mod_func(self._callback_str)
raise ViewDoesNotExist, "Tried %s in module %s. Error was: %s" % (func_name, mod_name, str(e))
raise ViewDoesNotExist("Tried %s in module %s. Error was: %s" % (func_name, mod_name, str(e)))
return self._callback
callback = property(_get_callback)
@ -234,8 +234,8 @@ class RegexURLResolver(object):
sub_match_dict[smart_str(k)] = v
return sub_match[0], sub_match[1], sub_match_dict
tried.append(pattern.regex.pattern)
raise Resolver404, {'tried': tried, 'path': new_path}
raise Resolver404, {'path' : path}
raise Resolver404({'tried': tried, 'path': new_path})
raise Resolver404({'path' : path})
def _get_urlconf_module(self):
try:
@ -250,8 +250,7 @@ class RegexURLResolver(object):
try:
iter(patterns)
except TypeError:
raise ImproperlyConfigured("The included urlconf %s doesn't have any "
"patterns in it" % self.urlconf_name)
raise ImproperlyConfigured("The included urlconf %s doesn't have any patterns in it" % self.urlconf_name)
return patterns
url_patterns = property(_get_url_patterns)
@ -260,7 +259,7 @@ class RegexURLResolver(object):
try:
return get_callable(callback), {}
except (ImportError, AttributeError), e:
raise ViewDoesNotExist, "Tried %s. Error was: %s" % (callback, str(e))
raise ViewDoesNotExist("Tried %s. Error was: %s" % (callback, str(e)))
def resolve404(self):
return self._resolve_special('404')

View File

@ -12,7 +12,7 @@ from django.db.backends import *
from django.db.backends.creation import BaseDatabaseCreation
def complain(*args, **kwargs):
raise ImproperlyConfigured, "You haven't set the database ENGINE setting yet."
raise ImproperlyConfigured("You haven't set the database ENGINE setting yet.")
def ignore(*args, **kwargs):
pass

View File

@ -27,7 +27,7 @@ except ImportError, exc:
exc = e1
else:
module = 'either pysqlite2 or sqlite3 modules (tried in that order)'
raise ImproperlyConfigured, "Error loading %s: %s" % (module, exc)
raise ImproperlyConfigured("Error loading %s: %s" % (module, exc))
DatabaseError = Database.DatabaseError
@ -157,7 +157,7 @@ class DatabaseWrapper(BaseDatabaseWrapper):
settings_dict = self.settings_dict
if not settings_dict['NAME']:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured, "Please fill out the database NAME in the settings module before using the database."
raise ImproperlyConfigured("Please fill out the database NAME in the settings module before using the database.")
kwargs = {
'database': settings_dict['NAME'],
'detect_types': Database.PARSE_DECLTYPES | Database.PARSE_COLNAMES,

View File

@ -111,8 +111,7 @@ class ModelBase(type):
raise TypeError("Proxy model '%s' has no non-abstract model base class." % name)
if (new_class._meta.local_fields or
new_class._meta.local_many_to_many):
raise FieldError("Proxy model '%s' contains model fields."
% name)
raise FieldError("Proxy model '%s' contains model fields." % name)
while base._meta.proxy:
base = base._meta.proxy_for_model
new_class._meta.setup_proxy(base)
@ -333,7 +332,7 @@ class Model(object):
except AttributeError:
pass
if kwargs:
raise TypeError, "'%s' is an invalid keyword argument for this function" % kwargs.keys()[0]
raise TypeError("'%s' is an invalid keyword argument for this function" % kwargs.keys()[0])
signals.post_init.send(sender=self.__class__, instance=self)
def __repr__(self):
@ -427,8 +426,7 @@ class Model(object):
non-SQL backends), respectively. Normally, they should not be set.
"""
if force_insert and force_update:
raise ValueError("Cannot force both insert and updating in "
"model saving.")
raise ValueError("Cannot force both insert and updating in model saving.")
self.save_base(using=using, force_insert=force_insert, force_update=force_update)
save.alters_data = True
@ -621,7 +619,7 @@ class Model(object):
try:
return qs[0]
except IndexError:
raise self.DoesNotExist, "%s matching query does not exist." % self.__class__._meta.object_name
raise self.DoesNotExist("%s matching query does not exist." % self.__class__._meta.object_name)
def _get_next_or_previous_in_order(self, is_next):
cachename = "__%s_order_cache" % is_next

View File

@ -171,7 +171,7 @@ class RelatedField(object):
return [pk_trace(v) for v in value]
elif lookup_type == 'isnull':
return []
raise TypeError, "Related Field has invalid lookup: %s" % lookup_type
raise TypeError("Related Field has invalid lookup: %s" % lookup_type)
def _get_related_query_name(self, opts):
# This method defines the name that can be used to identify this
@ -203,7 +203,7 @@ class SingleRelatedObjectDescriptor(object):
def __set__(self, instance, value):
if instance is None:
raise AttributeError, "%s must be accessed via instance" % self.related.opts.object_name
raise AttributeError("%s must be accessed via instance" % self.related.opts.object_name)
# The similarity of the code below to the code in
# ReverseSingleRelatedObjectDescriptor is annoying, but there's a bunch
@ -270,7 +270,7 @@ class ReverseSingleRelatedObjectDescriptor(object):
def __set__(self, instance, value):
if instance is None:
raise AttributeError, "%s must be accessed via instance" % self._field.name
raise AttributeError("%s must be accessed via instance" % self._field.name)
# If null=True, we can assign null here, but otherwise the value needs
# to be an instance of the related class.
@ -343,7 +343,7 @@ class ForeignRelatedObjectsDescriptor(object):
def __set__(self, instance, value):
if instance is None:
raise AttributeError, "Manager must be accessed via instance"
raise AttributeError("Manager must be accessed via instance")
manager = self.__get__(instance)
# If the foreign key can support nulls, then completely clear the related set.
@ -376,7 +376,7 @@ class ForeignRelatedObjectsDescriptor(object):
def add(self, *objs):
for obj in objs:
if not isinstance(obj, self.model):
raise TypeError, "'%s' instance expected" % self.model._meta.object_name
raise TypeError("'%s' instance expected" % self.model._meta.object_name)
setattr(obj, rel_field.name, instance)
obj.save(using=instance._state.db)
add.alters_data = True
@ -404,7 +404,7 @@ class ForeignRelatedObjectsDescriptor(object):
setattr(obj, rel_field.name, None)
obj.save(using=instance._state.db)
else:
raise rel_field.rel.to.DoesNotExist, "%r is not related to %r." % (obj, instance)
raise rel_field.rel.to.DoesNotExist("%r is not related to %r." % (obj, instance))
remove.alters_data = True
def clear(self):
@ -475,7 +475,7 @@ def create_many_related_manager(superclass, rel=False):
# from the method lookup table, as we do with add and remove.
if not rel.through._meta.auto_created:
opts = through._meta
raise AttributeError, "Cannot use create() on a ManyToManyField which specifies an intermediary model. Use %s.%s's Manager instead." % (opts.app_label, opts.object_name)
raise AttributeError("Cannot use create() on a ManyToManyField which specifies an intermediary model. Use %s.%s's Manager instead." % (opts.app_label, opts.object_name))
new_obj = super(ManyRelatedManager, self).using(self.instance._state.db).create(**kwargs)
self.add(new_obj)
return new_obj
@ -508,7 +508,7 @@ def create_many_related_manager(superclass, rel=False):
# (obj, self.instance._state.db, obj._state.db))
new_ids.add(obj.pk)
elif isinstance(obj, Model):
raise TypeError, "'%s' instance expected" % self.model._meta.object_name
raise TypeError("'%s' instance expected" % self.model._meta.object_name)
else:
new_ids.add(obj)
vals = self.through._default_manager.using(self.instance._state.db).values_list(target_field_name, flat=True)
@ -586,11 +586,11 @@ class ManyRelatedObjectsDescriptor(object):
def __set__(self, instance, value):
if instance is None:
raise AttributeError, "Manager must be accessed via instance"
raise AttributeError("Manager must be accessed via instance")
if not self.related.field.rel.through._meta.auto_created:
opts = self.related.field.rel.through._meta
raise AttributeError, "Cannot set values on a ManyToManyField which specifies an intermediary model. Use %s.%s's Manager instead." % (opts.app_label, opts.object_name)
raise AttributeError("Cannot set values on a ManyToManyField which specifies an intermediary model. Use %s.%s's Manager instead." % (opts.app_label, opts.object_name))
manager = self.__get__(instance)
manager.clear()
@ -636,11 +636,11 @@ class ReverseManyRelatedObjectsDescriptor(object):
def __set__(self, instance, value):
if instance is None:
raise AttributeError, "Manager must be accessed via instance"
raise AttributeError("Manager must be accessed via instance")
if not self.field.rel.through._meta.auto_created:
opts = self.field.rel.through._meta
raise AttributeError, "Cannot set values on a ManyToManyField which specifies an intermediary model. Use %s.%s's Manager instead." % (opts.app_label, opts.object_name)
raise AttributeError("Cannot set values on a ManyToManyField which specifies an intermediary model. Use %s.%s's Manager instead." % (opts.app_label, opts.object_name))
manager = self.__get__(instance)
manager.clear()

View File

@ -123,7 +123,7 @@ class AppCache(object):
return None
else:
return mod
raise ImproperlyConfigured, "App with label %s could not be found" % app_label
raise ImproperlyConfigured("App with label %s could not be found" % app_label)
finally:
self.write_lock.release()

View File

@ -19,7 +19,7 @@ def ensure_default_manager(sender, **kwargs):
# Create the default manager, if needed.
try:
cls._meta.get_field('objects')
raise ValueError, "Model %s must specify a custom Manager, because it has a field named 'objects'" % cls.__name__
raise ValueError("Model %s must specify a custom Manager, because it has a field named 'objects'" % cls.__name__)
except FieldDoesNotExist:
pass
cls.add_to_class('objects', Manager())
@ -210,7 +210,7 @@ class ManagerDescriptor(object):
def __get__(self, instance, type=None):
if instance != None:
raise AttributeError, "Manager isn't accessible via %s instances" % type.__name__
raise AttributeError("Manager isn't accessible via %s instances" % type.__name__)
return self.manager
class EmptyManager(Manager):

View File

@ -94,7 +94,7 @@ class Options(object):
# Any leftover attributes must be invalid.
if meta_attrs != {}:
raise TypeError, "'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys())
raise TypeError("'class Meta' got invalid attribute(s): %s" % ','.join(meta_attrs.keys()))
else:
self.verbose_name_plural = string_concat(self.verbose_name, 's')
del self.meta
@ -274,7 +274,7 @@ class Options(object):
for f in to_search:
if f.name == name:
return f
raise FieldDoesNotExist, '%s has no field named %r' % (self.object_name, name)
raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, name))
def get_field_by_name(self, name):
"""

View File

@ -185,7 +185,7 @@ class QuerySet(object):
qs.query.set_limits(k, k + 1)
return list(qs)[0]
except self.model.DoesNotExist, e:
raise IndexError, e.args
raise IndexError(e.args)
def __and__(self, other):
self._merge_sanity_check(other)

View File

@ -41,7 +41,7 @@ class Media(StrAndUnicode):
# Any leftover attributes must be invalid.
# if media_attrs != {}:
# raise TypeError, "'class Media' has invalid attribute(s): %s" % ','.join(media_attrs.keys())
# raise TypeError("'class Media' has invalid attribute(s): %s" % ','.join(media_attrs.keys()))
def __unicode__(self):
return self.render()

View File

@ -439,10 +439,10 @@ def autoescape(parser, token):
"""
args = token.contents.split()
if len(args) != 2:
raise TemplateSyntaxError("'Autoescape' tag requires exactly one argument.")
raise TemplateSyntaxError("'autoescape' tag requires exactly one argument.")
arg = args[1]
if arg not in (u'on', u'off'):
raise TemplateSyntaxError("'Autoescape' argument should be 'on' or 'off'")
raise TemplateSyntaxError("'autoescape' argument should be 'on' or 'off'")
nodelist = parser.parse(('endautoescape',))
parser.delete_first_token()
return AutoEscapeControlNode((arg == 'on'), nodelist)
@ -604,8 +604,7 @@ def firstof(parser, token):
"""
bits = token.split_contents()[1:]
if len(bits) < 1:
raise TemplateSyntaxError("'firstof' statement requires at least one"
" argument")
raise TemplateSyntaxError("'firstof' statement requires at least one argument")
return FirstOfNode([parser.compile_filter(bit) for bit in bits])
firstof = register.tag(firstof)
@ -704,7 +703,7 @@ do_for = register.tag("for", do_for)
def do_ifequal(parser, token, negate):
bits = list(token.split_contents())
if len(bits) != 3:
raise TemplateSyntaxError, "%r takes two arguments" % bits[0]
raise TemplateSyntaxError("%r takes two arguments" % bits[0])
end_tag = 'end' + bits[0]
nodelist_true = parser.parse(('else', end_tag))
token = parser.next_token()
@ -943,7 +942,7 @@ def now(parser, token):
"""
bits = token.contents.split('"')
if len(bits) != 3:
raise TemplateSyntaxError, "'now' statement takes one argument"
raise TemplateSyntaxError("'now' statement takes one argument")
format_string = bits[1]
return NowNode(format_string)
now = register.tag(now)
@ -997,7 +996,7 @@ def regroup(parser, token):
"""
firstbits = token.contents.split(None, 3)
if len(firstbits) != 4:
raise TemplateSyntaxError, "'regroup' tag takes five arguments"
raise TemplateSyntaxError("'regroup' tag takes five arguments")
target = parser.compile_filter(firstbits[1])
if firstbits[2] != 'by':
raise TemplateSyntaxError("second argument to 'regroup' tag must be 'by'")
@ -1067,7 +1066,7 @@ def templatetag(parser, token):
"""
bits = token.contents.split()
if len(bits) != 2:
raise TemplateSyntaxError, "'templatetag' statement takes one argument"
raise TemplateSyntaxError("'templatetag' statement takes one argument")
tag = bits[1]
if tag not in TemplateTagNode.mapping:
raise TemplateSyntaxError("Invalid templatetag argument: '%s'."

View File

@ -122,7 +122,7 @@ def find_template(name, dirs=None):
return (source, make_origin(display_name, loader, name, dirs))
except TemplateDoesNotExist:
pass
raise TemplateDoesNotExist, name
raise TemplateDoesNotExist(name)
def find_template_source(name, dirs=None):
# For backward compatibility
@ -180,6 +180,6 @@ def select_template(template_name_list):
except TemplateDoesNotExist:
continue
# If we get here, none of the templates could be loaded
raise TemplateDoesNotExist, ', '.join(template_name_list)
raise TemplateDoesNotExist(', '.join(template_name_list))
add_to_builtins('django.template.loader_tags')

View File

@ -94,13 +94,13 @@ class ExtendsNode(Node):
error_msg = "Invalid template name in 'extends' tag: %r." % parent
if self.parent_name_expr:
error_msg += " Got this from the '%s' variable." % self.parent_name_expr.token
raise TemplateSyntaxError, error_msg
raise TemplateSyntaxError(error_msg)
if hasattr(parent, 'render'):
return parent # parent is a Template object
try:
return get_template(parent)
except TemplateDoesNotExist:
raise TemplateSyntaxError, "Template %r cannot be extended, because it doesn't exist" % parent
raise TemplateSyntaxError("Template %r cannot be extended, because it doesn't exist" % parent)
def render(self, context):
compiled_parent = self.get_parent(context)
@ -165,13 +165,13 @@ def do_block(parser, token):
"""
bits = token.contents.split()
if len(bits) != 2:
raise TemplateSyntaxError, "'%s' tag takes only one argument" % bits[0]
raise TemplateSyntaxError("'%s' tag takes only one argument" % bits[0])
block_name = bits[1]
# Keep track of the names of BlockNodes found in this template, so we can
# check for duplication.
try:
if block_name in parser.__loaded_blocks:
raise TemplateSyntaxError, "'%s' tag with name '%s' appears more than once" % (bits[0], block_name)
raise TemplateSyntaxError("'%s' tag with name '%s' appears more than once" % (bits[0], block_name))
parser.__loaded_blocks.append(block_name)
except AttributeError: # parser.__loaded_blocks isn't a list yet
parser.__loaded_blocks = [block_name]
@ -191,7 +191,7 @@ def do_extends(parser, token):
"""
bits = token.split_contents()
if len(bits) != 2:
raise TemplateSyntaxError, "'%s' takes one argument" % bits[0]
raise TemplateSyntaxError("'%s' takes one argument" % bits[0])
parent_name, parent_name_expr = None, None
if bits[1][0] in ('"', "'") and bits[1][-1] == bits[1][0]:
parent_name = bits[1][1:-1]
@ -199,7 +199,7 @@ def do_extends(parser, token):
parent_name_expr = parser.compile_filter(bits[1])
nodelist = parser.parse()
if nodelist.get_nodes_by_type(ExtendsNode):
raise TemplateSyntaxError, "'%s' cannot appear more than once in the same template" % bits[0]
raise TemplateSyntaxError("'%s' cannot appear more than once in the same template" % bits[0])
return ExtendsNode(nodelist, parent_name, parent_name_expr)
def do_include(parser, token):
@ -212,7 +212,7 @@ def do_include(parser, token):
"""
bits = token.split_contents()
if len(bits) != 2:
raise TemplateSyntaxError, "%r tag takes one argument: the name of the template to be included" % bits[0]
raise TemplateSyntaxError("%r tag takes one argument: the name of the template to be included" % bits[0])
path = bits[1]
if path[0] in ('"', "'") and path[-1] == path[0]:
return ConstantIncludeNode(path[1:-1])

View File

@ -20,7 +20,7 @@ for app in settings.INSTALLED_APPS:
try:
mod = import_module(app)
except ImportError, e:
raise ImproperlyConfigured, 'ImportError %s: %s' % (app, e.args[0])
raise ImproperlyConfigured('ImportError %s: %s' % (app, e.args[0]))
template_dir = os.path.join(os.path.dirname(mod.__file__), 'templates')
if os.path.isdir(template_dir):
app_template_dirs.append(template_dir.decode(fs_encoding))
@ -59,7 +59,7 @@ class Loader(BaseLoader):
file.close()
except IOError:
pass
raise TemplateDoesNotExist, template_name
raise TemplateDoesNotExist(template_name)
_loader = Loader()

View File

@ -31,7 +31,7 @@ class Loader(BaseLoader):
return (template, make_origin(display_name, loader, name, dirs))
except TemplateDoesNotExist:
pass
raise TemplateDoesNotExist, name
raise TemplateDoesNotExist(name)
def load_template(self, template_name, template_dirs=None):
if template_name not in self.template_cache:

View File

@ -25,7 +25,7 @@ class Loader(BaseLoader):
return (resource_string(app, pkg_name).decode(settings.FILE_CHARSET), 'egg:%s:%s' % (app, pkg_name))
except:
pass
raise TemplateDoesNotExist, template_name
raise TemplateDoesNotExist(template_name)
_loader = Loader()

View File

@ -45,7 +45,7 @@ class Loader(BaseLoader):
error_msg = "Tried %s" % tried
else:
error_msg = "Your TEMPLATE_DIRS setting is empty. Change it to point to at least one template directory."
raise TemplateDoesNotExist, error_msg
raise TemplateDoesNotExist(error_msg)
load_template_source.is_usable = True
_loader = Loader()

View File

@ -104,7 +104,7 @@ def do_get_available_languages(parser, token):
"""
args = token.contents.split()
if len(args) != 3 or args[1] != 'as':
raise TemplateSyntaxError, "'get_available_languages' requires 'as variable' (got %r)" % args
raise TemplateSyntaxError("'get_available_languages' requires 'as variable' (got %r)" % args)
return GetAvailableLanguagesNode(args[2])
def do_get_current_language(parser, token):
@ -121,7 +121,7 @@ def do_get_current_language(parser, token):
"""
args = token.contents.split()
if len(args) != 3 or args[1] != 'as':
raise TemplateSyntaxError, "'get_current_language' requires 'as variable' (got %r)" % args
raise TemplateSyntaxError("'get_current_language' requires 'as variable' (got %r)" % args)
return GetCurrentLanguageNode(args[2])
def do_get_current_language_bidi(parser, token):
@ -138,7 +138,7 @@ def do_get_current_language_bidi(parser, token):
"""
args = token.contents.split()
if len(args) != 3 or args[1] != 'as':
raise TemplateSyntaxError, "'get_current_language_bidi' requires 'as variable' (got %r)" % args
raise TemplateSyntaxError("'get_current_language_bidi' requires 'as variable' (got %r)" % args)
return GetCurrentLanguageBidiNode(args[2])
def do_translate(parser, token):
@ -178,7 +178,7 @@ def do_translate(parser, token):
if self.tag() == 'noop':
noop = True
else:
raise TemplateSyntaxError, "only option for 'trans' is 'noop'"
raise TemplateSyntaxError("only option for 'trans' is 'noop'")
else:
noop = False
return (value, noop)
@ -215,16 +215,16 @@ def do_block_translate(parser, token):
if tag == 'with' or tag == 'and':
value = self.value()
if self.tag() != 'as':
raise TemplateSyntaxError, "variable bindings in 'blocktrans' must be 'with value as variable'"
raise TemplateSyntaxError("variable bindings in 'blocktrans' must be 'with value as variable'")
extra_context[self.tag()] = VariableNode(
parser.compile_filter(value))
elif tag == 'count':
counter = parser.compile_filter(self.value())
if self.tag() != 'as':
raise TemplateSyntaxError, "counter specification in 'blocktrans' must be 'count value as variable'"
raise TemplateSyntaxError("counter specification in 'blocktrans' must be 'count value as variable'")
countervar = self.tag()
else:
raise TemplateSyntaxError, "unknown subtag %s for 'blocktrans' found" % tag
raise TemplateSyntaxError("unknown subtag %s for 'blocktrans' found" % tag)
return (countervar, counter, extra_context)
countervar, counter, extra_context = BlockTranslateParser(token.contents).top()
@ -239,7 +239,7 @@ def do_block_translate(parser, token):
break
if countervar and counter:
if token.contents.strip() != 'plural':
raise TemplateSyntaxError, "'blocktrans' doesn't allow other block tags inside it"
raise TemplateSyntaxError("'blocktrans' doesn't allow other block tags inside it")
while parser.tokens:
token = parser.next_token()
if token.token_type in (TOKEN_VAR, TOKEN_TEXT):
@ -247,7 +247,7 @@ def do_block_translate(parser, token):
else:
break
if token.contents.strip() != 'endblocktrans':
raise TemplateSyntaxError, "'blocktrans' doesn't allow other block tags (seen %r) inside it" % token.contents
raise TemplateSyntaxError("'blocktrans' doesn't allow other block tags (seen %r) inside it" % token.contents)
return BlockTranslateNode(extra_context, singular, plural, countervar,
counter)

View File

@ -208,7 +208,7 @@ class MultiValueDict(dict):
try:
list_ = super(MultiValueDict, self).__getitem__(key)
except KeyError:
raise MultiValueDictKeyError, "Key %r not found in %r" % (key, self)
raise MultiValueDictKeyError("Key %r not found in %r" % (key, self))
try:
return list_[-1]
except IndexError:
@ -325,7 +325,7 @@ class MultiValueDict(dict):
Also accepts keyword args.
"""
if len(args) > 1:
raise TypeError, "update expected at most 1 arguments, got %d" % len(args)
raise TypeError("update expected at most 1 arguments, got %d" % len(args))
if args:
other_dict = args[0]
if isinstance(other_dict, MultiValueDict):
@ -336,7 +336,7 @@ class MultiValueDict(dict):
for key, value in other_dict.items():
self.setlistdefault(key, []).append(value)
except TypeError:
raise ValueError, "MultiValueDict.update() takes either a MultiValueDict or dictionary"
raise ValueError("MultiValueDict.update() takes either a MultiValueDict or dictionary")
for key, value in kwargs.iteritems():
self.setlistdefault(key, []).append(value)
@ -400,7 +400,7 @@ class ImmutableList(tuple):
if isinstance(self.warning, Exception):
raise self.warning
else:
raise AttributeError, self.warning
raise AttributeError(self.warning)
# All list mutation functions complain.
__delitem__ = complain

View File

@ -186,7 +186,7 @@ def javascript_quote(s, quote_double_quotes=False):
if type(s) == str:
s = s.decode('utf-8')
elif type(s) != unicode:
raise TypeError, s
raise TypeError(s)
s = s.replace('\\', '\\\\')
s = s.replace('\r', '\\r')
s = s.replace('\n', '\\n')

View File

@ -27,7 +27,7 @@ def archive_index(request, queryset, date_field, num_latest=15,
queryset = queryset.filter(**{'%s__lte' % date_field: datetime.datetime.now()})
date_list = queryset.dates(date_field, 'year')[::-1]
if not date_list and not allow_empty:
raise Http404, "No %s available" % model._meta.verbose_name
raise Http404("No %s available" % model._meta.verbose_name)
if date_list and num_latest:
latest = queryset.order_by('-'+date_field)[:num_latest]
@ -339,11 +339,11 @@ def object_detail(request, year, month, day, queryset, date_field,
elif slug and slug_field:
lookup_kwargs['%s__exact' % slug_field] = slug
else:
raise AttributeError, "Generic detail view must be called with either an object_id or a slug/slugfield"
raise AttributeError("Generic detail view must be called with either an object_id or a slug/slugfield")
try:
obj = queryset.get(**lookup_kwargs)
except ObjectDoesNotExist:
raise Http404, "No %s found for" % model._meta.verbose_name
raise Http404("No %s found for" % model._meta.verbose_name)
if not template_name:
template_name = "%s/%s_detail.html" % (model._meta.app_label, model._meta.object_name.lower())
if template_name_field:

View File

@ -120,11 +120,11 @@ def object_detail(request, queryset, object_id=None, slug=None,
elif slug and slug_field:
queryset = queryset.filter(**{slug_field: slug})
else:
raise AttributeError, "Generic detail view must be called with either an object_id or a slug/slug_field."
raise AttributeError("Generic detail view must be called with either an object_id or a slug/slug_field.")
try:
obj = queryset.get()
except ObjectDoesNotExist:
raise Http404, "No %s found matching the query" % (model._meta.verbose_name)
raise Http404("No %s found matching the query" % (model._meta.verbose_name))
if not template_name:
template_name = "%s/%s_detail.html" % (model._meta.app_label, model._meta.object_name.lower())
if template_name_field:

View File

@ -233,7 +233,7 @@ def javascript_catalog(request, domain='djangojs', packages=None):
pdict[k[0]] = max(k[1], pdict[k[0]])
csrc.append("catalog['%s'][%d] = '%s';\n" % (javascript_quote(k[0]), k[1], javascript_quote(v)))
else:
raise TypeError, k
raise TypeError(k)
csrc.sort()
for k, v in pdict.items():
src.append("catalog['%s'] = [%s];\n" % (javascript_quote(k), ','.join(["''"]*(v+1))))

View File

@ -51,9 +51,9 @@ def serve(request, path, document_root=None, show_indexes=False):
if os.path.isdir(fullpath):
if show_indexes:
return directory_index(newpath, fullpath)
raise Http404, "Directory indexes are not allowed here."
raise Http404("Directory indexes are not allowed here.")
if not os.path.exists(fullpath):
raise Http404, '"%s" does not exist' % fullpath
raise Http404('"%s" does not exist' % fullpath)
# Respect the If-Modified-Since header.
statobj = os.stat(fullpath)
mimetype = mimetypes.guess_type(fullpath)[0] or 'application/octet-stream'