Skip to content

Commit

Permalink
Ran the 2to3 script 2to3 -w .
Browse files Browse the repository at this point in the history
  • Loading branch information
epicserve committed Feb 10, 2016
1 parent 1c64f4e commit c5c459f
Show file tree
Hide file tree
Showing 20 changed files with 73 additions and 70 deletions.
2 changes: 1 addition & 1 deletion categories/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,4 @@ def register():
try:
register()
except Exception as e:
print e
print(e)
8 changes: 4 additions & 4 deletions categories/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

class NullTreeNodeChoiceField(forms.ModelChoiceField):
"""A ModelChoiceField for tree nodes."""
def __init__(self, level_indicator=u'---', *args, **kwargs):
def __init__(self, level_indicator='---', *args, **kwargs):
self.level_indicator = level_indicator
super(NullTreeNodeChoiceField, self).__init__(*args, **kwargs)

Expand All @@ -20,7 +20,7 @@ def label_from_instance(self, obj):
Creates labels which represent the tree level of each node when
generating option labels.
"""
return u'%s %s' % (self.level_indicator * getattr(
return '%s %s' % (self.level_indicator * getattr(
obj, obj._mptt_meta.level_attr), obj)
if RELATION_MODELS:
from .models import CategoryRelation
Expand Down Expand Up @@ -68,8 +68,8 @@ class Media:
if REGISTER_ADMIN:
admin.site.register(Category, CategoryAdmin)

for model, modeladmin in admin.site._registry.items():
if model in MODEL_REGISTRY.values() and modeladmin.fieldsets:
for model, modeladmin in list(admin.site._registry.items()):
if model in list(MODEL_REGISTRY.values()) and modeladmin.fieldsets:
fieldsets = getattr(modeladmin, 'fieldsets', ())
fields = [cat.split('.')[2] for cat in MODEL_REGISTRY if MODEL_REGISTRY[cat] == model]
# check each field to see if already defined
Expand Down
4 changes: 2 additions & 2 deletions categories/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ def handle_class_prepared(sender, **kwargs):
sender_app = sender._meta.app_label
sender_name = sender._meta.model_name

for key, val in FK_REGISTRY.items():
for key, val in list(FK_REGISTRY.items()):
app_name, model_name = key.split('.')
if app_name == sender_app and sender_name == model_name:
registry.register_model(app_name, sender, 'ForeignKey', val)

for key, val in M2M_REGISTRY.items():
for key, val in list(M2M_REGISTRY.items()):
app_name, model_name = key.split('.')
if app_name == sender_app and sender_name == model_name:
registry.register_model(app_name, sender, 'ManyToManyField', val)
8 changes: 4 additions & 4 deletions categories/editor/templatetags/admin_tree_list_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,10 @@ def items_for_tree_result(cl, result, form):
result_id = repr(force_unicode(value))[1:]
first = False
if django.VERSION[1] < 4:
yield mark_safe(u'<%s%s>%s<a href="%s"%s>%s</a></%s>' % \
yield mark_safe('<%s%s>%s<a href="%s"%s>%s</a></%s>' % \
(table_tag, row_class, checkbox_value, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), conditional_escape(result_repr), table_tag))
else:
yield mark_safe(u'<%s%s><a href="%s"%s>%s</a></%s>' % \
yield mark_safe('<%s%s><a href="%s"%s>%s</a></%s>' % \
(table_tag, row_class, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), conditional_escape(result_repr), table_tag))

else:
Expand All @@ -106,9 +106,9 @@ def items_for_tree_result(cl, result, form):
result_repr = mark_safe(force_unicode(bf.errors) + force_unicode(bf))
else:
result_repr = conditional_escape(result_repr)
yield mark_safe(u'<td%s>%s</td>' % (row_class, result_repr))
yield mark_safe('<td%s>%s</td>' % (row_class, result_repr))
if form and not form[cl.model._meta.pk.name].is_hidden:
yield mark_safe(u'<td>%s</td>' % force_unicode(form[cl.model._meta.pk.name]))
yield mark_safe('<td>%s</td>' % force_unicode(form[cl.model._meta.pk.name]))


class TreeList(list):
Expand Down
4 changes: 2 additions & 2 deletions categories/editor/tree_editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

import django

import settings
from . import settings


class TreeEditorQuerySet(QuerySet):
Expand Down Expand Up @@ -162,7 +162,7 @@ def old_changelist_view(self, request, extra_context=None):
# parameter via the query string. If wacky parameters were given and
# the 'invalid=1' parameter was already in the query string, something
# is screwed up with the database, so display an error page.
if ERROR_FLAG in request.GET.keys():
if ERROR_FLAG in list(request.GET.keys()):
return render_to_response(
'admin/invalid_setup.html', {'title': _('Database error')})
return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1')
Expand Down
11 changes: 6 additions & 5 deletions categories/editor/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from django.utils.text import capfirst
from django.utils import dateformat
from django.utils.html import escape
import collections


def lookup_field(name, obj, model_admin=None):
Expand All @@ -20,7 +21,7 @@ def lookup_field(name, obj, model_admin=None):
except models.FieldDoesNotExist:
# For non-field values, the value is either a method, property or
# returned via a callable.
if callable(name):
if isinstance(name, collections.Callable):
attr = name
value = attr(obj)
elif (model_admin is not None and hasattr(model_admin, name) and
Expand All @@ -29,7 +30,7 @@ def lookup_field(name, obj, model_admin=None):
value = attr(obj)
else:
attr = getattr(obj, name)
if callable(attr):
if isinstance(attr, collections.Callable):
value = attr()
else:
value = attr
Expand Down Expand Up @@ -57,12 +58,12 @@ def label_for_field(name, model, model_admin=None, return_attr=False):
except models.FieldDoesNotExist:
if name == "__unicode__":
label = force_unicode(model._meta.verbose_name)
attr = unicode
attr = str
elif name == "__str__":
label = smart_str(model._meta.verbose_name)
attr = str
else:
if callable(name):
if isinstance(name, collections.Callable):
attr = name
elif model_admin is not None and hasattr(model_admin, name):
attr = getattr(model_admin, name)
Expand All @@ -76,7 +77,7 @@ def label_for_field(name, model, model_admin=None, return_attr=False):

if hasattr(attr, "short_description"):
label = attr.short_description
elif callable(attr):
elif isinstance(attr, collections.Callable):
if attr.__name__ == "<lambda>":
label = "--"
else:
Expand Down
2 changes: 1 addition & 1 deletion categories/management/commands/drop_category_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,6 @@ def handle(self, *args, **options):

from categories.migration import drop_field
if len(args) != 3:
print "You must specify an Application name, a Model name and a Field name"
print("You must specify an Application name, a Model name and a Field name")

drop_field(*args)
2 changes: 1 addition & 1 deletion categories/management/commands/import_categories.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def handle(self, *file_paths, **options):

for file_path in file_paths:
if not os.path.isfile(file_path):
print "File %s not found." % file_path
print("File %s not found." % file_path)
continue
f = file(file_path, 'r')
data = f.readlines()
Expand Down
4 changes: 2 additions & 2 deletions categories/migration.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals


from django.db import connection, transaction
from django.apps import apps
Expand Down Expand Up @@ -47,7 +47,7 @@ def migrate_app(sender, *args, **kwargs):

app_name = app_config.label

fields = [fld for fld in registry._field_registry.keys() if fld.startswith(app_name)]
fields = [fld for fld in list(registry._field_registry.keys()) if fld.startswith(app_name)]

sid = transaction.savepoint()
for fld in fields:
Expand Down
2 changes: 1 addition & 1 deletion categories/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals


from django.db import models, migrations
import django.core.files.storage
Expand Down
3 changes: 2 additions & 1 deletion categories/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from django.db import models
from django.utils.encoding import force_unicode
from django.contrib.contenttypes.models import ContentType
from functools import reduce
try:
from django.contrib.contenttypes.fields import GenericForeignKey
except ImportError:
Expand Down Expand Up @@ -141,7 +142,7 @@ class CategoryRelation(models.Model):
objects = CategoryRelationManager()

def __unicode__(self):
return u"CategoryRelation"
return "CategoryRelation"

try:
from south.db import db # South is required for migrating. Need to check for it
Expand Down
12 changes: 6 additions & 6 deletions categories/registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
These functions handle the adding of fields to other models
"""
from django.db.models import FieldDoesNotExist, ForeignKey, ManyToManyField
import fields
from . import fields
# from settings import self._field_registry, self._model_registry
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ImproperlyConfigured
Expand Down Expand Up @@ -32,7 +32,7 @@ def register_model(self, app, model_name, field_type, field_definitions):

app_label = app

if isinstance(field_definitions, basestring):
if isinstance(field_definitions, str):
field_definitions = [field_definitions]
elif not isinstance(field_definitions, collections.Iterable):
raise ImproperlyConfigured(_('Field configuration for %(app)s should '
Expand Down Expand Up @@ -64,7 +64,7 @@ def register_model(self, app, model_name, field_type, field_definitions):
extra_params = {'to': 'categories.Category', 'blank': True}
if field_type != 'ManyToManyField':
extra_params['null'] = True
if isinstance(fld, basestring):
if isinstance(fld, str):
field_name = fld
elif isinstance(fld, dict):
if 'name' in fld:
Expand Down Expand Up @@ -121,21 +121,21 @@ def _process_registry(registry, call_func):
from django.core.exceptions import ImproperlyConfigured
from django.db.models.loading import get_model

for key, value in registry.items():
for key, value in list(registry.items()):
model = get_model(*key.split('.'))
if model is None:
raise ImproperlyConfigured(_('%(key)s is not a model') % {'key': key})
if isinstance(value, (tuple, list)):
for item in value:
if isinstance(item, basestring):
if isinstance(item, str):
call_func(model, item)
elif isinstance(item, dict):
field_name = item.pop('name')
call_func(model, field_name, extra_params=item)
else:
raise ImproperlyConfigured(_("%(settings)s doesn't recognize the value of %(key)s") %
{'settings': 'CATEGORY_SETTINGS', 'key': key})
elif isinstance(value, basestring):
elif isinstance(value, str):
call_func(model, value)
elif isinstance(value, dict):
field_name = value.pop('name')
Expand Down
5 changes: 3 additions & 2 deletions categories/settings.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from django.conf import settings
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
import collections

DEFAULT_SETTINGS = {
'ALLOW_SLUG_CHANGE': False,
Expand All @@ -18,9 +19,9 @@
DEFAULT_SETTINGS.update(getattr(settings, 'CATEGORIES_SETTINGS', {}))

if DEFAULT_SETTINGS['SLUG_TRANSLITERATOR']:
if callable(DEFAULT_SETTINGS['SLUG_TRANSLITERATOR']):
if isinstance(DEFAULT_SETTINGS['SLUG_TRANSLITERATOR'], collections.Callable):
pass
elif isinstance(DEFAULT_SETTINGS['SLUG_TRANSLITERATOR'], basestring):
elif isinstance(DEFAULT_SETTINGS['SLUG_TRANSLITERATOR'], str):
from django.utils.importlib import import_module
bits = DEFAULT_SETTINGS['SLUG_TRANSLITERATOR'].split(".")
module = import_module(".".join(bits[:-1]))
Expand Down
40 changes: 20 additions & 20 deletions categories/south_migration.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,22 @@ def migrate_app(sender, app, created_models=None, verbosity=False, *args, **kwar
from .models import Category
from .registration import registry
import sys
import StringIO
import io

org_stderror = sys.stderr
sys.stderr = StringIO.StringIO() # south will print out errors to stderr
sys.stderr = io.StringIO() # south will print out errors to stderr
try:
from south.db import db
except ImportError:
raise ImproperlyConfigured(_('%(dependency)s must be installed for this command to work') %
{'dependency': 'South'})
# pull the information from the registry
if isinstance(app, basestring):
if isinstance(app, str):
app_name = app
else:
app_name = app.__name__.split('.')[-2]

fields = [fld for fld in registry._field_registry.keys() if fld.startswith(app_name)]
fields = [fld for fld in list(registry._field_registry.keys()) if fld.startswith(app_name)]
# call the south commands to add the fields/tables
for fld in fields:
app_name, model_name, field_name = fld.split('.')
Expand All @@ -43,14 +43,14 @@ def migrate_app(sender, app, created_models=None, verbosity=False, *args, **kwar
db.add_column(table_name, field_name, registry._field_registry[fld], keep_default=False)
db.commit_transaction()
if verbosity:
print (_('Added ForeignKey %(field_name)s to %(model_name)s') %
{'field_name': field_name, 'model_name': model_name})
except DatabaseError, e:
print((_('Added ForeignKey %(field_name)s to %(model_name)s') %
{'field_name': field_name, 'model_name': model_name}))
except DatabaseError as e:
db.rollback_transaction()
if "already exists" in str(e):
if verbosity > 1:
print (_('ForeignKey %(field_name)s to %(model_name)s already exists') %
{'field_name': field_name, 'model_name': model_name})
print((_('ForeignKey %(field_name)s to %(model_name)s already exists') %
{'field_name': field_name, 'model_name': model_name}))
else:
sys.stderr = org_stderror
raise e
Expand All @@ -66,14 +66,14 @@ def migrate_app(sender, app, created_models=None, verbosity=False, *args, **kwar
db.create_unique(table_name, ['%s_id' % model_name, 'category_id'])
db.commit_transaction()
if verbosity:
print (_('Added Many2Many table between %(model_name)s and %(category_table)s') %
{'model_name': model_name, 'category_table': 'category'})
except DatabaseError, e:
print((_('Added Many2Many table between %(model_name)s and %(category_table)s') %
{'model_name': model_name, 'category_table': 'category'}))
except DatabaseError as e:
db.rollback_transaction()
if "already exists" in str(e):
if verbosity > 1:
print (_('Many2Many table between %(model_name)s and %(category_table)s already exists') %
{'model_name': model_name, 'category_table': 'category'})
print((_('Many2Many table between %(model_name)s and %(category_table)s already exists') %
{'model_name': model_name, 'category_table': 'category'}))
else:
sys.stderr = org_stderror
raise e
Expand All @@ -98,23 +98,23 @@ def drop_field(app_name, model_name, field_name):
fld = '%s.%s.%s' % (app_name, model_name, field_name)

if isinstance(registry._field_registry[fld], CategoryFKField):
print (_('Dropping ForeignKey %(field_name)s from %(model_name)s') %
{'field_name': field_name, 'model_name': model_name})
print((_('Dropping ForeignKey %(field_name)s from %(model_name)s') %
{'field_name': field_name, 'model_name': model_name}))
try:
db.start_transaction()
table_name = mdl._meta.db_table
db.delete_column(table_name, field_name)
db.commit_transaction()
except DatabaseError, e:
except DatabaseError as e:
db.rollback_transaction()
raise e
elif isinstance(registry._field_registry[fld], CategoryM2MField):
print (_('Dropping Many2Many table between %(model_name)s and %(category_table)s') %
{'model_name': model_name, 'category_table': 'category'})
print((_('Dropping Many2Many table between %(model_name)s and %(category_table)s') %
{'model_name': model_name, 'category_table': 'category'}))
try:
db.start_transaction()
db.delete_table(table_name, cascade=False)
db.commit_transaction()
except DatabaseError, e:
except DatabaseError as e:
db.rollback_transaction()
raise e
6 changes: 3 additions & 3 deletions categories/templatetags/category_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def get_cat_model(model):
Return a class from a string or class
"""
try:
if isinstance(model, basestring):
if isinstance(model, str):
model_class = get_model(*model.split("."))
elif issubclass(model, CategoryBase):
model_class = model
Expand Down Expand Up @@ -119,13 +119,13 @@ def get_category_drilldown(parser, token):
'{%% %(tagname)s category_obj as varname %%}.'
if len(bits) == 4:
if bits[2] != 'as':
raise template.TemplateSyntaxError, error_str % {'tagname': bits[0]}
raise template.TemplateSyntaxError(error_str % {'tagname': bits[0]})
if bits[2] == 'as':
varname = bits[3].strip("'\"")
model = "categories.category"
if len(bits) == 6:
if bits[2] not in ('using', 'as') or bits[4] not in ('using', 'as'):
raise template.TemplateSyntaxError, error_str % {'tagname': bits[0]}
raise template.TemplateSyntaxError(error_str % {'tagname': bits[0]})
if bits[2] == 'as':
varname = bits[3].strip("'\"")
model = bits[5].strip("'\"")
Expand Down

0 comments on commit c5c459f

Please sign in to comment.