@@ -368,22 +368,44 @@ def get_form(self, model):
368
368
"Meta" : meta ,
369
369
"__module__" : "database.forms" ,
370
370
"_errors" : None ,
371
+ "custom_fields" : {},
372
+ "custom_field_groups" : {},
371
373
}
372
374
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' ) :
374
376
field_type = field_types .FIELD_TYPE_CLASS [field .type ]()
375
377
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
+
377
390
except NotImplementedError :
378
391
print (f"get_form: { field .name } field is not supported" )
379
392
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 (
381
403
f"{ model ._meta .object_name } Form" ,
382
404
(forms .NetBoxModelForm ,),
383
405
attrs ,
384
406
)
385
407
386
- return form
408
+ return form_class
387
409
388
410
389
411
@register_model_view (CustomObject , "delete" )
0 commit comments