@@ -330,26 +330,24 @@ def manage_vpn_clients(cls, action, instance, pk_set, **kwargs):
330330 else :
331331 templates = pk_set
332332
333+ # Check if all templates in pk_set are required templates. If they are,
334+ # skip deletion of VpnClient objects at this point.
333335 if len (pk_set ) != templates .filter (required = True ).count ():
334336 # Explanation:
335- # The SortedManyToManyField clears all templates before adding new ones.
336- # This operation emits an m2m_changed signal with the "post_clear" action,
337- # which triggers the "enforce_required_templates" receiver to add
338- # required templates back .
337+ # SortedManyToManyField clears all existing templates before adding
338+ # new ones. This triggers an m2m_changed signal with the "post_clear"
339+ # action, which is handled by the "enforce_required_templates" signal
340+ # receiver. That receiver re-adds the required templates.
339341 #
340- # Adding required templates emits another m2m_changed signal with the
341- # "post_add" action, which executes this receiver . At this point , only
342- # required templates exist in the DB, hence we cannot decide which
343- # VpnClient objects to delete .
342+ # Re-adding required templates triggers another m2m_changed signal
343+ # with the "post_add" action. At this stage , only required templates
344+ # exist in the DB, so we cannot yet determine which VpnClient objects
345+ # should be deleted based on the new selection .
344346 #
345- # Therefore, we don't delete any VpnClient objects at this point
346- # that are not associated with the current templates. The receiver
347- # will be called again with the "post_add" action when all the templates
348- # are added back, including the required ones. And then, it will
349- # delete any VpnClient objects that are not associated with the
350- # current templates.
351-
352- # Delete VPN clients that are not associated with current templates
347+ # Therefore, we defer deletion of VpnClient objects until the "post_add"
348+ # signal is triggered again—after all templates, including the required
349+ # ones, have been fully added. At that point, we can identify and
350+ # delete VpnClient objects not linked to the final template set.
353351 instance .vpnclient_set .exclude (
354352 template_id__in = instance .templates .values_list ("id" , flat = True )
355353 ).delete ()
0 commit comments