| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from collections.abc import Callable, Iterable |
| 4 |
from typing import Any, cast |
| 5 |
|
| 6 |
from django.contrib.contenttypes.forms import ( |
| 7 |
BaseGenericInlineFormSet, |
| 8 |
generic_inlineformset_factory, |
| 9 |
) |
| 10 |
from django.contrib.contenttypes.models import ContentType |
| 11 |
from django.db import models |
| 12 |
from django.forms.models import ModelForm |
| 13 |
|
| 14 |
from .models import ( |
| 15 |
BasePolymorphicModelFormSet, |
| 16 |
PolymorphicFormSetChild, |
| 17 |
polymorphic_child_forms_factory, |
| 18 |
) |
| 19 |
|
| 20 |
|
| 21 |
class GenericPolymorphicFormSetChild(PolymorphicFormSetChild): |
| 22 |
""" |
| 23 |
Formset child for generic inlines |
| 24 |
""" |
| 25 |
|
| 26 |
ct_field: str |
| 27 |
fk_field: str |
| 28 |
|
| 29 |
def __init__( |
| 30 |
self, |
| 31 |
*args: Any, |
| 32 |
ct_field: str = "content_type", |
| 33 |
fk_field: str = "object_id", |
| 34 |
**kwargs: Any, |
| 35 |
) -> None: |
| 36 |
self.ct_field = ct_field |
| 37 |
self.fk_field = fk_field |
| 38 |
super().__init__(*args, **kwargs) |
| 39 |
|
| 40 |
def get_form( |
| 41 |
self, ct_field: str = "content_type", fk_field: str = "object_id", **kwargs: Any |
| 42 |
) -> type[ModelForm[Any]]: |
| 43 |
""" |
| 44 |
Construct the form class for the formset child. |
| 45 |
""" |
| 46 |
exclude = list(self.exclude) |
| 47 |
extra_exclude = kwargs.pop("extra_exclude", None) |
| 48 |
if extra_exclude: |
| 49 |
exclude += list(extra_exclude) |
| 50 |
|
| 51 |
# Make sure the GFK fields are excluded by default |
| 52 |
# This is similar to what generic_inlineformset_factory() does |
| 53 |
# if there is no field called `ct_field` let the exception propagate |
| 54 |
opts = self.model._meta |
| 55 |
ct_field_obj = opts.get_field(self.ct_field) |
| 56 |
|
| 57 |
if ( |
| 58 |
not isinstance(ct_field_obj, models.ForeignKey) |
| 59 |
or ct_field_obj.remote_field.model != ContentType |
| 60 |
): |
| 61 |
raise Exception(f"fk_name '{ct_field_obj}' is not a ForeignKey to ContentType") |
| 62 |
|
| 63 |
fk_field_obj = opts.get_field(self.fk_field) # let the exception propagate |
| 64 |
exclude.extend([ct_field_obj.name, fk_field_obj.name]) |
| 65 |
kwargs["exclude"] = exclude |
| 66 |
|
| 67 |
return super().get_form(**kwargs) |
| 68 |
|
| 69 |
|
| 70 |
class BaseGenericPolymorphicInlineFormSet(BaseGenericInlineFormSet, BasePolymorphicModelFormSet): |
| 71 |
""" |
| 72 |
Polymorphic formset variation for inline generic formsets |
| 73 |
""" |
| 74 |
|
| 75 |
|
| 76 |
def generic_polymorphic_inlineformset_factory( |
| 77 |
model: type[models.Model], |
| 78 |
formset_children: Iterable[PolymorphicFormSetChild], |
| 79 |
form: type[ModelForm[Any]] = ModelForm, |
| 80 |
formset: type[BaseGenericPolymorphicInlineFormSet] = BaseGenericPolymorphicInlineFormSet, |
| 81 |
ct_field: str = "content_type", |
| 82 |
fk_field: str = "object_id", |
| 83 |
# Base form |
| 84 |
# TODO: should these fields be removed in favor of creating |
| 85 |
# the base form as a formset child too? |
| 86 |
fields: list[str] | None = None, |
| 87 |
exclude: list[str] | None = None, |
| 88 |
extra: int = 1, |
| 89 |
can_order: bool = False, |
| 90 |
can_delete: bool = True, |
| 91 |
max_num: int | None = None, |
| 92 |
formfield_callback: Callable[..., Any] | None = None, |
| 93 |
validate_max: bool = False, |
| 94 |
for_concrete_model: bool = True, |
| 95 |
min_num: int | None = None, |
| 96 |
validate_min: bool = False, |
| 97 |
child_form_kwargs: dict[str, Any] | None = None, |
| 98 |
) -> type[BaseGenericPolymorphicInlineFormSet]: |
| 99 |
""" |
| 100 |
Construct the class for a generic inline polymorphic formset. |
| 101 |
|
| 102 |
All arguments are identical to :func:`~django.contrib.contenttypes.forms.generic_inlineformset_factory`, |
| 103 |
with the exception of the ``formset_children`` argument. |
| 104 |
|
| 105 |
:param formset_children: A list of all child :class:`PolymorphicFormSetChild` objects |
| 106 |
that tell the inline how to render the child model types. |
| 107 |
:type formset_children: Iterable[PolymorphicFormSetChild] |
| 108 |
:rtype: type |
| 109 |
""" |
| 110 |
kwargs = { |
| 111 |
"model": model, |
| 112 |
"form": form, |
| 113 |
"formfield_callback": formfield_callback, |
| 114 |
"formset": formset, |
| 115 |
"ct_field": ct_field, |
| 116 |
"fk_field": fk_field, |
| 117 |
"extra": extra, |
| 118 |
"can_delete": can_delete, |
| 119 |
"can_order": can_order, |
| 120 |
"fields": fields, |
| 121 |
"exclude": exclude, |
| 122 |
"min_num": min_num, |
| 123 |
"max_num": max_num, |
| 124 |
"validate_min": validate_min, |
| 125 |
"validate_max": validate_max, |
| 126 |
"for_concrete_model": for_concrete_model, |
| 127 |
# 'localized_fields': localized_fields, |
| 128 |
# 'labels': labels, |
| 129 |
# 'help_texts': help_texts, |
| 130 |
# 'error_messages': error_messages, |
| 131 |
# 'field_classes': field_classes, |
| 132 |
} |
| 133 |
if child_form_kwargs is None: |
| 134 |
child_form_kwargs = {} |
| 135 |
|
| 136 |
child_kwargs = { |
| 137 |
# 'exclude': exclude, |
| 138 |
"ct_field": ct_field, |
| 139 |
"fk_field": fk_field, |
| 140 |
} |
| 141 |
if child_form_kwargs: |
| 142 |
child_kwargs.update(child_form_kwargs) |
| 143 |
|
| 144 |
FormSet = generic_inlineformset_factory(**kwargs) # type: ignore[arg-type] |
| 145 |
FormSet.child_forms = polymorphic_child_forms_factory(formset_children, **child_kwargs) # type: ignore[attr-defined] |
| 146 |
return cast(type[BaseGenericPolymorphicInlineFormSet], FormSet) |