Last active
September 3, 2024 22:06
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from utils import get_modelform_fields | |
from myapp.forms import MyModelForm | |
print(get_modelform_fields(MyModelForm)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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