@@ -90,14 +90,14 @@ def __new__(mcs, name, bases, attrs):
9090 class _CableForm (CableForm , metaclass = FormMetaclass ):
9191
9292 def __init__ (self , * args , initial = None , ** kwargs ):
93-
9493 initial = initial or {}
94+
9595 if a_type :
96- ct = ContentType .objects .get_for_model (a_type )
97- initial ['a_terminations_type' ] = f'{ ct .app_label } .{ ct .model } '
96+ a_ct = ContentType .objects .get_for_model (a_type )
97+ initial ['a_terminations_type' ] = f'{ a_ct .app_label } .{ a_ct .model } '
9898 if b_type :
99- ct = ContentType .objects .get_for_model (b_type )
100- initial ['b_terminations_type' ] = f'{ ct .app_label } .{ ct .model } '
99+ b_ct = ContentType .objects .get_for_model (b_type )
100+ initial ['b_terminations_type' ] = f'{ b_ct .app_label } .{ b_ct .model } '
101101
102102 # TODO: Temporary hack to work around list handling limitations with utils.normalize_querydict()
103103 for field_name in ('a_terminations' , 'b_terminations' ):
@@ -108,8 +108,17 @@ def __init__(self, *args, initial=None, **kwargs):
108108
109109 if self .instance and self .instance .pk :
110110 # Initialize A/B terminations when modifying an existing Cable instance
111- self .initial ['a_terminations' ] = self .instance .a_terminations
112- self .initial ['b_terminations' ] = self .instance .b_terminations
111+ if a_type and self .instance .a_terminations and a_ct == ContentType .objects .get_for_model (self .instance .a_terminations [0 ]):
112+ self .initial ['a_terminations' ] = self .instance .a_terminations
113+ if b_type and self .instance .b_terminations and b_ct == ContentType .objects .get_for_model (self .instance .b_terminations [0 ]):
114+ self .initial ['b_terminations' ] = self .instance .b_terminations
115+ else :
116+ # Need to clear terminations if swapped type - but need to do it only
117+ # if not from instance
118+ if a_type :
119+ initial .pop ('a_terminations' , None )
120+ if b_type :
121+ initial .pop ('b_terminations' , None )
113122
114123 def clean (self ):
115124 super ().clean ()
0 commit comments