@@ -368,22 +368,44 @@ def get_form(self, model):
368368 "Meta" : meta ,
369369 "__module__" : "database.forms" ,
370370 "_errors" : None ,
371+ "custom_fields" : {},
372+ "custom_field_groups" : {},
371373 }
372374
373- for field in self .object .custom_object_type .fields .all ():
375+ for field in self .object .custom_object_type .fields .all (). order_by ( 'group_name' , 'weight' , 'name' ) :
374376 field_type = field_types .FIELD_TYPE_CLASS [field .type ]()
375377 try :
376- attrs [field .name ] = field_type .get_annotated_form_field (field )
378+ field_name = field .name
379+ attrs [field_name ] = field_type .get_annotated_form_field (field )
380+
381+ # Annotate the field in the list of CustomField form fields
382+ attrs ["custom_fields" ][field_name ] = field
383+
384+ # Group fields by group_name (similar to NetBox custom fields)
385+ group_name = field .group_name or None # Use None for ungrouped fields
386+ if group_name not in attrs ["custom_field_groups" ]:
387+ attrs ["custom_field_groups" ][group_name ] = []
388+ attrs ["custom_field_groups" ][group_name ].append (field_name )
389+
377390 except NotImplementedError :
378391 print (f"get_form: { field .name } field is not supported" )
379392
380- form = type (
393+ # Create a custom __init__ method to set instance attributes
394+ def custom_init (self , * args , ** kwargs ):
395+ super (form_class , self ).__init__ (* args , ** kwargs )
396+ # Set the grouping info as instance attributes from the outer scope
397+ self .custom_fields = attrs ["custom_fields" ]
398+ self .custom_field_groups = attrs ["custom_field_groups" ]
399+
400+ attrs ["__init__" ] = custom_init
401+
402+ form_class = type (
381403 f"{ model ._meta .object_name } Form" ,
382404 (forms .NetBoxModelForm ,),
383405 attrs ,
384406 )
385407
386- return form
408+ return form_class
387409
388410
389411@register_model_view (CustomObject , "delete" )
0 commit comments