customfields.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. from django.contrib.contenttypes.models import ContentType
  2. from extras.models import *
  3. __all__ = (
  4. 'CustomFieldsMixin',
  5. )
  6. class CustomFieldsMixin:
  7. """
  8. Extend a Form to include custom field support.
  9. Attributes:
  10. model: The model class
  11. """
  12. model = None
  13. def __init__(self, *args, **kwargs):
  14. self.custom_fields = {}
  15. super().__init__(*args, **kwargs)
  16. self._append_customfield_fields()
  17. def _get_content_type(self):
  18. """
  19. Return the ContentType of the form's model.
  20. """
  21. if not getattr(self, 'model', None):
  22. raise NotImplementedError(f"{self.__class__.__name__} must specify a model class.")
  23. return ContentType.objects.get_for_model(self.model)
  24. def _get_custom_fields(self, content_type):
  25. return CustomField.objects.filter(content_types=content_type)
  26. def _get_form_field(self, customfield):
  27. return customfield.to_form_field()
  28. def _append_customfield_fields(self):
  29. """
  30. Append form fields for all CustomFields assigned to this object type.
  31. """
  32. for customfield in self._get_custom_fields(self._get_content_type()):
  33. field_name = f'cf_{customfield.name}'
  34. self.fields[field_name] = self._get_form_field(customfield)
  35. # Annotate the field in the list of CustomField form fields
  36. self.custom_fields[field_name] = customfield