1+ from functools import cached_property
12from hashlib import md5
23
34from django .core .exceptions import ObjectDoesNotExist , PermissionDenied , ValidationError
1819 management_ip_changed ,
1920)
2021from ..validators import device_name_validator , mac_address_validator
22+ from ..whois .service import WHOISService
2123from .base import BaseModel
2224
2325
@@ -118,6 +120,11 @@ class Meta:
118120
119121 def __init__ (self , * args , ** kwargs ):
120122 super ().__init__ (* args , ** kwargs )
123+ # Initial value for last_ip is required in WHOIS
124+ # to remove WHOIS info related to that ip address.
125+ if app_settings .WHOIS_CONFIGURED :
126+ self ._changed_checked_fields .append ("last_ip" )
127+
121128 self ._set_initial_values_for_changed_checked_fields ()
122129
123130 def _set_initial_values_for_changed_checked_fields (self ):
@@ -279,6 +286,8 @@ def save(self, *args, **kwargs):
279286 self .key = self .generate_key (shared_secret )
280287 state_adding = self ._state .adding
281288 super ().save (* args , ** kwargs )
289+ if app_settings .WHOIS_CONFIGURED :
290+ self ._check_last_ip ()
282291 if state_adding and self .group and self .group .templates .exists ():
283292 self .create_default_config ()
284293 # The value of "self._state.adding" will always be "False"
@@ -299,7 +308,9 @@ def _check_changed_fields(self):
299308 self ._get_initial_values_for_checked_fields ()
300309 # Execute method for checked for each field in self._changed_checked_fields
301310 for field in self ._changed_checked_fields :
302- getattr (self , f"_check_{ field } _changed" )()
311+ method = getattr (self , f"_check_{ field } _changed" , None )
312+ if callable (method ):
313+ method ()
303314
304315 def _is_deferred (self , field ):
305316 """
@@ -490,3 +501,18 @@ def config_deactivated_clear_management_ip(cls, instance, *args, **kwargs):
490501 is changed to 'deactivated'.
491502 """
492503 cls .objects .filter (pk = instance .device_id ).update (management_ip = "" )
504+
505+ @cached_property
506+ def whois_service (self ):
507+ """
508+ Used as a shortcut to get WHOISService instance
509+ for the device.
510+ """
511+ return WHOISService (self )
512+
513+ def _check_last_ip (self ):
514+ """Trigger WHOIS lookup if last_ip is not deferred."""
515+ if self ._initial_last_ip == models .DEFERRED :
516+ return
517+ self .whois_service .trigger_whois_lookup ()
518+ self ._initial_last_ip = self .last_ip
0 commit comments