10
10
from django .db import transaction
11
11
from django .db .models import Q
12
12
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
+ MAX_NUM_FORM_COUNT ,
16
+ TOTAL_FORM_COUNT ,
17
+ ManagementForm ,
18
+ )
14
19
from django .forms .models import BaseModelFormSet
15
20
from django .http import HttpResponse , HttpResponseRedirect
16
21
from django .utils .encoding import force_str
17
22
from django .utils .html import format_html
18
23
from django .utils .safestring import mark_safe
19
- from django .utils .translation import gettext_lazy as _ , ngettext
24
+ from django .utils .translation import gettext_lazy as _
25
+ from django .utils .translation import ngettext
20
26
21
27
from concurrency import core , forms
22
28
from concurrency .api import get_revision_of_object
@@ -66,7 +72,7 @@ def response_action(self, request, queryset): # noqa
66
72
# and bottom of the change list, for example). Get the action
67
73
# whose button was pushed.
68
74
try :
69
- action_index = int (request .POST .get (' index' , 0 ))
75
+ action_index = int (request .POST .get (" index" , 0 ))
70
76
except ValueError : # pragma: no cover
71
77
action_index = 0
72
78
@@ -77,24 +83,24 @@ def response_action(self, request, queryset): # noqa
77
83
78
84
# Use the action whose button was pushed
79
85
try :
80
- data .update ({' action' : data .getlist (' action' )[action_index ]})
86
+ data .update ({" action" : data .getlist (" action" )[action_index ]})
81
87
except IndexError : # pragma: no cover
82
88
# If we didn't get an action from the chosen form that's invalid
83
89
# POST data, so by deleting action it'll fail the validation check
84
90
# below. So no need to do anything here
85
91
pass
86
92
87
93
action_form = self .action_form (data , auto_id = None )
88
- action_form .fields [' action' ].choices = self .get_action_choices (request )
94
+ action_form .fields [" action" ].choices = self .get_action_choices (request )
89
95
90
96
# If the form's valid we can handle the action.
91
97
if action_form .is_valid ():
92
- action = action_form .cleaned_data [' action' ]
98
+ action = action_form .cleaned_data [" action" ]
93
99
func , name , description = self .get_actions (request )[action ]
94
100
95
101
# Get the list of selected PKs. If nothing's selected, we can't
96
102
# perform an action on it, so bail.
97
- if action_form .cleaned_data [' select_across' ]:
103
+ if action_form .cleaned_data [" select_across" ]:
98
104
selected = ALL
99
105
else :
100
106
selected = request .POST .getlist (helpers .ACTION_CHECKBOX_NAME )
@@ -114,20 +120,27 @@ def response_action(self, request, queryset): # noqa
114
120
try :
115
121
pk , version = x .split ("," )
116
122
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 }))
123
+ raise ImproperlyConfigured (
124
+ "`ConcurrencyActionMixin` error."
125
+ "A tuple with `primary_key, version_number` "
126
+ "expected: `%s` found" % x
127
+ )
128
+ filters .append (Q (** {"pk" : pk , revision_field .attname : version }))
122
129
123
130
queryset = queryset .filter (reduce (operator .or_ , filters ))
124
131
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.' )
132
+ messages .error (
133
+ request ,
134
+ "One or more record were updated. "
135
+ "(Probably by other user) "
136
+ "The execution was aborted." ,
137
+ )
128
138
return HttpResponseRedirect ("." )
129
139
else :
130
- messages .warning (request , 'Selecting all records, you will avoid the concurrency check' )
140
+ messages .warning (
141
+ request ,
142
+ "Selecting all records, you will avoid the concurrency check" ,
143
+ )
131
144
132
145
response = func (self , request , queryset )
133
146
@@ -142,7 +155,7 @@ def response_action(self, request, queryset): # noqa
142
155
143
156
class ConcurrentManagementForm (ManagementForm ):
144
157
def __init__ (self , * args , ** kwargs ):
145
- self ._versions = kwargs .pop (' versions' , [])
158
+ self ._versions = kwargs .pop (" versions" , [])
146
159
super ().__init__ (* args , ** kwargs )
147
160
148
161
def _get_concurrency_fields (self ):
@@ -172,18 +185,20 @@ class ConcurrentBaseModelFormSet(BaseModelFormSet):
172
185
def _management_form (self ):
173
186
"""Returns the ManagementForm instance for this FormSet."""
174
187
if self .is_bound :
175
- form = ConcurrentManagementForm (self .data , auto_id = self .auto_id ,
176
- prefix = self .prefix )
188
+ form = ConcurrentManagementForm (self .data , auto_id = self .auto_id , prefix = self .prefix )
177
189
if not form .is_valid ():
178
- raise ValidationError (' ManagementForm data is missing or has been tampered with' )
190
+ raise ValidationError (" ManagementForm data is missing or has been tampered with" )
179
191
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 ])
192
+ form = ConcurrentManagementForm (
193
+ auto_id = self .auto_id ,
194
+ prefix = self .prefix ,
195
+ initial = {
196
+ TOTAL_FORM_COUNT : self .total_form_count (),
197
+ INITIAL_FORM_COUNT : self .initial_form_count (),
198
+ MAX_NUM_FORM_COUNT : self .max_num ,
199
+ },
200
+ versions = [(form .instance .pk , get_revision_of_object (form .instance )) for form in self .initial_forms ],
201
+ )
187
202
return form
188
203
189
204
management_form = property (_management_form )
@@ -193,17 +208,17 @@ class ConcurrencyListEditableMixin:
193
208
list_editable_policy = conf .POLICY
194
209
195
210
def get_changelist_formset (self , request , ** kwargs ):
196
- kwargs [' formset' ] = ConcurrentBaseModelFormSet
211
+ kwargs [" formset" ] = ConcurrentBaseModelFormSet
197
212
return super ().get_changelist_formset (request , ** kwargs )
198
213
199
214
def _add_conflict (self , request , obj ):
200
- if hasattr (request , ' _concurrency_list_editable_errors' ):
215
+ if hasattr (request , " _concurrency_list_editable_errors" ):
201
216
request ._concurrency_list_editable_errors .append (obj .pk )
202
217
else :
203
218
request ._concurrency_list_editable_errors = [obj .pk ]
204
219
205
220
def _get_conflicts (self , request ):
206
- if hasattr (request , ' _concurrency_list_editable_errors' ):
221
+ if hasattr (request , " _concurrency_list_editable_errors" ):
207
222
return request ._concurrency_list_editable_errors
208
223
else :
209
224
return []
@@ -212,7 +227,7 @@ def _get_conflicts(self, request):
212
227
def save_model (self , request , obj , form , change ):
213
228
try :
214
229
if change :
215
- version = request .POST .get (f' { concurrency_param_name } _{ obj .pk } ' , None )
230
+ version = request .POST .get (f" { concurrency_param_name } _{ obj .pk } " , None )
216
231
if version :
217
232
core ._set_version (obj , version )
218
233
super ().save_model (request , obj , form , change )
@@ -248,33 +263,36 @@ def message_user(self, request, message, *args, **kwargs):
248
263
m = rex .match (message )
249
264
concurrency_errros = len (conflicts )
250
265
if m :
251
- updated_record = int (m .group (' num' )) - concurrency_errros
266
+ updated_record = int (m .group (" num" )) - concurrency_errros
252
267
253
268
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 ))
269
+ messages .error (
270
+ request ,
271
+ ngettext (
272
+ "Record with pk `{0}` has been modified and was not updated" ,
273
+ "Records `{0}` have been modified and were not updated" ,
274
+ concurrency_errros ,
275
+ ).format (ids ),
276
+ )
258
277
if updated_record == 1 :
259
278
name = force_str (opts .verbose_name )
260
279
else :
261
280
name = force_str (opts .verbose_name_plural )
262
281
263
282
message = None
264
283
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 }
284
+ message = ngettext (
285
+ "%(count)s %(name)s was changed successfully." ,
286
+ "%(count)s %(name)s were changed successfully." ,
287
+ updated_record ,
288
+ ) % {"count" : updated_record , "name" : name }
269
289
270
290
return super ().message_user (request , message , * args , ** kwargs )
271
291
272
292
273
- class ConcurrentModelAdmin (ConcurrencyActionMixin ,
274
- ConcurrencyListEditableMixin ,
275
- admin .ModelAdmin ):
293
+ class ConcurrentModelAdmin (ConcurrencyActionMixin , ConcurrencyListEditableMixin , admin .ModelAdmin ):
276
294
form = ConcurrentForm
277
- formfield_overrides = {forms .VersionField : {' widget' : VersionWidget }}
295
+ formfield_overrides = {forms .VersionField : {" widget" : VersionWidget }}
278
296
279
297
def check (self , ** kwargs ):
280
298
errors = super ().check (** kwargs )
@@ -283,23 +301,23 @@ def check(self, **kwargs):
283
301
if version_field .name not in self .fields :
284
302
errors .append (
285
303
Error (
286
- ' Missed version field in {} fields definition' .format (self ),
304
+ " Missed version field in {} fields definition" .format (self ),
287
305
hint = "Please add '{}' to the 'fields' attribute" .format (version_field .name ),
288
306
obj = None ,
289
- id = ' concurrency.A001' ,
307
+ id = " concurrency.A001" ,
290
308
)
291
309
)
292
310
if self .fieldsets :
293
311
version_field = self .model ._concurrencymeta .field
294
- fields = flatten ([v [' fields' ] for k , v in self .fieldsets ])
312
+ fields = flatten ([v [" fields" ] for k , v in self .fieldsets ])
295
313
296
314
if version_field .name not in fields :
297
315
errors .append (
298
316
Error (
299
- ' Missed version field in {} fieldsets definition' .format (self ),
317
+ " Missed version field in {} fieldsets definition" .format (self ),
300
318
hint = "Please add '{}' to the 'fieldsets' attribute" .format (version_field .name ),
301
319
obj = None ,
302
- id = ' concurrency.A002' ,
320
+ id = " concurrency.A002" ,
303
321
)
304
322
)
305
323
return errors
0 commit comments