Skip to content

Commit 55aa88f

Browse files
committed
lint
1 parent 534648a commit 55aa88f

File tree

17 files changed

+405
-260
lines changed

17 files changed

+405
-260
lines changed

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ name = "pypi"
1818

1919
[tool.pdm.dev-dependencies]
2020
dev = [
21-
"black",
21+
"black>=24.8.0",
2222
"bump2version>=1.0.1",
2323
"check-manifest",
2424
"django",

src/concurrency/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
__author__ = 'sax'
1+
__author__ = "sax"
22

33
VERSION = __version__ = "2.5.0"
4-
NAME = 'django-concurrency'
4+
NAME = "django-concurrency"

src/concurrency/admin.py

Lines changed: 98 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,12 @@
1010
from django.db import transaction
1111
from django.db.models import Q
1212
from django.forms import CheckboxInput
13-
from django.forms.formsets import INITIAL_FORM_COUNT, ManagementForm, MAX_NUM_FORM_COUNT, TOTAL_FORM_COUNT
13+
from django.forms.formsets import (
14+
INITIAL_FORM_COUNT,
15+
ManagementForm,
16+
MAX_NUM_FORM_COUNT,
17+
TOTAL_FORM_COUNT,
18+
)
1419
from django.forms.models import BaseModelFormSet
1520
from django.http import HttpResponse, HttpResponseRedirect
1621
from django.utils.encoding import force_str
@@ -39,7 +44,9 @@ def action_checkbox(self, obj):
3944
if self.check_concurrent_action:
4045
attrs = {
4146
"class": "action-select",
42-
"aria-label": format_html(_("Select this object for an action - {}"), obj),
47+
"aria-label": format_html(
48+
_("Select this object for an action - {}"), obj
49+
),
4350
}
4451
checkbox = CheckboxInput(attrs, lambda value: False)
4552
pk = force_str("%s,%s" % (obj.pk, get_revision_of_object(obj)))
@@ -50,7 +57,9 @@ def action_checkbox(self, obj):
5057
else: # pragma: no cover
5158
return super().action_checkbox(obj)
5259

53-
action_checkbox.short_description = mark_safe('<input type="checkbox" id="action-toggle" />')
60+
action_checkbox.short_description = mark_safe(
61+
'<input type="checkbox" id="action-toggle" />'
62+
)
5463
action_checkbox.allow_tags = True
5564

5665
def get_confirmation_template(self):
@@ -66,7 +75,7 @@ def response_action(self, request, queryset): # noqa
6675
# and bottom of the change list, for example). Get the action
6776
# whose button was pushed.
6877
try:
69-
action_index = int(request.POST.get('index', 0))
78+
action_index = int(request.POST.get("index", 0))
7079
except ValueError: # pragma: no cover
7180
action_index = 0
7281

@@ -77,24 +86,24 @@ def response_action(self, request, queryset): # noqa
7786

7887
# Use the action whose button was pushed
7988
try:
80-
data.update({'action': data.getlist('action')[action_index]})
89+
data.update({"action": data.getlist("action")[action_index]})
8190
except IndexError: # pragma: no cover
8291
# If we didn't get an action from the chosen form that's invalid
8392
# POST data, so by deleting action it'll fail the validation check
8493
# below. So no need to do anything here
8594
pass
8695

8796
action_form = self.action_form(data, auto_id=None)
88-
action_form.fields['action'].choices = self.get_action_choices(request)
97+
action_form.fields["action"].choices = self.get_action_choices(request)
8998

9099
# If the form's valid we can handle the action.
91100
if action_form.is_valid():
92-
action = action_form.cleaned_data['action']
101+
action = action_form.cleaned_data["action"]
93102
func, name, description = self.get_actions(request)[action]
94103

95104
# Get the list of selected PKs. If nothing's selected, we can't
96105
# perform an action on it, so bail.
97-
if action_form.cleaned_data['select_across']:
106+
if action_form.cleaned_data["select_across"]:
98107
selected = ALL
99108
else:
100109
selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
@@ -105,7 +114,9 @@ def response_action(self, request, queryset): # noqa
105114
revision_field = self.model._concurrencymeta.field
106115

107116
if self.check_concurrent_action:
108-
self.delete_selected_confirmation_template = self.get_confirmation_template()
117+
self.delete_selected_confirmation_template = (
118+
self.get_confirmation_template()
119+
)
109120

110121
# If select_across we have to avoid the use of concurrency
111122
if selected is not ALL:
@@ -114,20 +125,27 @@ def response_action(self, request, queryset): # noqa
114125
try:
115126
pk, version = x.split(",")
116127
except ValueError: # pragma: no cover
117-
raise ImproperlyConfigured('`ConcurrencyActionMixin` error.'
118-
'A tuple with `primary_key, version_number` '
119-
'expected: `%s` found' % x)
120-
filters.append(Q(**{'pk': pk,
121-
revision_field.attname: version}))
128+
raise ImproperlyConfigured(
129+
"`ConcurrencyActionMixin` error."
130+
"A tuple with `primary_key, version_number` "
131+
"expected: `%s` found" % x
132+
)
133+
filters.append(Q(**{"pk": pk, revision_field.attname: version}))
122134

123135
queryset = queryset.filter(reduce(operator.or_, filters))
124136
if len(selected) != queryset.count():
125-
messages.error(request, 'One or more record were updated. '
126-
'(Probably by other user) '
127-
'The execution was aborted.')
137+
messages.error(
138+
request,
139+
"One or more record were updated. "
140+
"(Probably by other user) "
141+
"The execution was aborted.",
142+
)
128143
return HttpResponseRedirect(".")
129144
else:
130-
messages.warning(request, 'Selecting all records, you will avoid the concurrency check')
145+
messages.warning(
146+
request,
147+
"Selecting all records, you will avoid the concurrency check",
148+
)
131149

132150
response = func(self, request, queryset)
133151

@@ -142,13 +160,15 @@ def response_action(self, request, queryset): # noqa
142160

143161
class ConcurrentManagementForm(ManagementForm):
144162
def __init__(self, *args, **kwargs):
145-
self._versions = kwargs.pop('versions', [])
163+
self._versions = kwargs.pop("versions", [])
146164
super().__init__(*args, **kwargs)
147165

148166
def _get_concurrency_fields(self):
149167
v = []
150168
for pk, version in self._versions:
151-
v.append(f'<input type="hidden" name="{concurrency_param_name}_{pk}" value="{version}">')
169+
v.append(
170+
f'<input type="hidden" name="{concurrency_param_name}_{pk}" value="{version}">'
171+
)
152172
return mark_safe("".join(v))
153173

154174
def render(self, template_name=None, context=None, renderer=None):
@@ -163,27 +183,40 @@ def __str__(self):
163183

164184
__html__ = __str__
165185

166-
def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row):
167-
ret = super()._html_output(normal_row, error_row, row_ender, help_text_html, errors_on_separate_row)
186+
def _html_output(
187+
self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row
188+
):
189+
ret = super()._html_output(
190+
normal_row, error_row, row_ender, help_text_html, errors_on_separate_row
191+
)
168192
return mark_safe("{0}{1}".format(ret, self._get_concurrency_fields()))
169193

170194

171195
class ConcurrentBaseModelFormSet(BaseModelFormSet):
172196
def _management_form(self):
173197
"""Returns the ManagementForm instance for this FormSet."""
174198
if self.is_bound:
175-
form = ConcurrentManagementForm(self.data, auto_id=self.auto_id,
176-
prefix=self.prefix)
199+
form = ConcurrentManagementForm(
200+
self.data, auto_id=self.auto_id, prefix=self.prefix
201+
)
177202
if not form.is_valid():
178-
raise ValidationError('ManagementForm data is missing or has been tampered with')
203+
raise ValidationError(
204+
"ManagementForm data is missing or has been tampered with"
205+
)
179206
else:
180-
form = ConcurrentManagementForm(auto_id=self.auto_id,
181-
prefix=self.prefix,
182-
initial={TOTAL_FORM_COUNT: self.total_form_count(),
183-
INITIAL_FORM_COUNT: self.initial_form_count(),
184-
MAX_NUM_FORM_COUNT: self.max_num},
185-
versions=[(form.instance.pk, get_revision_of_object(form.instance)) for form
186-
in self.initial_forms])
207+
form = ConcurrentManagementForm(
208+
auto_id=self.auto_id,
209+
prefix=self.prefix,
210+
initial={
211+
TOTAL_FORM_COUNT: self.total_form_count(),
212+
INITIAL_FORM_COUNT: self.initial_form_count(),
213+
MAX_NUM_FORM_COUNT: self.max_num,
214+
},
215+
versions=[
216+
(form.instance.pk, get_revision_of_object(form.instance))
217+
for form in self.initial_forms
218+
],
219+
)
187220
return form
188221

189222
management_form = property(_management_form)
@@ -193,17 +226,17 @@ class ConcurrencyListEditableMixin:
193226
list_editable_policy = conf.POLICY
194227

195228
def get_changelist_formset(self, request, **kwargs):
196-
kwargs['formset'] = ConcurrentBaseModelFormSet
229+
kwargs["formset"] = ConcurrentBaseModelFormSet
197230
return super().get_changelist_formset(request, **kwargs)
198231

199232
def _add_conflict(self, request, obj):
200-
if hasattr(request, '_concurrency_list_editable_errors'):
233+
if hasattr(request, "_concurrency_list_editable_errors"):
201234
request._concurrency_list_editable_errors.append(obj.pk)
202235
else:
203236
request._concurrency_list_editable_errors = [obj.pk]
204237

205238
def _get_conflicts(self, request):
206-
if hasattr(request, '_concurrency_list_editable_errors'):
239+
if hasattr(request, "_concurrency_list_editable_errors"):
207240
return request._concurrency_list_editable_errors
208241
else:
209242
return []
@@ -212,7 +245,7 @@ def _get_conflicts(self, request):
212245
def save_model(self, request, obj, form, change):
213246
try:
214247
if change:
215-
version = request.POST.get(f'{concurrency_param_name}_{obj.pk}', None)
248+
version = request.POST.get(f"{concurrency_param_name}_{obj.pk}", None)
216249
if version:
217250
core._set_version(obj, version)
218251
super().save_model(request, obj, form, change)
@@ -248,33 +281,38 @@ def message_user(self, request, message, *args, **kwargs):
248281
m = rex.match(message)
249282
concurrency_errros = len(conflicts)
250283
if m:
251-
updated_record = int(m.group('num')) - concurrency_errros
284+
updated_record = int(m.group("num")) - concurrency_errros
252285

253286
ids = ",".join(map(str, conflicts))
254-
messages.error(request,
255-
ngettext("Record with pk `{0}` has been modified and was not updated",
256-
"Records `{0}` have been modified and were not updated",
257-
concurrency_errros).format(ids))
287+
messages.error(
288+
request,
289+
ngettext(
290+
"Record with pk `{0}` has been modified and was not updated",
291+
"Records `{0}` have been modified and were not updated",
292+
concurrency_errros,
293+
).format(ids),
294+
)
258295
if updated_record == 1:
259296
name = force_str(opts.verbose_name)
260297
else:
261298
name = force_str(opts.verbose_name_plural)
262299

263300
message = None
264301
if updated_record > 0:
265-
message = ngettext("%(count)s %(name)s was changed successfully.",
266-
"%(count)s %(name)s were changed successfully.",
267-
updated_record) % {'count': updated_record,
268-
'name': name}
302+
message = ngettext(
303+
"%(count)s %(name)s was changed successfully.",
304+
"%(count)s %(name)s were changed successfully.",
305+
updated_record,
306+
) % {"count": updated_record, "name": name}
269307

270308
return super().message_user(request, message, *args, **kwargs)
271309

272310

273-
class ConcurrentModelAdmin(ConcurrencyActionMixin,
274-
ConcurrencyListEditableMixin,
275-
admin.ModelAdmin):
311+
class ConcurrentModelAdmin(
312+
ConcurrencyActionMixin, ConcurrencyListEditableMixin, admin.ModelAdmin
313+
):
276314
form = ConcurrentForm
277-
formfield_overrides = {forms.VersionField: {'widget': VersionWidget}}
315+
formfield_overrides = {forms.VersionField: {"widget": VersionWidget}}
278316

279317
def check(self, **kwargs):
280318
errors = super().check(**kwargs)
@@ -283,23 +321,27 @@ def check(self, **kwargs):
283321
if version_field.name not in self.fields:
284322
errors.append(
285323
Error(
286-
'Missed version field in {} fields definition'.format(self),
287-
hint="Please add '{}' to the 'fields' attribute".format(version_field.name),
324+
"Missed version field in {} fields definition".format(self),
325+
hint="Please add '{}' to the 'fields' attribute".format(
326+
version_field.name
327+
),
288328
obj=None,
289-
id='concurrency.A001',
329+
id="concurrency.A001",
290330
)
291331
)
292332
if self.fieldsets:
293333
version_field = self.model._concurrencymeta.field
294-
fields = flatten([v['fields'] for k, v in self.fieldsets])
334+
fields = flatten([v["fields"] for k, v in self.fieldsets])
295335

296336
if version_field.name not in fields:
297337
errors.append(
298338
Error(
299-
'Missed version field in {} fieldsets definition'.format(self),
300-
hint="Please add '{}' to the 'fieldsets' attribute".format(version_field.name),
339+
"Missed version field in {} fieldsets definition".format(self),
340+
hint="Please add '{}' to the 'fieldsets' attribute".format(
341+
version_field.name
342+
),
301343
obj=None,
302-
id='concurrency.A002',
344+
id="concurrency.A002",
303345
)
304346
)
305347
return errors

0 commit comments

Comments
 (0)