Debian Codegraph @

src/polymorphic/formsets/models.py

raw
1 from __future__ import annotations
2
3 from collections import OrderedDict
4 from collections.abc import Callable, Iterable
5 from typing import Any, cast
6
7 from django import forms
8 from django.contrib.contenttypes.models import ContentType
9 from django.core.exceptions import ImproperlyConfigured, ValidationError
10 from django.db import models
11 from django.forms import BaseForm, Media
12 from django.forms.models import (
13 BaseInlineFormSet,
14 BaseModelFormSet,
15 ModelForm,
16 inlineformset_factory,
17 modelform_factory,
18 modelformset_factory,
19 )
20 from django.utils.functional import cached_property
21
22 from polymorphic.models import PolymorphicModel
23
24 from .utils import add_media
25
26
27 class UnsupportedChildType(LookupError):
28 pass
29
30
31 class PolymorphicFormSetChild:
32 """
33 Metadata to define the inline of a polymorphic child.
34 Provide this information in the :func:'polymorphic_inlineformset_factory' construction.
35 """
36
37 model: type[models.Model]
38 fields: list[str] | None
39 exclude: tuple[str, ...] | list[str]
40 formfield_callback: Callable[..., Any] | None
41 widgets: dict[str, Any] | None
42 localized_fields: list[str] | None
43 labels: dict[str, str] | None
44 help_texts: dict[str, str] | None
45 error_messages: dict[str, dict[str, str]] | None
46
47 def __init__(
48 self,
49 model: type[models.Model],
50 form: type[ModelForm[Any]] = ModelForm,
51 fields: list[str] | None = None,
52 exclude: tuple[str, ...] | list[str] | None = None,
53 formfield_callback: Callable[..., Any] | None = None,
54 widgets: dict[str, Any] | None = None,
55 localized_fields: list[str] | None = None,
56 labels: dict[str, str] | None = None,
57 help_texts: dict[str, str] | None = None,
58 error_messages: dict[str, dict[str, str]] | None = None,
59 ) -> None:
60 self.model = model
61
62 # Instead of initializing the form here right away,
63 # the settings are saved so get_form() can receive additional exclude kwargs.
64 # This is mostly needed for the generic inline formsets
65 self._form_base = form
66 self.fields = fields
67 # Normalize exclude=None to () to match Django's formset behavior
68 self.exclude = () if exclude is None else exclude
69 self.formfield_callback = formfield_callback
70 self.widgets = widgets
71 self.localized_fields = localized_fields
72 self.labels = labels
73 self.help_texts = help_texts
74 self.error_messages = error_messages
75
76 @cached_property
77 def content_type(self) -> ContentType:
78 """
79 Expose the ContentType that the child relates to.
80 This can be used for the ''polymorphic_ctype'' field.
81 """
82 return ContentType.objects.get_for_model(self.model, for_concrete_model=False)
83
84 def get_form(self, **kwargs: Any) -> type[ModelForm[Any]]:
85 """
86 Construct the form class for the formset child.
87 """
88 # Do what modelformset_factory() / inlineformset_factory() does to the 'form' argument;
89 # Construct the form with the given ModelFormOptions values
90
91 # Fields can be overwritten. To support the global 'polymorphic_child_forms_factory' kwargs,
92 # that doesn't completely replace all 'exclude' settings defined per child type,
93 # we allow to define things like 'extra_...' fields that are amended to the current child settings.
94
95 # Handle exclude parameter carefully:
96 # - If exclude was explicitly provided (not empty), use it
97 # - If extra_exclude is provided, merge it with self.exclude
98 # - If neither was provided, don't pass exclude to modelform_factory at all,
99 # allowing the form's Meta.exclude to take effect
100 extra_exclude = kwargs.pop("extra_exclude", None)
101
102 # Determine if we should pass exclude to modelform_factory
103 # Treat empty tuples/lists the same as None to allow form's Meta.exclude to take effect
104 should_pass_exclude = bool(self.exclude) or extra_exclude is not None
105
106 if should_pass_exclude:
107 if self.exclude:
108 exclude = list(self.exclude)
109 else:
110 exclude = []
111
112 if extra_exclude:
113 exclude += list(extra_exclude)
114
115 defaults = {
116 "form": self._form_base,
117 "formfield_callback": self.formfield_callback,
118 "fields": self.fields,
119 # 'for_concrete_model': for_concrete_model,
120 "localized_fields": self.localized_fields,
121 "labels": self.labels,
122 "help_texts": self.help_texts,
123 "error_messages": self.error_messages,
124 "widgets": self.widgets,
125 # 'field_classes': field_classes,
126 }
127
128 # Only add exclude to defaults if we determined it should be passed
129 if should_pass_exclude:
130 defaults["exclude"] = exclude
131
132 defaults.update(kwargs)
133
134 return modelform_factory(self.model, **defaults) # type: ignore[arg-type]
135
136
137 def polymorphic_child_forms_factory(
138 formset_children: Iterable[PolymorphicFormSetChild], **kwargs: Any
139 ) -> dict[type[models.Model], type[ModelForm[Any]]]:
140 """
141 Construct the forms for the formset children.
142 This is mostly used internally, and rarely needs to be used by external projects.
143 When using the factory methods (:func:'polymorphic_inlineformset_factory'),
144 this feature is called already for you.
145 """
146 child_forms = OrderedDict()
147
148 for formset_child in formset_children:
149 child_forms[formset_child.model] = formset_child.get_form(**kwargs)
150
151 return child_forms
152
153
154 class BasePolymorphicModelFormSet(BaseModelFormSet):
155 """
156 A formset that can produce different forms depending on the object type.
157
158 Note that the 'add' feature is therefore more complex,
159 as all variations need ot be exposed somewhere.
160
161 When switching existing formsets to the polymorphic formset,
162 note that the ID field will no longer be named ''model_ptr'',
163 but just appear as ''id''.
164 """
165
166 # Assigned by the factory
167 child_forms: dict[type[models.Model], type[ModelForm[Any]]] = OrderedDict()
168 queryset_data: Any
169
170 def __init__(self, *args: Any, **kwargs: Any) -> None:
171 super().__init__(*args, **kwargs)
172 self.queryset_data = self.get_queryset()
173
174 def _construct_form(self, i: int, **kwargs: Any) -> BaseForm:
175 """
176 Create the form, depending on the model that's behind it.
177 """
178 # BaseModelFormSet logic
179 if self.is_bound and i < self.initial_form_count():
180 pk_key = f"{self.add_prefix(i)}-{self.model._meta.pk.name}" # type: ignore[union-attr]
181 pk = self.data[pk_key]
182 pk_field = self.model._meta.pk # type: ignore[union-attr]
183 to_python = self._get_to_python(pk_field) # type: ignore[attr-defined]
184 pk = to_python(pk)
185 kwargs["instance"] = self._existing_object(pk) # type: ignore[attr-defined]
186 if i < self.initial_form_count() and "instance" not in kwargs:
187 kwargs["instance"] = self.get_queryset()[i]
188 if i >= self.initial_form_count() and self.initial_extra:
189 # Set initial values for extra forms
190 try:
191 kwargs["initial"] = self.initial_extra[i - self.initial_form_count()]
192 except IndexError:
193 pass
194
195 # BaseFormSet logic, with custom formset_class
196 defaults: dict[str, Any] = {
197 "auto_id": self.auto_id,
198 "prefix": self.add_prefix(i),
199 "error_class": self.error_class,
200 }
201 if self.is_bound:
202 defaults["data"] = self.data
203 defaults["files"] = self.files
204 if self.initial and "initial" not in kwargs:
205 try:
206 defaults["initial"] = self.initial[i]
207 except IndexError:
208 pass
209 # Allow extra forms to be empty, unless they're part of
210 # the minimum forms.
211 if i >= self.initial_form_count() and i >= self.min_num:
212 defaults["empty_permitted"] = True
213 defaults["use_required_attribute"] = False
214 defaults.update(kwargs)
215
216 # Need to find the model that will be displayed in this form.
217 # Hence, peeking in the self.queryset_data beforehand.
218 model: type[models.Model] | None
219 if self.is_bound:
220 if "instance" in defaults and defaults["instance"] is not None:
221 # Object is already bound to a model, won't change the content type
222 model = cast(
223 PolymorphicModel, defaults["instance"]
224 ).get_real_instance_class() # allow proxy models
225 else:
226 # Extra or empty form, use the provided type.
227 # Note this completely tru
228 prefix = defaults["prefix"]
229 try:
230 ct_id = int(self.data[f"{prefix}-polymorphic_ctype"])
231 except (KeyError, ValueError):
232 raise ValidationError(
233 f"Formset row {prefix} has no 'polymorphic_ctype' defined!"
234 )
235
236 model = ContentType.objects.get_for_id(ct_id).model_class()
237 if model not in self.child_forms:
238 # Perform basic validation, as we skip the ChoiceField here.
239 raise UnsupportedChildType(
240 f"Child model type {model} is not part of the formset"
241 )
242 else:
243 if "instance" in defaults and defaults["instance"] is not None:
244 model = cast(
245 PolymorphicModel, defaults["instance"]
246 ).get_real_instance_class() # allow proxy models
247 elif "polymorphic_ctype" in cast(dict[str, Any], defaults.get("initial", {})):
248 ct_value = cast(dict[str, Any], defaults["initial"])["polymorphic_ctype"]
249 # Handle both ContentType instances and IDs
250 if isinstance(ct_value, ContentType):
251 model = ct_value.model_class()
252 else:
253 model = ContentType.objects.get_for_id(ct_value).model_class()
254 elif i < len(self.queryset_data):
255 model = self.queryset_data[i].__class__ # pragma: no cover
256 else:
257 # Extra forms, cycle between all types
258 # TODO: take the 'extra' value of each child formset into account.
259 total_known = len(self.queryset_data)
260 child_models = list(self.child_forms.keys())
261 model = child_models[(i - total_known) % len(child_models)]
262
263 # Normalize polymorphic_ctype in initial data if it's a ContentType instance
264 # This allows users to set initial[i]['polymorphic_ctype'] = ct (ContentType instance)
265 # while the form field expects an integer ID
266 # We do this AFTER determining the model so the model determination can use the ContentType
267 if "initial" in defaults and "polymorphic_ctype" in cast(
268 dict[str, Any], defaults["initial"]
269 ):
270 ct_value = cast(dict[str, Any], defaults["initial"])["polymorphic_ctype"]
271 if isinstance(ct_value, ContentType):
272 # Create a copy to avoid modifying the original formset.initial
273 defaults["initial"] = cast(dict[str, Any], defaults["initial"]).copy()
274 # Convert ContentType instance to its ID
275 cast(dict[str, Any], defaults["initial"])["polymorphic_ctype"] = ct_value.pk
276
277 assert model is not None, "Model must be determined before creating form"
278 form_class = self.get_form_class(model)
279 form = form_class(**defaults)
280 self.add_fields(form, i)
281 return form
282
283 def add_fields(self, form: BaseForm, index: int | None) -> None:
284 """Add a hidden field for the content type."""
285 ct = ContentType.objects.get_for_model(form._meta.model, for_concrete_model=False) # type: ignore[attr-defined]
286 choices = [(ct.pk, ct)] # Single choice, existing forms can't change the value.
287 form.fields["polymorphic_ctype"] = forms.TypedChoiceField(
288 choices=choices,
289 initial=ct.pk,
290 required=False,
291 widget=forms.HiddenInput,
292 coerce=int,
293 )
294 super().add_fields(form, index)
295
296 def get_form_class(self, model: type[models.Model]) -> type[ModelForm[Any]]:
297 """
298 Return the proper form class for the given model.
299 """
300 if not self.child_forms:
301 raise ImproperlyConfigured(f"No 'child_forms' defined in {self.__class__.__name__}")
302 if not issubclass(model, PolymorphicModel):
303 raise TypeError(f"Expect polymorphic model type, not {model}")
304
305 try:
306 return self.child_forms[model]
307 except KeyError:
308 # This may happen when the query returns objects of a type that was not handled by the formset.
309 raise UnsupportedChildType(
310 f"The '{self.__class__.__name__}' found a '{model.__name__}' model in the queryset, "
311 f"but no form class is registered to display it."
312 )
313
314 def is_multipart(self) -> bool:
315 """
316 Returns True if the formset needs to be multipart, i.e. it
317 has FileInput. Otherwise, False.
318 """
319 return any(f.is_multipart() for f in self.empty_forms)
320
321 @property
322 def media(self) -> Media:
323 # Include the media of all form types.
324 # The form media includes all form widget media
325 media = forms.Media()
326 for form in self.empty_forms:
327 add_media(media, form.media)
328 return media
329
330 @cached_property
331 def empty_forms(self) -> list[BaseForm]:
332 """
333 Return all possible empty forms
334 """
335 forms: list[BaseForm] = []
336 for _model, form_class in self.child_forms.items():
337 kwargs = self.get_form_kwargs(None)
338
339 form = form_class(
340 auto_id=self.auto_id,
341 prefix=self.add_prefix("__prefix__"),
342 empty_permitted=True,
343 use_required_attribute=False,
344 **kwargs,
345 )
346 self.add_fields(form, None)
347 forms.append(form)
348 return forms
349
350 @property
351 def empty_form(self) -> BaseForm:
352 # TODO: make an exception when can_add_base is defined?
353 raise RuntimeError(
354 "'empty_form' is not used in polymorphic formsets, use 'empty_forms' instead."
355 )
356
357
358 def polymorphic_modelformset_factory(
359 model: type[models.Model],
360 formset_children: Iterable[PolymorphicFormSetChild],
361 formset: type[BasePolymorphicModelFormSet] = BasePolymorphicModelFormSet,
362 # Base field
363 # TODO: should these fields be removed in favor of creating
364 # the base form as a formset child too?
365 form: type[ModelForm[Any]] = ModelForm,
366 fields: list[str] | None = None,
367 exclude: list[str] | None = None,
368 extra: int = 1,
369 can_order: bool = False,
370 can_delete: bool = True,
371 max_num: int | None = None,
372 formfield_callback: Callable[..., Any] | None = None,
373 widgets: dict[str, Any] | None = None,
374 validate_max: bool = False,
375 localized_fields: list[str] | None = None,
376 labels: dict[str, str] | None = None,
377 help_texts: dict[str, str] | None = None,
378 error_messages: dict[str, dict[str, str]] | None = None,
379 min_num: int | None = None,
380 validate_min: bool = False,
381 field_classes: dict[str, type[Any]] | None = None,
382 child_form_kwargs: dict[str, Any] | None = None,
383 ) -> type[BasePolymorphicModelFormSet]:
384 """
385 Construct the class for an polymorphic model formset.
386
387 All arguments are identical to :func:'~django.forms.models.modelformset_factory',
388 with the exception of the ''formset_children'' argument.
389
390 :param formset_children: A list of all child :class:'PolymorphicFormSetChild' objects
391 that tell the inline how to render the child model types.
392 :type formset_children: Iterable[PolymorphicFormSetChild]
393 :rtype: type
394 """
395 kwargs = {
396 "model": model,
397 "form": form,
398 "formfield_callback": formfield_callback,
399 "formset": formset,
400 "extra": extra,
401 "can_delete": can_delete,
402 "can_order": can_order,
403 "fields": fields,
404 "exclude": exclude,
405 "min_num": min_num,
406 "max_num": max_num,
407 "widgets": widgets,
408 "validate_min": validate_min,
409 "validate_max": validate_max,
410 "localized_fields": localized_fields,
411 "labels": labels,
412 "help_texts": help_texts,
413 "error_messages": error_messages,
414 "field_classes": field_classes,
415 }
416 FormSet = modelformset_factory(**kwargs) # type: ignore[arg-type]
417
418 child_kwargs = {
419 "fields": fields,
420 # 'exclude': exclude,
421 }
422 if child_form_kwargs:
423 child_kwargs.update(child_form_kwargs)
424
425 FormSet.child_forms = polymorphic_child_forms_factory(formset_children, **child_kwargs) # type: ignore[attr-defined]
426 return cast(type[BasePolymorphicModelFormSet], FormSet)
427
428
429 class BasePolymorphicInlineFormSet(BaseInlineFormSet, BasePolymorphicModelFormSet):
430 """
431 Polymorphic formset variation for inline formsets
432 """
433
434 def _construct_form(self, i: int, **kwargs: Any) -> BaseForm:
435 return super()._construct_form(i, **kwargs)
436
437
438 def polymorphic_inlineformset_factory(
439 parent_model: type[models.Model],
440 model: type[models.Model],
441 formset_children: Iterable[PolymorphicFormSetChild],
442 formset: type[BasePolymorphicInlineFormSet] = BasePolymorphicInlineFormSet,
443 fk_name: str | None = None,
444 # Base field
445 # TODO: should these fields be removed in favor of creating
446 # the base form as a formset child too?
447 form: type[ModelForm[Any]] = ModelForm,
448 fields: list[str] | None = None,
449 exclude: list[str] | None = None,
450 extra: int = 1,
451 can_order: bool = False,
452 can_delete: bool = True,
453 max_num: int | None = None,
454 formfield_callback: Callable[..., Any] | None = None,
455 widgets: dict[str, Any] | None = None,
456 validate_max: bool = False,
457 localized_fields: list[str] | None = None,
458 labels: dict[str, str] | None = None,
459 help_texts: dict[str, str] | None = None,
460 error_messages: dict[str, dict[str, str]] | None = None,
461 min_num: int | None = None,
462 validate_min: bool = False,
463 field_classes: dict[str, type[Any]] | None = None,
464 child_form_kwargs: dict[str, Any] | None = None,
465 ) -> type[BasePolymorphicInlineFormSet]:
466 """
467 Construct the class for an inline polymorphic formset.
468
469 All arguments are identical to :func:'~django.forms.models.inlineformset_factory',
470 with the exception of the ''formset_children'' argument.
471
472 :param formset_children: A list of all child :class:'PolymorphicFormSetChild' objects
473 that tell the inline how to render the child model types.
474 :type formset_children: Iterable[PolymorphicFormSetChild]
475 :rtype: type
476 """
477 kwargs = {
478 "parent_model": parent_model,
479 "model": model,
480 "form": form,
481 "formfield_callback": formfield_callback,
482 "formset": formset,
483 "fk_name": fk_name,
484 "extra": extra,
485 "can_delete": can_delete,
486 "can_order": can_order,
487 "fields": fields,
488 "exclude": exclude,
489 "min_num": min_num,
490 "max_num": max_num,
491 "widgets": widgets,
492 "validate_min": validate_min,
493 "validate_max": validate_max,
494 "localized_fields": localized_fields,
495 "labels": labels,
496 "help_texts": help_texts,
497 "error_messages": error_messages,
498 "field_classes": field_classes,
499 }
500 FormSet = inlineformset_factory(**kwargs) # type: ignore[arg-type]
501
502 child_kwargs = {
503 "fields": fields,
504 # 'exclude': exclude,
505 }
506 if child_form_kwargs:
507 child_kwargs.update(child_form_kwargs)
508
509 FormSet.child_forms = polymorphic_child_forms_factory(formset_children, **child_kwargs) # type: ignore[attr-defined]
510 return cast(type[BasePolymorphicInlineFormSet], FormSet)