Skip to content

Commit

Permalink
Upgrade Python syntax with pyupgrade --py36-plus
Browse files Browse the repository at this point in the history
  • Loading branch information
hugovk committed Aug 27, 2021
1 parent a470d4a commit cc34677
Show file tree
Hide file tree
Showing 15 changed files with 49 additions and 59 deletions.
25 changes: 12 additions & 13 deletions advanced_filters/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ def lookups(self, request, model_admin):
if not model_admin:
raise Exception('Cannot use AdvancedListFilters without a '
'model_admin')
model_name = "%s.%s" % (model_admin.model._meta.app_label,
model_admin.model._meta.object_name)
model_name = "{}.{}".format(model_admin.model._meta.app_label,
model_admin.model._meta.object_name)
return AdvancedFilter.objects.filter_by_user(request.user).filter(
model=model_name).values_list('id', 'title')

Expand All @@ -43,13 +43,13 @@ def queryset(self, request, queryset):
return queryset


class AdminAdvancedFiltersMixin(object):
class AdminAdvancedFiltersMixin:
""" Generic AdvancedFilters mixin """
advanced_change_list_template = "admin/advanced_filters.html"
advanced_filter_form = AdvancedFilterForm

def __init__(self, *args, **kwargs):
super(AdminAdvancedFiltersMixin, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
if self.change_list_template:
self.original_change_list_template = self.change_list_template
else:
Expand Down Expand Up @@ -98,8 +98,7 @@ def changelist_view(self, request, extra_context=None):
extra_context=extra_context)
if response:
return response
return super(AdminAdvancedFiltersMixin, self
).changelist_view(request, extra_context=extra_context)
return super().changelist_view(request, extra_context=extra_context)


class AdvancedFilterAdmin(admin.ModelAdmin):
Expand All @@ -118,20 +117,20 @@ def save_model(self, request, new_object, *args, **kwargs):
if new_object and not new_object.pk:
new_object.created_by = request.user

super(AdvancedFilterAdmin, self).save_model(
super().save_model(
request, new_object, *args, **kwargs)

def change_view(self, request, object_id, form_url='', extra_context=None):
orig_response = super(AdvancedFilterAdmin, self).change_view(
orig_response = super().change_view(
request, object_id, form_url, extra_context)
if '_save_goto' in request.POST:
obj = self.get_object(request, unquote(object_id))
if obj:
app, model = obj.model.split('.')
path = resolve_url('admin:%s_%s_changelist' % (
path = resolve_url('admin:{}_{}_changelist'.format(
app, model.lower()))
url = "{path}{qparams}".format(
path=path, qparams="?_afilter={id}".format(id=object_id))
path=path, qparams=f"?_afilter={object_id}")
return HttpResponseRedirect(url)
return orig_response

Expand All @@ -142,18 +141,18 @@ def user_has_permission(user):

def get_queryset(self, request):
if self.user_has_permission(request.user):
return super(AdvancedFilterAdmin, self).get_queryset(request)
return super().get_queryset(request)
else:
return self.model.objects.filter_by_user(request.user)

def has_change_permission(self, request, obj=None):
if obj is None:
return super(AdvancedFilterAdmin, self).has_change_permission(request)
return super().has_change_permission(request)
return self.user_has_permission(request.user) or obj in self.model.objects.filter_by_user(request.user)

def has_delete_permission(self, request, obj=None):
if obj is None:
return super(AdvancedFilterAdmin, self).has_delete_permission(request)
return super().has_delete_permission(request)
return self.user_has_permission(request.user) or obj in self.model.objects.filter_by_user(request.user)


Expand Down
8 changes: 4 additions & 4 deletions advanced_filters/form_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def to_python(self, value):
>>> assert field.to_python('and,me') == '(and|me)'
>>> assert field.to_python('and,me;too') == '(and|me;too)'
"""
res = super(VaryingTypeCharField, self).to_python(value)
res = super().to_python(value)
split_res = res.split(self._default_separator)
if not res or len(split_res) < 2:
return res.strip()
Expand All @@ -40,7 +40,7 @@ def to_python(self, value):
return res


class CleanWhiteSpacesMixin(object):
class CleanWhiteSpacesMixin:
"""
This mixin, when added to any form subclass, adds a clean method which
strips repeating spaces in and around each string value of "clean_data".
Expand All @@ -55,9 +55,9 @@ def clean(self):
>>> assert form.is_valid()
>>> assert form.cleaned_data == {'some_field': 'a weird value'}
"""
cleaned_data = super(CleanWhiteSpacesMixin, self).clean()
cleaned_data = super().clean()
for k in self.cleaned_data:
if isinstance(self.cleaned_data[k], six.string_types):
if isinstance(self.cleaned_data[k], str):
cleaned_data[k] = re.sub(extra_spaces_pattern, ' ',
self.cleaned_data[k] or '').strip()
return cleaned_data
22 changes: 11 additions & 11 deletions advanced_filters/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from django.db.models.fields import DateField
from django.forms.formsets import formset_factory, BaseFormSet
from django.utils.functional import cached_property
from six.moves import range, reduce
from six.moves import reduce
from django.utils.text import capfirst
from django.utils.translation import gettext_lazy as _

Expand Down Expand Up @@ -76,7 +76,7 @@ def _build_field_choices(self, fields):
Iterate over passed model fields tuple and update initial choices.
"""
return tuple(sorted(
[(fquery, capfirst(fname)) for fquery, fname in fields.items()],
((fquery, capfirst(fname)) for fquery, fname in fields.items()),
key=lambda f: f[1].lower())
) + self.FIELD_CHOICES

Expand Down Expand Up @@ -158,7 +158,7 @@ def set_range_value(self, data):
data['value'] = (dtfrom, dtto)

def clean(self):
cleaned_data = super(AdvancedFilterQueryForm, self).clean()
cleaned_data = super().clean()
if cleaned_data.get('operator') == "range":
if ('value_from' in cleaned_data and
'value_to' in cleaned_data):
Expand All @@ -176,7 +176,7 @@ def make_query(self, *args, **kwargs):
return query

def __init__(self, model_fields={}, *args, **kwargs):
super(AdvancedFilterQueryForm, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.FIELD_CHOICES = self._build_field_choices(model_fields)
self.fields['field'].choices = self.FIELD_CHOICES
if not self.fields['field'].initial:
Expand All @@ -190,13 +190,13 @@ class AdvancedFilterFormSet(BaseFormSet):

def __init__(self, *args, **kwargs):
self.model_fields = kwargs.pop('model_fields', {})
super(AdvancedFilterFormSet, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
if self.forms:
form = self.forms[0]
self.fields = form.visible_fields()

def get_form_kwargs(self, index):
kwargs = super(AdvancedFilterFormSet, self).get_form_kwargs(index)
kwargs = super().get_form_kwargs(index)
kwargs['model_fields'] = self.model_fields
return kwargs

Expand Down Expand Up @@ -286,7 +286,7 @@ def __init__(self, *args, **kwargs):
self._filter_fields = filter_fields or getattr(
model_admin, 'advanced_filter_fields', ())

super(AdvancedFilterForm, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)

# populate existing or empty forms formset
data = None
Expand All @@ -297,15 +297,15 @@ def __init__(self, *args, **kwargs):
self.initialize_form(instance, self._model, data, extra_form)

def clean(self):
cleaned_data = super(AdvancedFilterForm, self).clean()
cleaned_data = super().clean()
if not self.fields_formset.is_valid():
logger.debug(
"Errors validating advanced query filters: %s",
pformat([(f.errors, f.non_field_errors())
for f in self.fields_formset.forms]))
raise forms.ValidationError("Error validating filter forms")
cleaned_data['model'] = "%s.%s" % (self._model._meta.app_label,
self._model._meta.object_name)
cleaned_data['model'] = "{}.{}".format(self._model._meta.app_label,
self._model._meta.object_name)
return cleaned_data

@property
Expand Down Expand Up @@ -356,4 +356,4 @@ def initialize_form(self, instance, model, data=None, extra=None):
def save(self, commit=True):
self.instance.query = self.generate_query()
self.instance.model = self.cleaned_data.get('model')
return super(AdvancedFilterForm, self).save(commit)
return super().save(commit)
2 changes: 0 additions & 2 deletions advanced_filters/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-03-07 23:02
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
Expand Down
3 changes: 0 additions & 3 deletions advanced_filters/migrations/0002_advancedfilter_created_at.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations


Expand Down
12 changes: 6 additions & 6 deletions advanced_filters/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import six


class CsrfExemptMixin(object):
class CsrfExemptMixin:
"""
Exempts the view from CSRF requirements.
NOTE:
Expand All @@ -31,10 +31,10 @@ class CsrfExemptMixin(object):

@method_decorator(csrf_exempt)
def dispatch(self, *args, **kwargs):
return super(CsrfExemptMixin, self).dispatch(*args, **kwargs)
return super().dispatch(*args, **kwargs)


class AccessMixin(object):
class AccessMixin:
"""
'Abstract' mixin that gives access mixins the same customizable
functionality.
Expand Down Expand Up @@ -104,11 +104,11 @@ def dispatch(self, request, *args, **kwargs):
if not request.user.is_staff:
return self.handle_no_permission(request)

return super(StaffuserRequiredMixin, self).dispatch(
return super().dispatch(
request, *args, **kwargs)


class JSONResponseMixin(object):
class JSONResponseMixin:
"""
A mixin that allows you to easily serialize simple data such as a dict or
Django models.
Expand All @@ -120,7 +120,7 @@ class JSONResponseMixin(object):
def get_content_type(self):
if (self.content_type is not None and
not isinstance(self.content_type,
(six.string_types, six.text_type))):
((str,), str))):
raise ImproperlyConfigured(
'{0} is missing a content type. Define {0}.content_type, '
'or override {0}.get_content_type().'.format(
Expand Down
2 changes: 1 addition & 1 deletion advanced_filters/q_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def dt2ts(obj):
return time.mktime(obj.timetuple()) if isinstance(obj, date) else obj


class QSerializer(object):
class QSerializer:
"""
A Q object serializer base class. Pass base64=True when initializing
to Base-64 encode/decode the returned/passed string.
Expand Down
2 changes: 1 addition & 1 deletion advanced_filters/tests/test_creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,6 @@ def test_create_form_valid(user, client, good_data, query):

created_filter = AdvancedFilter.objects.order_by("pk").last()
url = res["location"]
assert url.endswith("%s?_afilter=%s" % (URL_CLIENT_CHANGELIST, created_filter.pk))
assert url.endswith(f"{URL_CLIENT_CHANGELIST}?_afilter={created_filter.pk}")

assert list(created_filter.query.children[0]) == query
14 changes: 7 additions & 7 deletions advanced_filters/tests/test_forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,8 +219,8 @@ def setUp(self):
created_by=self.user)

def _create_query_form_data(self, form_number=0, data=None, **kwargs):
form_data = dict(('form-%d-%s' % (form_number, k), v)
for k, v in (data or self.formset_data).items())
form_data = {'form-%d-%s' % (form_number, k): v
for k, v in (data or self.formset_data).items()}
form_data.update(self.mgmg_form_data)
form_data.update(dict(title='baz filter'))
form_data.update(kwargs)
Expand All @@ -236,9 +236,9 @@ def test_failed_validation(self):
**self.default_error)
assert form.non_field_errors() == self.default_non_field_err
assert form.fields_formset.errors == [
{'operator': [u'This field is required.'],
'field': [u'This field is required.'],
'value': [u'This field is required.']}]
{'operator': ['This field is required.'],
'field': ['This field is required.'],
'value': ['This field is required.']}]

def test_invalid_field_validation(self):
form = AdvancedFilterForm(self._create_query_form_data(), instance=self.af,
Expand Down Expand Up @@ -279,7 +279,7 @@ def test_remove_existing_query(self):

class TestAdminInitialization(CommonFormTest):
def setUp(self):
super(TestAdminInitialization, self).setUp()
super().setUp()
self.fdata = self._create_query_form_data(form_number=0, data={
'field': 'groups__name', 'negate': False, 'operator': 'iexact',
'value': 'bar'})
Expand Down Expand Up @@ -323,7 +323,7 @@ def test_field_resolution(self):

def test_create_instance_with_modeladmin(self):
form = AdvancedFilterForm(data=self.fdata, model_admin=self.rep_model_admin)
assert form.is_valid(), 'errors: %s, %s' % (form.errors, form.fields_formset.errors)
assert form.is_valid(), f'errors: {form.errors}, {form.fields_formset.errors}'
instance = form.save(commit=False)
instance.created_by = self.user
assert isinstance(instance, AdvancedFilter)
Expand Down
2 changes: 1 addition & 1 deletion advanced_filters/tests/test_get_field_choices_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ def test_choices_no_date_fields_support(user, client, settings):
def test_choices_has_null(user, client, settings):
settings.ADVANCED_FILTERS_MAX_CHOICES = 4
named_users = ClientFactory.create_batch(2, assigned_to=user)
names = [None] + sorted(set([nu.first_name for nu in named_users]))
names = [None] + sorted({nu.first_name for nu in named_users})
assert len(named_users) == 2
ClientFactory.create_batch(2, assigned_to=user, first_name=None)
view_url = reverse(
Expand Down
4 changes: 2 additions & 2 deletions advanced_filters/tests/test_q_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
class QSerializerTest(TestCase):
correct_query = {
'children': [('test', 1234)],
'connector': u'AND',
'connector': 'AND',
'negated': False,
}

Expand All @@ -28,7 +28,7 @@ def test_jsondump_q(self):
def test_deserialize_q(self):
qres = self.s.deserialize({
'children': [('test', 1234)],
'connector': u'AND',
'connector': 'AND',
'negated': False,
'subtree_parents': []
})
Expand Down
6 changes: 3 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@ def get_full_description():
readme = 'README.rst'
changelog = 'CHANGELOG.rst'
base = os.path.dirname(__file__)
with io.open(os.path.join(base, readme), encoding='utf-8') as readme:
with open(os.path.join(base, readme), encoding='utf-8') as readme:
README = readme.read()
with io.open(os.path.join(base, changelog), encoding='utf-8') as changelog:
with open(os.path.join(base, changelog), encoding='utf-8') as changelog:
CHANGELOG = changelog.read()
return '%s\n%s' % (README, CHANGELOG)
return f'{README}\n{CHANGELOG}'


# allow setup.py to be run from any path
Expand Down
2 changes: 0 additions & 2 deletions tests/customers/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-03-13 22:23
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
Expand Down
2 changes: 1 addition & 1 deletion tests/factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class Meta:
@classmethod
def _prepare(cls, create, **kwargs):
password = kwargs.pop('password', None)
user = super(SalesRepFactory, cls)._prepare(create, **kwargs)
user = super()._prepare(create, **kwargs)
if password:
user.set_password(password)
if create:
Expand Down
2 changes: 0 additions & 2 deletions tests/reps/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-03-13 22:23
from __future__ import unicode_literals

import django.contrib.auth.models
import django.core.validators
Expand Down

0 comments on commit cc34677

Please sign in to comment.