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__)). argument must support attribute access (__getattr__)).
""" """
if self._wrapped != None: if self._wrapped != None:
raise RuntimeError, 'Settings already configured.' raise RuntimeError('Settings already configured.')
holder = UserSettingsHolder(default_settings) holder = UserSettingsHolder(default_settings)
for name, value in options.items(): for name, value in options.items():
setattr(holder, name, value) setattr(holder, name, value)
@ -72,7 +72,7 @@ class Settings(object):
try: try:
mod = importlib.import_module(self.SETTINGS_MODULE) mod = importlib.import_module(self.SETTINGS_MODULE)
except ImportError, e: 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 # Settings that should be converted into tuples if they're mistakenly entered
# as strings. # as strings.

View File

@ -44,14 +44,14 @@ class DoGetAdminLog:
def __call__(self, parser, token): def __call__(self, parser, token):
tokens = token.contents.split() tokens = token.contents.split()
if len(tokens) < 4: 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(): 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': 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 len(tokens) > 4:
if tokens[4] != 'for_user': 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)) 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')) register.tag('get_admin_log', DoGetAdminLog('get_admin_log'))

View File

@ -76,4 +76,4 @@ class TemplateValidatorForm(forms.Form):
error = e error = e
template.builtins.remove(register) template.builtins.remove(register)
if error: 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: try:
app_mod = models.get_app(app_label) app_mod = models.get_app(app_label)
except ImproperlyConfigured: except ImproperlyConfigured:
raise Http404, _("App %r not found") % app_label raise Http404(_("App %r not found") % app_label)
model = None model = None
for m in models.get_models(app_mod): for m in models.get_models(app_mod):
if m._meta.object_name.lower() == model_name: if m._meta.object_name.lower() == model_name:
model = m model = m
break break
if model is None: 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 opts = model._meta
@ -353,7 +353,7 @@ def extract_views_from_urlpatterns(urlpatterns, base=''):
continue continue
views.extend(extract_views_from_urlpatterns(patterns, base + p.regex.pattern)) views.extend(extract_views_from_urlpatterns(patterns, base + p.regex.pattern))
else: 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 return views
named_group_matcher = re.compile(r'\(\?P(<\w+>).+?\)') named_group_matcher = re.compile(r'\(\?P(<\w+>).+?\)')

View File

@ -13,13 +13,13 @@ def load_backend(path):
try: try:
mod = import_module(module) mod = import_module(module)
except ImportError, e: 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: 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: try:
cls = getattr(mod, attr) cls = getattr(mod, attr)
except AttributeError: 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: try:
getattr(cls, 'supports_object_permissions') getattr(cls, 'supports_object_permissions')
except AttributeError: except AttributeError:

View File

@ -83,7 +83,7 @@ class GenericForeignKey(object):
def __set__(self, instance, value): def __set__(self, instance, value):
if instance is None: 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 ct = None
fk = None fk = None
@ -210,7 +210,7 @@ class ReverseGenericRelatedObjectsDescriptor(object):
def __set__(self, instance, value): def __set__(self, instance, value):
if instance is None: 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 = self.__get__(instance)
manager.clear() manager.clear()
@ -252,7 +252,7 @@ def create_generic_related_manager(superclass):
def add(self, *objs): def add(self, *objs):
for obj in objs: for obj in objs:
if not isinstance(obj, self.model): 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.content_type_field_name, self.content_type)
setattr(obj, self.object_id_field_name, self.pk_val) setattr(obj, self.object_id_field_name, self.pk_val)
obj.save(using=self.instance._state.db) obj.save(using=self.instance._state.db)

View File

@ -39,7 +39,7 @@ class DatabaseWrapper(SqliteDatabaseWrapper):
settings_dict = self.settings_dict settings_dict = self.settings_dict
if not settings_dict['NAME']: if not settings_dict['NAME']:
from django.core.exceptions import ImproperlyConfigured 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 = { kwargs = {
'database': settings_dict['NAME'], 'database': settings_dict['NAME'],
'detect_types': Database.PARSE_DECLTYPES | Database.PARSE_COLNAMES, 'detect_types': Database.PARSE_DECLTYPES | Database.PARSE_COLNAMES,

View File

@ -19,7 +19,7 @@ class GeometryCollection(GEOSGeometry):
# Checking the arguments # Checking the arguments
if not args: 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 len(args) == 1:
# If only one geometry provided or a list of geometries is provided # If only one geometry provided or a list of geometries is provided

View File

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

View File

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

View File

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

View File

@ -26,7 +26,7 @@ def textile(value):
import textile import textile
except ImportError: except ImportError:
if settings.DEBUG: 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) return force_unicode(value)
else: else:
return mark_safe(force_unicode(textile.textile(smart_str(value), encoding='utf-8', output='utf-8'))) 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 import markdown
except ImportError: except ImportError:
if settings.DEBUG: 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) return force_unicode(value)
else: else:
# markdown.version was first added in 1.6b. The only version of markdown # 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 from docutils.core import publish_parts
except ImportError: except ImportError:
if settings.DEBUG: 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) return force_unicode(value)
else: else:
docutils_settings = getattr(settings, "RESTRUCTUREDTEXT_FILTER_SETTINGS", {}) 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:] pickled, tamper_check = encoded_data[:-32], encoded_data[-32:]
if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper_check: if md5_constructor(pickled + settings.SECRET_KEY).hexdigest() != tamper_check:
from django.core.exceptions import SuspiciousOperation from django.core.exceptions import SuspiciousOperation
raise SuspiciousOperation, "User tampered with session cookie." raise SuspiciousOperation("User tampered with session cookie.")
try: try:
return pickle.loads(pickled) return pickle.loads(pickled)
# Unpickling can cause a variety of exceptions. If something happens, # Unpickling can cause a variety of exceptions. If something happens,

View File

@ -14,7 +14,7 @@ class CurrentSiteManager(models.Manager):
try: try:
self.model._meta.get_field(self.__field_name) self.model._meta.get_field(self.__field_name)
except FieldDoesNotExist: except FieldDoesNotExist:
raise ValueError, "%s couldn't find a field named %s in %s." % \ raise ValueError("%s couldn't find a field named %s in %s." % \
(self.__class__.__name__, self.__field_name, self.model._meta.object_name) (self.__class__.__name__, self.__field_name, self.model._meta.object_name))
self.__is_validated = True self.__is_validated = True
return super(CurrentSiteManager, self).get_query_set().filter(**{self.__field_name + '__id__exact': settings.SITE_ID}) 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: try:
return item.get_absolute_url() return item.get_absolute_url()
except AttributeError: 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): def __get_dynamic_attr(self, attname, obj, default=None):
try: try:

View File

@ -3,7 +3,7 @@ from django.http import HttpResponse, Http404
def feed(request, url, feed_dict=None): def feed(request, url, feed_dict=None):
if not feed_dict: if not feed_dict:
raise Http404, "No feeds are registered." raise Http404("No feeds are registered.")
try: try:
slug, param = url.split('/', 1) slug, param = url.split('/', 1)
@ -13,12 +13,12 @@ def feed(request, url, feed_dict=None):
try: try:
f = feed_dict[slug] f = feed_dict[slug]
except KeyError: except KeyError:
raise Http404, "Slug %r isn't registered." % slug raise Http404("Slug %r isn't registered." % slug)
try: try:
feedgen = f(slug, request).get_feed(param) feedgen = f(slug, request).get_feed(param)
except feeds.FeedDoesNotExist: 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) response = HttpResponse(mimetype=feedgen.mime_type)
feedgen.write(response, 'utf-8') feedgen.write(response, 'utf-8')

View File

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

View File

@ -71,7 +71,7 @@ class BaseCache(object):
ValueError exception. ValueError exception.
""" """
if key not in self: 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 new_value = self.get(key) + delta
self.set(key, new_value) self.set(key, new_value)
return new_value return new_value

View File

@ -129,7 +129,7 @@ class CacheClass(BaseCache):
try: try:
os.makedirs(self._dir) os.makedirs(self._dir)
except OSError: 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): def _key_to_file(self, key):
""" """

View File

@ -34,16 +34,16 @@ class BaseHandler(object):
try: try:
dot = middleware_path.rindex('.') dot = middleware_path.rindex('.')
except ValueError: 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:] mw_module, mw_classname = middleware_path[:dot], middleware_path[dot+1:]
try: try:
mod = import_module(mw_module) mod = import_module(mw_module)
except ImportError, e: 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: try:
mw_class = getattr(mod, mw_classname) mw_class = getattr(mod, mw_classname)
except AttributeError: 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: try:
mw_instance = mw_class() mw_instance = mw_class()
@ -113,7 +113,7 @@ class BaseHandler(object):
view_name = callback.func_name # If it's a function view_name = callback.func_name # If it's a function
except AttributeError: except AttributeError:
view_name = callback.__class__.__name__ + '.__call__' # If it's a class 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 return response
except http.Http404, e: except http.Http404, e:

View File

@ -152,7 +152,7 @@ def call_command(name, *args, **options):
else: else:
klass = load_command_class(app_name, name) klass = load_command_class(app_name, name)
except KeyError: 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 # 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 # when the script runs from the command line, but since call_command can

View File

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

View File

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

View File

@ -12,7 +12,7 @@ from django.db.backends import *
from django.db.backends.creation import BaseDatabaseCreation from django.db.backends.creation import BaseDatabaseCreation
def complain(*args, **kwargs): 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): def ignore(*args, **kwargs):
pass pass

View File

@ -27,7 +27,7 @@ except ImportError, exc:
exc = e1 exc = e1
else: else:
module = 'either pysqlite2 or sqlite3 modules (tried in that order)' 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 DatabaseError = Database.DatabaseError
@ -157,7 +157,7 @@ class DatabaseWrapper(BaseDatabaseWrapper):
settings_dict = self.settings_dict settings_dict = self.settings_dict
if not settings_dict['NAME']: if not settings_dict['NAME']:
from django.core.exceptions import ImproperlyConfigured 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 = { kwargs = {
'database': settings_dict['NAME'], 'database': settings_dict['NAME'],
'detect_types': Database.PARSE_DECLTYPES | Database.PARSE_COLNAMES, '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) raise TypeError("Proxy model '%s' has no non-abstract model base class." % name)
if (new_class._meta.local_fields or if (new_class._meta.local_fields or
new_class._meta.local_many_to_many): new_class._meta.local_many_to_many):
raise FieldError("Proxy model '%s' contains model fields." raise FieldError("Proxy model '%s' contains model fields." % name)
% name)
while base._meta.proxy: while base._meta.proxy:
base = base._meta.proxy_for_model base = base._meta.proxy_for_model
new_class._meta.setup_proxy(base) new_class._meta.setup_proxy(base)
@ -333,7 +332,7 @@ class Model(object):
except AttributeError: except AttributeError:
pass pass
if kwargs: 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) signals.post_init.send(sender=self.__class__, instance=self)
def __repr__(self): def __repr__(self):
@ -427,8 +426,7 @@ class Model(object):
non-SQL backends), respectively. Normally, they should not be set. non-SQL backends), respectively. Normally, they should not be set.
""" """
if force_insert and force_update: if force_insert and force_update:
raise ValueError("Cannot force both insert and updating in " raise ValueError("Cannot force both insert and updating in model saving.")
"model saving.")
self.save_base(using=using, force_insert=force_insert, force_update=force_update) self.save_base(using=using, force_insert=force_insert, force_update=force_update)
save.alters_data = True save.alters_data = True
@ -621,7 +619,7 @@ class Model(object):
try: try:
return qs[0] return qs[0]
except IndexError: 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): def _get_next_or_previous_in_order(self, is_next):
cachename = "__%s_order_cache" % 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] return [pk_trace(v) for v in value]
elif lookup_type == 'isnull': elif lookup_type == 'isnull':
return [] 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): def _get_related_query_name(self, opts):
# This method defines the name that can be used to identify this # This method defines the name that can be used to identify this
@ -203,7 +203,7 @@ class SingleRelatedObjectDescriptor(object):
def __set__(self, instance, value): def __set__(self, instance, value):
if instance is None: 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 # The similarity of the code below to the code in
# ReverseSingleRelatedObjectDescriptor is annoying, but there's a bunch # ReverseSingleRelatedObjectDescriptor is annoying, but there's a bunch
@ -270,7 +270,7 @@ class ReverseSingleRelatedObjectDescriptor(object):
def __set__(self, instance, value): def __set__(self, instance, value):
if instance is None: 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 # If null=True, we can assign null here, but otherwise the value needs
# to be an instance of the related class. # to be an instance of the related class.
@ -343,7 +343,7 @@ class ForeignRelatedObjectsDescriptor(object):
def __set__(self, instance, value): def __set__(self, instance, value):
if instance is None: 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 = self.__get__(instance)
# If the foreign key can support nulls, then completely clear the related set. # If the foreign key can support nulls, then completely clear the related set.
@ -376,7 +376,7 @@ class ForeignRelatedObjectsDescriptor(object):
def add(self, *objs): def add(self, *objs):
for obj in objs: for obj in objs:
if not isinstance(obj, self.model): 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) setattr(obj, rel_field.name, instance)
obj.save(using=instance._state.db) obj.save(using=instance._state.db)
add.alters_data = True add.alters_data = True
@ -404,7 +404,7 @@ class ForeignRelatedObjectsDescriptor(object):
setattr(obj, rel_field.name, None) setattr(obj, rel_field.name, None)
obj.save(using=instance._state.db) obj.save(using=instance._state.db)
else: 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 remove.alters_data = True
def clear(self): 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. # from the method lookup table, as we do with add and remove.
if not rel.through._meta.auto_created: if not rel.through._meta.auto_created:
opts = through._meta 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) new_obj = super(ManyRelatedManager, self).using(self.instance._state.db).create(**kwargs)
self.add(new_obj) self.add(new_obj)
return 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)) # (obj, self.instance._state.db, obj._state.db))
new_ids.add(obj.pk) new_ids.add(obj.pk)
elif isinstance(obj, Model): 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: else:
new_ids.add(obj) new_ids.add(obj)
vals = self.through._default_manager.using(self.instance._state.db).values_list(target_field_name, flat=True) 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): def __set__(self, instance, value):
if instance is None: 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: if not self.related.field.rel.through._meta.auto_created:
opts = self.related.field.rel.through._meta 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 = self.__get__(instance)
manager.clear() manager.clear()
@ -636,11 +636,11 @@ class ReverseManyRelatedObjectsDescriptor(object):
def __set__(self, instance, value): def __set__(self, instance, value):
if instance is None: 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: if not self.field.rel.through._meta.auto_created:
opts = self.field.rel.through._meta 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 = self.__get__(instance)
manager.clear() manager.clear()

View File

@ -123,7 +123,7 @@ class AppCache(object):
return None return None
else: else:
return mod 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: finally:
self.write_lock.release() self.write_lock.release()

View File

@ -19,7 +19,7 @@ def ensure_default_manager(sender, **kwargs):
# Create the default manager, if needed. # Create the default manager, if needed.
try: try:
cls._meta.get_field('objects') 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: except FieldDoesNotExist:
pass pass
cls.add_to_class('objects', Manager()) cls.add_to_class('objects', Manager())
@ -210,7 +210,7 @@ class ManagerDescriptor(object):
def __get__(self, instance, type=None): def __get__(self, instance, type=None):
if instance != 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 return self.manager
class EmptyManager(Manager): class EmptyManager(Manager):

View File

@ -94,7 +94,7 @@ class Options(object):
# Any leftover attributes must be invalid. # Any leftover attributes must be invalid.
if meta_attrs != {}: 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: else:
self.verbose_name_plural = string_concat(self.verbose_name, 's') self.verbose_name_plural = string_concat(self.verbose_name, 's')
del self.meta del self.meta
@ -274,7 +274,7 @@ class Options(object):
for f in to_search: for f in to_search:
if f.name == name: if f.name == name:
return f 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): def get_field_by_name(self, name):
""" """

View File

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

View File

@ -41,7 +41,7 @@ class Media(StrAndUnicode):
# Any leftover attributes must be invalid. # Any leftover attributes must be invalid.
# if media_attrs != {}: # 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): def __unicode__(self):
return self.render() return self.render()

View File

@ -439,10 +439,10 @@ def autoescape(parser, token):
""" """
args = token.contents.split() args = token.contents.split()
if len(args) != 2: if len(args) != 2:
raise TemplateSyntaxError("'Autoescape' tag requires exactly one argument.") raise TemplateSyntaxError("'autoescape' tag requires exactly one argument.")
arg = args[1] arg = args[1]
if arg not in (u'on', u'off'): 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',)) nodelist = parser.parse(('endautoescape',))
parser.delete_first_token() parser.delete_first_token()
return AutoEscapeControlNode((arg == 'on'), nodelist) return AutoEscapeControlNode((arg == 'on'), nodelist)
@ -604,8 +604,7 @@ def firstof(parser, token):
""" """
bits = token.split_contents()[1:] bits = token.split_contents()[1:]
if len(bits) < 1: if len(bits) < 1:
raise TemplateSyntaxError("'firstof' statement requires at least one" raise TemplateSyntaxError("'firstof' statement requires at least one argument")
" argument")
return FirstOfNode([parser.compile_filter(bit) for bit in bits]) return FirstOfNode([parser.compile_filter(bit) for bit in bits])
firstof = register.tag(firstof) firstof = register.tag(firstof)
@ -704,7 +703,7 @@ do_for = register.tag("for", do_for)
def do_ifequal(parser, token, negate): def do_ifequal(parser, token, negate):
bits = list(token.split_contents()) bits = list(token.split_contents())
if len(bits) != 3: 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] end_tag = 'end' + bits[0]
nodelist_true = parser.parse(('else', end_tag)) nodelist_true = parser.parse(('else', end_tag))
token = parser.next_token() token = parser.next_token()
@ -943,7 +942,7 @@ def now(parser, token):
""" """
bits = token.contents.split('"') bits = token.contents.split('"')
if len(bits) != 3: if len(bits) != 3:
raise TemplateSyntaxError, "'now' statement takes one argument" raise TemplateSyntaxError("'now' statement takes one argument")
format_string = bits[1] format_string = bits[1]
return NowNode(format_string) return NowNode(format_string)
now = register.tag(now) now = register.tag(now)
@ -997,7 +996,7 @@ def regroup(parser, token):
""" """
firstbits = token.contents.split(None, 3) firstbits = token.contents.split(None, 3)
if len(firstbits) != 4: if len(firstbits) != 4:
raise TemplateSyntaxError, "'regroup' tag takes five arguments" raise TemplateSyntaxError("'regroup' tag takes five arguments")
target = parser.compile_filter(firstbits[1]) target = parser.compile_filter(firstbits[1])
if firstbits[2] != 'by': if firstbits[2] != 'by':
raise TemplateSyntaxError("second argument to 'regroup' tag must be 'by'") raise TemplateSyntaxError("second argument to 'regroup' tag must be 'by'")
@ -1067,7 +1066,7 @@ def templatetag(parser, token):
""" """
bits = token.contents.split() bits = token.contents.split()
if len(bits) != 2: if len(bits) != 2:
raise TemplateSyntaxError, "'templatetag' statement takes one argument" raise TemplateSyntaxError("'templatetag' statement takes one argument")
tag = bits[1] tag = bits[1]
if tag not in TemplateTagNode.mapping: if tag not in TemplateTagNode.mapping:
raise TemplateSyntaxError("Invalid templatetag argument: '%s'." 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)) return (source, make_origin(display_name, loader, name, dirs))
except TemplateDoesNotExist: except TemplateDoesNotExist:
pass pass
raise TemplateDoesNotExist, name raise TemplateDoesNotExist(name)
def find_template_source(name, dirs=None): def find_template_source(name, dirs=None):
# For backward compatibility # For backward compatibility
@ -180,6 +180,6 @@ def select_template(template_name_list):
except TemplateDoesNotExist: except TemplateDoesNotExist:
continue continue
# If we get here, none of the templates could be loaded # 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') 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 error_msg = "Invalid template name in 'extends' tag: %r." % parent
if self.parent_name_expr: if self.parent_name_expr:
error_msg += " Got this from the '%s' variable." % self.parent_name_expr.token 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'): if hasattr(parent, 'render'):
return parent # parent is a Template object return parent # parent is a Template object
try: try:
return get_template(parent) return get_template(parent)
except TemplateDoesNotExist: 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): def render(self, context):
compiled_parent = self.get_parent(context) compiled_parent = self.get_parent(context)
@ -165,13 +165,13 @@ def do_block(parser, token):
""" """
bits = token.contents.split() bits = token.contents.split()
if len(bits) != 2: 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] block_name = bits[1]
# Keep track of the names of BlockNodes found in this template, so we can # Keep track of the names of BlockNodes found in this template, so we can
# check for duplication. # check for duplication.
try: try:
if block_name in parser.__loaded_blocks: 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) parser.__loaded_blocks.append(block_name)
except AttributeError: # parser.__loaded_blocks isn't a list yet except AttributeError: # parser.__loaded_blocks isn't a list yet
parser.__loaded_blocks = [block_name] parser.__loaded_blocks = [block_name]
@ -191,7 +191,7 @@ def do_extends(parser, token):
""" """
bits = token.split_contents() bits = token.split_contents()
if len(bits) != 2: 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 parent_name, parent_name_expr = None, None
if bits[1][0] in ('"', "'") and bits[1][-1] == bits[1][0]: if bits[1][0] in ('"', "'") and bits[1][-1] == bits[1][0]:
parent_name = bits[1][1:-1] parent_name = bits[1][1:-1]
@ -199,7 +199,7 @@ def do_extends(parser, token):
parent_name_expr = parser.compile_filter(bits[1]) parent_name_expr = parser.compile_filter(bits[1])
nodelist = parser.parse() nodelist = parser.parse()
if nodelist.get_nodes_by_type(ExtendsNode): 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) return ExtendsNode(nodelist, parent_name, parent_name_expr)
def do_include(parser, token): def do_include(parser, token):
@ -212,7 +212,7 @@ def do_include(parser, token):
""" """
bits = token.split_contents() bits = token.split_contents()
if len(bits) != 2: 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] path = bits[1]
if path[0] in ('"', "'") and path[-1] == path[0]: if path[0] in ('"', "'") and path[-1] == path[0]:
return ConstantIncludeNode(path[1:-1]) return ConstantIncludeNode(path[1:-1])

View File

@ -20,7 +20,7 @@ for app in settings.INSTALLED_APPS:
try: try:
mod = import_module(app) mod = import_module(app)
except ImportError, e: 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') template_dir = os.path.join(os.path.dirname(mod.__file__), 'templates')
if os.path.isdir(template_dir): if os.path.isdir(template_dir):
app_template_dirs.append(template_dir.decode(fs_encoding)) app_template_dirs.append(template_dir.decode(fs_encoding))
@ -59,7 +59,7 @@ class Loader(BaseLoader):
file.close() file.close()
except IOError: except IOError:
pass pass
raise TemplateDoesNotExist, template_name raise TemplateDoesNotExist(template_name)
_loader = Loader() _loader = Loader()

View File

@ -31,7 +31,7 @@ class Loader(BaseLoader):
return (template, make_origin(display_name, loader, name, dirs)) return (template, make_origin(display_name, loader, name, dirs))
except TemplateDoesNotExist: except TemplateDoesNotExist:
pass pass
raise TemplateDoesNotExist, name raise TemplateDoesNotExist(name)
def load_template(self, template_name, template_dirs=None): def load_template(self, template_name, template_dirs=None):
if template_name not in self.template_cache: 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)) return (resource_string(app, pkg_name).decode(settings.FILE_CHARSET), 'egg:%s:%s' % (app, pkg_name))
except: except:
pass pass
raise TemplateDoesNotExist, template_name raise TemplateDoesNotExist(template_name)
_loader = Loader() _loader = Loader()

View File

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

View File

@ -104,7 +104,7 @@ def do_get_available_languages(parser, token):
""" """
args = token.contents.split() args = token.contents.split()
if len(args) != 3 or args[1] != 'as': 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]) return GetAvailableLanguagesNode(args[2])
def do_get_current_language(parser, token): def do_get_current_language(parser, token):
@ -121,7 +121,7 @@ def do_get_current_language(parser, token):
""" """
args = token.contents.split() args = token.contents.split()
if len(args) != 3 or args[1] != 'as': 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]) return GetCurrentLanguageNode(args[2])
def do_get_current_language_bidi(parser, token): def do_get_current_language_bidi(parser, token):
@ -138,7 +138,7 @@ def do_get_current_language_bidi(parser, token):
""" """
args = token.contents.split() args = token.contents.split()
if len(args) != 3 or args[1] != 'as': 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]) return GetCurrentLanguageBidiNode(args[2])
def do_translate(parser, token): def do_translate(parser, token):
@ -178,7 +178,7 @@ def do_translate(parser, token):
if self.tag() == 'noop': if self.tag() == 'noop':
noop = True noop = True
else: else:
raise TemplateSyntaxError, "only option for 'trans' is 'noop'" raise TemplateSyntaxError("only option for 'trans' is 'noop'")
else: else:
noop = False noop = False
return (value, noop) return (value, noop)
@ -215,16 +215,16 @@ def do_block_translate(parser, token):
if tag == 'with' or tag == 'and': if tag == 'with' or tag == 'and':
value = self.value() value = self.value()
if self.tag() != 'as': 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( extra_context[self.tag()] = VariableNode(
parser.compile_filter(value)) parser.compile_filter(value))
elif tag == 'count': elif tag == 'count':
counter = parser.compile_filter(self.value()) counter = parser.compile_filter(self.value())
if self.tag() != 'as': 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() countervar = self.tag()
else: else:
raise TemplateSyntaxError, "unknown subtag %s for 'blocktrans' found" % tag raise TemplateSyntaxError("unknown subtag %s for 'blocktrans' found" % tag)
return (countervar, counter, extra_context) return (countervar, counter, extra_context)
countervar, counter, extra_context = BlockTranslateParser(token.contents).top() countervar, counter, extra_context = BlockTranslateParser(token.contents).top()
@ -239,7 +239,7 @@ def do_block_translate(parser, token):
break break
if countervar and counter: if countervar and counter:
if token.contents.strip() != 'plural': 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: while parser.tokens:
token = parser.next_token() token = parser.next_token()
if token.token_type in (TOKEN_VAR, TOKEN_TEXT): if token.token_type in (TOKEN_VAR, TOKEN_TEXT):
@ -247,7 +247,7 @@ def do_block_translate(parser, token):
else: else:
break break
if token.contents.strip() != 'endblocktrans': 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, return BlockTranslateNode(extra_context, singular, plural, countervar,
counter) counter)

View File

@ -208,7 +208,7 @@ class MultiValueDict(dict):
try: try:
list_ = super(MultiValueDict, self).__getitem__(key) list_ = super(MultiValueDict, self).__getitem__(key)
except KeyError: except KeyError:
raise MultiValueDictKeyError, "Key %r not found in %r" % (key, self) raise MultiValueDictKeyError("Key %r not found in %r" % (key, self))
try: try:
return list_[-1] return list_[-1]
except IndexError: except IndexError:
@ -325,7 +325,7 @@ class MultiValueDict(dict):
Also accepts keyword args. Also accepts keyword args.
""" """
if len(args) > 1: 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: if args:
other_dict = args[0] other_dict = args[0]
if isinstance(other_dict, MultiValueDict): if isinstance(other_dict, MultiValueDict):
@ -336,7 +336,7 @@ class MultiValueDict(dict):
for key, value in other_dict.items(): for key, value in other_dict.items():
self.setlistdefault(key, []).append(value) self.setlistdefault(key, []).append(value)
except TypeError: 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(): for key, value in kwargs.iteritems():
self.setlistdefault(key, []).append(value) self.setlistdefault(key, []).append(value)
@ -400,7 +400,7 @@ class ImmutableList(tuple):
if isinstance(self.warning, Exception): if isinstance(self.warning, Exception):
raise self.warning raise self.warning
else: else:
raise AttributeError, self.warning raise AttributeError(self.warning)
# All list mutation functions complain. # All list mutation functions complain.
__delitem__ = complain __delitem__ = complain

View File

@ -186,7 +186,7 @@ def javascript_quote(s, quote_double_quotes=False):
if type(s) == str: if type(s) == str:
s = s.decode('utf-8') s = s.decode('utf-8')
elif type(s) != unicode: elif type(s) != unicode:
raise TypeError, s raise TypeError(s)
s = s.replace('\\', '\\\\') s = s.replace('\\', '\\\\')
s = s.replace('\r', '\\r') s = s.replace('\r', '\\r')
s = s.replace('\n', '\\n') 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()}) queryset = queryset.filter(**{'%s__lte' % date_field: datetime.datetime.now()})
date_list = queryset.dates(date_field, 'year')[::-1] date_list = queryset.dates(date_field, 'year')[::-1]
if not date_list and not allow_empty: 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: if date_list and num_latest:
latest = queryset.order_by('-'+date_field)[: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: elif slug and slug_field:
lookup_kwargs['%s__exact' % slug_field] = slug lookup_kwargs['%s__exact' % slug_field] = slug
else: 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: try:
obj = queryset.get(**lookup_kwargs) obj = queryset.get(**lookup_kwargs)
except ObjectDoesNotExist: 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: if not template_name:
template_name = "%s/%s_detail.html" % (model._meta.app_label, model._meta.object_name.lower()) template_name = "%s/%s_detail.html" % (model._meta.app_label, model._meta.object_name.lower())
if template_name_field: 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: elif slug and slug_field:
queryset = queryset.filter(**{slug_field: slug}) queryset = queryset.filter(**{slug_field: slug})
else: 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: try:
obj = queryset.get() obj = queryset.get()
except ObjectDoesNotExist: 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: if not template_name:
template_name = "%s/%s_detail.html" % (model._meta.app_label, model._meta.object_name.lower()) template_name = "%s/%s_detail.html" % (model._meta.app_label, model._meta.object_name.lower())
if template_name_field: 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]]) 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))) csrc.append("catalog['%s'][%d] = '%s';\n" % (javascript_quote(k[0]), k[1], javascript_quote(v)))
else: else:
raise TypeError, k raise TypeError(k)
csrc.sort() csrc.sort()
for k, v in pdict.items(): for k, v in pdict.items():
src.append("catalog['%s'] = [%s];\n" % (javascript_quote(k), ','.join(["''"]*(v+1)))) 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 os.path.isdir(fullpath):
if show_indexes: if show_indexes:
return directory_index(newpath, fullpath) 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): 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. # Respect the If-Modified-Since header.
statobj = os.stat(fullpath) statobj = os.stat(fullpath)
mimetype = mimetypes.guess_type(fullpath)[0] or 'application/octet-stream' mimetype = mimetypes.guess_type(fullpath)[0] or 'application/octet-stream'