PEP8 cleanups.

This commit is contained in:
Roberto Rosario
2015-08-19 14:50:44 -04:00
parent 683e54fea1
commit 68f3c6eee7
49 changed files with 1078 additions and 216 deletions
+13 -5
View File
@@ -18,8 +18,8 @@ class ModelAttribute(object):
return result
except IndexError:
# We were passed a model instance, try again using the model of the
# instance
# We were passed a model instance, try again using the model of
# the instance
# If we are already in the model class, exit with an error
if model.__class__ == models.base.ModelBase:
@@ -30,16 +30,24 @@ class ModelAttribute(object):
@classmethod
def get_choices_for(cls, model, type_names=None):
return [
(attribute.name, attribute) for attribute in cls.get_for(model, type_names)
(
attribute.name, attribute
) for attribute in cls.get_for(model, type_names)
]
@classmethod
def help_text_for(cls, model, type_names=None):
result = []
for count, attribute in enumerate(cls.get_for(model, type_names), 1):
result.append('{}) {}'.format(count, unicode(attribute.get_display(show_name=True))))
result.append(
'{}) {}'.format(
count, unicode(attribute.get_display(show_name=True))
)
)
return ' '.join([ugettext('Available attributes: '), ', '.join(result)])
return ' '.join(
[ugettext('Available attributes: '), ', '.join(result)]
)
def get_display(self, show_name=False):
if self.description:
+3 -1
View File
@@ -101,7 +101,9 @@ class CompressedFile(object):
filename for filename in zfobj.namelist() if not filename.endswith('/')
]
return (
SimpleUploadedFile(name=filename, content=zfobj.read(filename)) for filename in filenames
SimpleUploadedFile(
name=filename, content=zfobj.read(filename)
) for filename in filenames
)
except zipfile.BadZipfile:
raise NotACompressedFile
+3 -1
View File
@@ -54,7 +54,9 @@ class DetailForm(forms.ModelForm):
self.fields[field_name].help_text = ''
for field_name, field in self.fields.items():
self.fields[field_name].widget.attrs.update({'readonly': 'readonly'})
self.fields[field_name].widget.attrs.update(
{'readonly': 'readonly'}
)
class ChoiceForm(forms.Form):
+24 -11
View File
@@ -4,11 +4,9 @@ from django.conf import settings
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ImproperlyConfigured
from django.http import Http404, HttpResponseRedirect
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _
from django.views.generic import FormView, TemplateView
from django.views.generic.detail import SingleObjectMixin
from django.views.generic.edit import CreateView, DeleteView, UpdateView
from django.views.generic.list import ListView
@@ -110,7 +108,9 @@ class AssignRemoveView(ExtraContextMixin, ViewPermissionCheckMixin, ObjectPermis
label = dict(flat_list)[selection]
if self.decode_content_type:
model, pk = selection.split(',')
selection_obj = ContentType.objects.get(model=model).get_object_for_this_type(pk=pk)
selection_obj = ContentType.objects.get(
model=model
).get_object_for_this_type(pk=pk)
else:
selection_obj = selection
@@ -202,7 +202,9 @@ class MultiFormView(FormView):
def get_forms(self, form_classes):
return dict(
[
(key, self._create_form(key, klass)) for key, klass in form_classes.items()
(
key, self._create_form(key, klass)
) for key, klass in form_classes.items()
]
)
@@ -270,7 +272,9 @@ class SingleObjectCreateView(ViewPermissionCheckMixin, ExtraContextMixin, Redire
try:
messages.success(
self.request,
_('%s created successfully.') % self.extra_context['object_name'].capitalize()
_(
'%s created successfully.'
) % self.extra_context['object_name'].capitalize()
)
except KeyError:
messages.success(
@@ -294,7 +298,8 @@ class SingleObjectDeleteView(ViewPermissionCheckMixin, ObjectPermissionCheckMixi
except Exception as exception:
try:
messages.error(
self.request, _('Error deleting %s.') % self.extra_context['object_name']
self.request,
_('Error deleting %s.') % self.extra_context['object_name']
)
except KeyError:
messages.error(
@@ -305,7 +310,10 @@ class SingleObjectDeleteView(ViewPermissionCheckMixin, ObjectPermissionCheckMixi
else:
try:
messages.success(
self.request, _('%s deleted successfully.') % self.extra_context['object_name'].capitalize()
self.request,
_(
'%s deleted successfully.'
) % self.extra_context['object_name'].capitalize()
)
except KeyError:
messages.success(
@@ -325,7 +333,10 @@ class SingleObjectEditView(ViewPermissionCheckMixin, ObjectPermissionCheckMixin,
try:
messages.error(
self.request, _('Error saving %s details.') % self.extra_context['object_name']
self.request,
_(
'Error saving %s details.'
) % self.extra_context['object_name']
)
except KeyError:
messages.error(
@@ -339,7 +350,10 @@ class SingleObjectEditView(ViewPermissionCheckMixin, ObjectPermissionCheckMixin,
try:
messages.success(
self.request, _('%s details saved successfully.') % self.extra_context['object_name'].capitalize()
self.request,
_(
'%s details saved successfully.'
) % self.extra_context['object_name'].capitalize()
)
except KeyError:
messages.success(
@@ -354,4 +368,3 @@ class SingleObjectListView(PaginationMixin, ViewPermissionCheckMixin, ObjectList
def get_paginate_by(self, queryset):
return setting_paginate_by.value
@@ -8,5 +8,7 @@ class AjaxRedirect(object):
def process_response(self, request, response):
if request.is_ajax():
if type(response) == HttpResponseRedirect:
response.status_code = getattr(settings, 'AJAX_REDIRECT_CODE', 302)
response.status_code = getattr(
settings, 'AJAX_REDIRECT_CODE', 302
)
return response
File diff suppressed because one or more lines are too long
+11 -4
View File
@@ -49,7 +49,8 @@ class ObjectListPermissionFilterMixin(object):
self.request.user, (self.object_permission,)
)
except PermissionDenied:
# No global permission, filter ther queryset per object + permission
# No global permission, filter ther queryset per object +
# permission
return AccessControlList.objects.filter_by_access(
self.object_permission, self.request.user, queryset
)
@@ -79,7 +80,9 @@ class ObjectPermissionCheckMixin(object):
self.get_permission_object()
)
return super(ObjectPermissionCheckMixin, self).dispatch(request, *args, **kwargs)
return super(
ObjectPermissionCheckMixin, self
).dispatch(request, *args, **kwargs)
class RedirectionMixin(object):
@@ -111,7 +114,9 @@ class RedirectionMixin(object):
)
)
return super(RedirectionMixin, self).dispatch(request, *args, **kwargs)
return super(
RedirectionMixin, self
).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super(RedirectionMixin, self).get_context_data(**kwargs)
@@ -137,4 +142,6 @@ class ViewPermissionCheckMixin(object):
self.request.user, (self.view_permission,)
)
return super(ViewPermissionCheckMixin, self).dispatch(request, *args, **kwargs)
return super(
ViewPermissionCheckMixin, self
).dispatch(request, *args, **kwargs)
+8 -2
View File
@@ -9,7 +9,11 @@ from smart_settings import Namespace
namespace = Namespace(name='common', label=_('Common'))
setting_temporary_directory = namespace.add_setting(
global_name='COMMON_TEMPORARY_DIRECTORY', default=tempfile.gettempdir(),
help_text=_('Temporary directory used site wide to store thumbnails, previews and temporary files. If none is specified, one will be created using tempfile.mkdtemp()'),
help_text=_(
'Temporary directory used site wide to store thumbnails, previews '
'and temporary files. If none is specified, one will be created '
'using tempfile.mkdtemp()'
),
is_path=True
)
setting_shared_storage = namespace.add_setting(
@@ -20,5 +24,7 @@ setting_shared_storage = namespace.add_setting(
setting_paginate_by = namespace.add_setting(
global_name='COMMON_PAGINATE_BY',
default=40,
help_text=_('An integer specifying how many objects should be displayed per page.')
help_text=_(
'An integer specifying how many objects should be displayed per page.'
)
)
+6 -3
View File
@@ -100,7 +100,9 @@ def return_attrib(obj, attrib, arguments=None):
try:
if isinstance(attrib, types.FunctionType):
return attrib(obj)
elif isinstance(obj, types.DictType) or isinstance(obj, types.DictionaryType):
elif isinstance(
obj, types.DictType
) or isinstance(obj, types.DictionaryType):
return obj[attrib]
else:
result = reduce(getattr, attrib.split('.'), obj)
@@ -140,12 +142,13 @@ def urlquote(link=None, get=None):
assert link or get
if isinstance(link, dict):
# urlqoute({'key': 'value', 'key2': 'value2'}) --> key=value&key2=value2
# urlqoute({'key': 'value', 'key2': 'value2'}) -->
# key=value&key2=value2
assert not get, get
get = link
link = ''
assert isinstance(get, dict), 'wrong type "%s", dict required' % type(get)
# assert not (link.startswith('http://') or link.startswith('https://')), \
# assert not (link.startswith('http://') or link.startswith('https://')),
# 'This method should only quote the url path.
# It should not start with http(s):// (%s)' % (
# link)
-3
View File
@@ -12,9 +12,6 @@ from django.utils.http import urlencode
from django.utils.translation import ugettext_lazy as _
from django.views.generic import TemplateView
from documents.search import document_search
from .classes import MissingItem
from .forms import (
LicenseForm, LocaleProfileForm, LocaleProfileForm_view,
UserForm, UserForm_view
-45
View File
@@ -1,6 +1,5 @@
from __future__ import unicode_literals
from itertools import chain
import os
from django import forms
@@ -107,50 +106,6 @@ class PlainWidget(forms.widgets.Widget):
return mark_safe('%s' % value)
class ScrollableCheckboxSelectMultiple(forms.widgets.CheckboxSelectMultiple):
"""
Class for a form widget composed of a selection of checkboxes wrapped
in a div tag with automatic overflow to add scrollbars when the list
exceds the height of the div
"""
def render(self, name, value, attrs=None, choices=()):
if value is None:
value = []
has_id = attrs and 'id' in attrs
final_attrs = self.build_attrs(attrs, name=name)
# TODO: Move this styling to a CSS class
output = [
'<ul class="undecorated_list" style="margin-left: 5px; margin-top: 3px; margin-bottom: 3px;">'
]
# Normalize to strings
str_values = set([force_unicode(v) for v in value])
for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
# If an ID attribute was given, add a numeric index as a suffix,
# so that the checkboxes don't all have the same ID attribute.
if has_id:
final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
label_for = ' for="%s"' % final_attrs['id']
else:
label_for = ''
cb = forms.widgets.CheckboxInput(
final_attrs, check_test=lambda value: value in str_values
)
option_value = force_unicode(option_value)
rendered_cb = cb.render(name, option_value)
option_label = conditional_escape(force_unicode(option_label))
output.append(
'<li><label%s>%s %s</label></li>' % (
label_for, rendered_cb, option_label
)
)
output.append('</ul>')
return mark_safe(
'<div class="text_area_div">%s</div>' % '\n'.join(output)
)
class TextAreaDiv(forms.widgets.Widget):
"""
Class to define a form widget that simulates the behavior of a