Skip to content

Instantly share code, notes, and snippets.

@archatas
Last active September 3, 2024 22:06
Show Gist options
  • Save archatas/8f3f354ed90d8890171cfa9289a0a6a6 to your computer and use it in GitHub Desktop.
Save archatas/8f3f354ed90d8890171cfa9289a0a6a6 to your computer and use it in GitHub Desktop.
Utility function to retrieve all the editable field names of a model form
from utils import get_modelform_fields
from myapp.forms import MyModelForm
print(get_modelform_fields(MyModelForm))
def get_modelform_fields(form_class):
"""
Get the list of editable fields for a ModelForm.
Args:
form_class (Type[ModelForm]): The ModelForm class (not an instance)
Returns:
list: A list of field names that would appear in the form
"""
# Get all model fields, excluding non-editable fields
model_fields = set(
field.name
for field in form_class._meta.model._meta.get_fields()
if not (field.auto_created) and getattr(field, "editable", True)
)
# Get explicitly excluded fields
excluded_fields = (
set(form_class._meta.exclude) if form_class._meta.exclude else set()
)
# Get fields that Django would automatically include
default_fields = set(form_class.base_fields.keys())
# Combine to get the final set of fields
form_fields = (model_fields - excluded_fields) | default_fields
return sorted(form_fields)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment