Skip to content

Commit b48c8ae

Browse files
committed
Increase Ruff lint coverage, fix lint errors
1 parent 72df3d4 commit b48c8ae

File tree

11 files changed

+70
-65
lines changed

11 files changed

+70
-65
lines changed

ajax_select/fields.py

Lines changed: 11 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -100,15 +100,12 @@ def render(self, name, value, attrs=None, renderer=None, **_kwargs):
100100
objs = lookup.get_objects([value])
101101
try:
102102
obj = objs[0]
103-
except IndexError:
104-
raise Exception(f"{lookup} cannot find object:{value}")
103+
except IndexError as e:
104+
raise Exception(f"{lookup} cannot find object:{value}") from e
105105
current_repr = lookup.format_item_display(obj)
106106
initial = [current_repr, obj.pk]
107107

108-
if self.show_help_text:
109-
help_text = self.help_text
110-
else:
111-
help_text = ""
108+
help_text = self.help_text if self.show_help_text else ""
112109

113110
context = {
114111
"name": name,
@@ -153,7 +150,7 @@ def __init__(self, channel, *args, **kwargs):
153150
)
154151
widget_kwargs.update(kwargs.pop("widget_options", {}))
155152
kwargs["widget"] = AutoCompleteSelectWidget(**widget_kwargs)
156-
super().__init__(max_length=255, *args, **kwargs)
153+
super().__init__(*args, **kwargs, max_length=255)
157154

158155
def clean(self, value):
159156
if value:
@@ -222,20 +219,18 @@ def render(self, name, value, attrs=None, renderer=None, **_kwargs):
222219
lookup = registry.get(self.channel)
223220

224221
values = list(value)
225-
if all([isinstance(v, Model) for v in values]):
226-
objects = values
227-
else:
228-
objects = lookup.get_objects(values)
222+
objects = (
223+
values
224+
if all([isinstance(v, Model) for v in values])
225+
else lookup.get_objects(values)
226+
)
229227

230228
current_ids = pack_ids([obj.pk for obj in objects])
231229

232230
# text repr of currently selected items
233231
initial = [[lookup.format_item_display(obj), obj.pk] for obj in objects]
234232

235-
if self.show_help_text:
236-
help_text = self.help_text
237-
else:
238-
help_text = ""
233+
help_text = self.help_text if self.show_help_text else ""
239234

240235
context = {
241236
"name": name,
@@ -371,10 +366,7 @@ def render(self, name, value, attrs=None, renderer=None, **_kwargs):
371366
final_attrs.pop("required", None)
372367

373368
lookup = registry.get(self.channel)
374-
if self.show_help_text:
375-
help_text = self.help_text
376-
else:
377-
help_text = ""
369+
help_text = self.help_text if self.show_help_text else ""
378370

379371
context = {
380372
"current_repr": initial,

ajax_select/helpers.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -45,14 +45,14 @@ class TheForm(superclass):
4545
class Meta:
4646
exclude = []
4747

48-
setattr(Meta, 'model', model)
48+
Meta.model = model
4949
if hasattr(superclass, 'Meta'):
5050
if hasattr(superclass.Meta, 'fields'):
51-
setattr(Meta, 'fields', superclass.Meta.fields)
51+
Meta.fields = superclass.Meta.fields
5252
if hasattr(superclass.Meta, 'exclude'):
53-
setattr(Meta, 'exclude', superclass.Meta.exclude)
53+
Meta.exclude = superclass.Meta.exclude
5454
if hasattr(superclass.Meta, 'widgets'):
55-
setattr(Meta, 'widgets', superclass.Meta.widgets)
55+
Meta.widgets = superclass.Meta.widgets
5656

5757
for model_fieldname, channel in fieldlist.items():
5858
f = make_ajax_field(model, model_fieldname, channel, show_help_text)
@@ -83,9 +83,7 @@ def make_ajax_field(related_model, fieldname_on_model, channel, show_help_text=F
8383
Returns:
8484
(AutoCompleteField, AutoCompleteSelectField, AutoCompleteSelectMultipleField): field
8585
"""
86-
from ajax_select.fields import AutoCompleteField, \
87-
AutoCompleteSelectMultipleField, \
88-
AutoCompleteSelectField
86+
from ajax_select.fields import AutoCompleteField, AutoCompleteSelectField, AutoCompleteSelectMultipleField
8987

9088
field = related_model._meta.get_field(fieldname_on_model)
9189
if 'label' not in kwargs:

ajax_select/registry.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,17 @@ class LookupChannelRegistry:
1111
This includes any installed apps that contain lookup.py modules (django 1.7+)
1212
and any lookups that are explicitly declared in `settings.AJAX_LOOKUP_CHANNELS`
1313
"""
14+
1415
_registry = {}
1516

1617
def load_channels(self):
1718
"""
1819
Called when loading the application. Cannot be called a second time,
1920
(eg. for testing) as Django will not re-import and re-register anything.
2021
"""
21-
autodiscover_modules('lookups')
22+
autodiscover_modules("lookups")
2223

23-
if hasattr(settings, 'AJAX_LOOKUP_CHANNELS'):
24+
if hasattr(settings, "AJAX_LOOKUP_CHANNELS"):
2425
self.register(settings.AJAX_LOOKUP_CHANNELS)
2526

2627
def register(self, lookup_specs):
@@ -54,9 +55,10 @@ def get(self, channel):
5455

5556
try:
5657
lookup_spec = self._registry[channel]
57-
except KeyError:
58+
except KeyError as e:
5859
raise ImproperlyConfigured(
59-
f"No ajax_select LookupChannel named {channel!r} is registered.")
60+
f"No ajax_select LookupChannel named {channel!r} is registered."
61+
) from e
6062

6163
if (type(lookup_spec) is type) and issubclass(lookup_spec, LookupChannel):
6264
return lookup_spec()
@@ -68,12 +70,12 @@ def get(self, channel):
6870
elif isinstance(lookup_spec, dict):
6971
# 'channel' : dict(model='app.model', search_field='title' )
7072
# generate a simple channel dynamically
71-
return self.make_channel(lookup_spec['model'], lookup_spec['search_field'])
73+
return self.make_channel(lookup_spec["model"], lookup_spec["search_field"])
7274
elif isinstance(lookup_spec, tuple):
7375
# a tuple
7476
# 'channel' : ('app.module','LookupClass')
7577
# from app.module load LookupClass and instantiate
76-
lookup_module = __import__(lookup_spec[0], {}, {}, [''])
78+
lookup_module = __import__(lookup_spec[0], {}, {}, [""])
7779
lookup_class = getattr(lookup_module, lookup_spec[1])
7880
return lookup_class()
7981
else:
@@ -92,6 +94,7 @@ def make_channel(self, app_model, arg_search_field):
9294
LookupChannel
9395
"""
9496
from ajax_select import LookupChannel
97+
9598
app_label, model_name = app_model.split(".")
9699

97100
class MadeLookupChannel(LookupChannel):
@@ -127,7 +130,7 @@ def format_item(self):
127130

128131
def _wrapper(lookup_class):
129132
if not channel:
130-
raise ValueError('Lookup Channel must have a channel name')
133+
raise ValueError("Lookup Channel must have a channel name")
131134

132135
registry.register({channel: lookup_class})
133136

ajax_select/views.py

Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import json
2+
23
from django.http import HttpResponse
34
from django.utils.encoding import force_str
45

@@ -20,32 +21,36 @@ def ajax_lookup(request, channel):
2021
# in which case we'll support POST
2122
if request.method == "GET":
2223
# we could also insist on an ajax request
23-
if 'term' not in request.GET:
24-
return HttpResponse('')
25-
query = request.GET['term']
24+
if "term" not in request.GET:
25+
return HttpResponse("")
26+
query = request.GET["term"]
2627
else:
27-
if 'term' not in request.POST:
28-
return HttpResponse('') # suspicious
29-
query = request.POST['term']
28+
if "term" not in request.POST:
29+
return HttpResponse("") # suspicious
30+
query = request.POST["term"]
3031

3132
lookup = registry.get(channel)
32-
if hasattr(lookup, 'check_auth'):
33+
if hasattr(lookup, "check_auth"):
3334
lookup.check_auth(request)
3435

35-
if len(query) >= getattr(lookup, 'min_length', 1):
36-
instances = lookup.get_query(query, request)
37-
else:
38-
instances = []
39-
40-
results = json.dumps([
41-
{
42-
'pk': force_str(getattr(item, 'pk', None)),
43-
'value': lookup.get_result(item),
44-
'match': lookup.format_match(item),
45-
'repr': lookup.format_item_display(item)
46-
} for item in instances
47-
])
48-
49-
response = HttpResponse(results, content_type='application/json')
50-
response['Cache-Control'] = 'max-age=0, must-revalidate, no-store, no-cache;'
36+
instances = (
37+
lookup.get_query(query, request)
38+
if len(query) >= getattr(lookup, "min_length", 1)
39+
else []
40+
)
41+
42+
results = json.dumps(
43+
[
44+
{
45+
"pk": force_str(getattr(item, "pk", None)),
46+
"value": lookup.get_result(item),
47+
"match": lookup.format_match(item),
48+
"repr": lookup.format_item_display(item),
49+
}
50+
for item in instances
51+
]
52+
)
53+
54+
response = HttpResponse(results, content_type="application/json")
55+
response["Cache-Control"] = "max-age=0, must-revalidate, no-store, no-cache;"
5156
return response

example/example/admin.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
from django.contrib import admin
2-
from example.forms import ReleaseForm
3-
from example.models import Author, Book, Group, Label, Person, Release, Song
42

53
from ajax_select import make_ajax_form
64
from ajax_select.admin import AjaxSelectAdmin, AjaxSelectAdminStackedInline, AjaxSelectAdminTabularInline
5+
from example.forms import ReleaseForm
6+
from example.models import Author, Book, Group, Label, Person, Release, Song
77

88

99
@admin.register(Person)

example/example/forms.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from django.forms.models import ModelForm
2-
from example.models import Release
32

43
from ajax_select import make_ajax_field
4+
from example.models import Release
55

66

77
class ReleaseForm(ModelForm):

example/example/lookups.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33

44
import ajax_select
55
from ajax_select import LookupChannel
6-
76
from example.models import Group, Person, Song
87

98

pyproject.toml

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,19 @@ exclude = [
4040
ignore = []
4141
line-length = 120
4242
select = [
43-
"C9",
43+
# pycodestyle
4444
"E",
45+
# Pyflakes
4546
"F",
47+
# pyupgrade
48+
"UP",
49+
# flake8-bugbear
50+
"B",
51+
# flake8-simplify
52+
"SIM",
53+
# isort
54+
"I",
55+
"C9",
4656
"W",
4757
]
4858

tests/test_integration.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
from ajax_select import fields
1414
from tests.models import Author, Book, Person
1515

16-
1716
# --------------- setup ----------------------------------- #
1817

1918

tests/test_views.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from django.contrib.auth.models import User
2-
from django.test import Client
3-
from django.test import TestCase
2+
from django.test import Client, TestCase
43

54

65
class TestViews(TestCase):

0 commit comments

Comments
 (0)