Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/django/forms/forms.py: 44%
247 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
1"""
2Form classes
3"""
5import copy
6import datetime
7import warnings
9from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
10from django.forms.fields import Field, FileField
11from django.forms.utils import ErrorDict, ErrorList, RenderableFormMixin
12from django.forms.widgets import Media, MediaDefiningClass
13from django.utils.datastructures import MultiValueDict
14from django.utils.deprecation import RemovedInDjango50Warning
15from django.utils.functional import cached_property
16from django.utils.html import conditional_escape
17from django.utils.safestring import SafeString, mark_safe
18from django.utils.translation import gettext as _
20from .renderers import get_default_renderer
22__all__ = ("BaseForm", "Form")
25class DeclarativeFieldsMetaclass(MediaDefiningClass):
26 """Collect Fields declared on the base classes."""
28 def __new__(mcs, name, bases, attrs):
29 # Collect fields from current class and remove them from attrs.
30 attrs["declared_fields"] = {
31 key: attrs.pop(key)
32 for key, value in list(attrs.items())
33 if isinstance(value, Field)
34 }
36 new_class = super().__new__(mcs, name, bases, attrs)
38 # Walk through the MRO.
39 declared_fields = {}
40 for base in reversed(new_class.__mro__):
41 # Collect fields from base class.
42 if hasattr(base, "declared_fields"):
43 declared_fields.update(base.declared_fields)
45 # Field shadowing.
46 for attr, value in base.__dict__.items():
47 if value is None and attr in declared_fields: 47 ↛ 48line 47 didn't jump to line 48, because the condition on line 47 was never true
48 declared_fields.pop(attr)
50 new_class.base_fields = declared_fields
51 new_class.declared_fields = declared_fields
53 return new_class
56class BaseForm(RenderableFormMixin):
57 """
58 The main implementation of all the Form logic. Note that this class is
59 different than Form. See the comments by the Form class for more info. Any
60 improvements to the form API should be made to this class, not to the Form
61 class.
62 """
64 default_renderer = None
65 field_order = None
66 prefix = None
67 use_required_attribute = True
69 template_name = "django/forms/default.html"
70 template_name_p = "django/forms/p.html"
71 template_name_table = "django/forms/table.html"
72 template_name_ul = "django/forms/ul.html"
73 template_name_label = "django/forms/label.html"
75 def __init__(
76 self,
77 data=None,
78 files=None,
79 auto_id="id_%s",
80 prefix=None,
81 initial=None,
82 error_class=ErrorList,
83 label_suffix=None,
84 empty_permitted=False,
85 field_order=None,
86 use_required_attribute=None,
87 renderer=None,
88 ):
89 self.is_bound = data is not None or files is not None
90 self.data = MultiValueDict() if data is None else data
91 self.files = MultiValueDict() if files is None else files
92 self.auto_id = auto_id
93 if prefix is not None: 93 ↛ 94line 93 didn't jump to line 94, because the condition on line 93 was never true
94 self.prefix = prefix
95 self.initial = initial or {}
96 self.error_class = error_class
97 # Translators: This is the default suffix added to form field labels
98 self.label_suffix = label_suffix if label_suffix is not None else _(":")
99 self.empty_permitted = empty_permitted
100 self._errors = None # Stores the errors after clean() has been called.
102 # The base_fields class attribute is the *class-wide* definition of
103 # fields. Because a particular *instance* of the class might want to
104 # alter self.fields, we create self.fields here by copying base_fields.
105 # Instances should always modify self.fields; they should not modify
106 # self.base_fields.
107 self.fields = copy.deepcopy(self.base_fields)
108 self._bound_fields_cache = {}
109 self.order_fields(self.field_order if field_order is None else field_order)
111 if use_required_attribute is not None: 111 ↛ 112line 111 didn't jump to line 112, because the condition on line 111 was never true
112 self.use_required_attribute = use_required_attribute
114 if self.empty_permitted and self.use_required_attribute: 114 ↛ 115line 114 didn't jump to line 115, because the condition on line 114 was never true
115 raise ValueError(
116 "The empty_permitted and use_required_attribute arguments may "
117 "not both be True."
118 )
120 # Initialize form renderer. Use a global default if not specified
121 # either as an argument or as self.default_renderer.
122 if renderer is None: 122 ↛ 129line 122 didn't jump to line 129, because the condition on line 122 was never false
123 if self.default_renderer is None: 123 ↛ 126line 123 didn't jump to line 126, because the condition on line 123 was never false
124 renderer = get_default_renderer()
125 else:
126 renderer = self.default_renderer
127 if isinstance(self.default_renderer, type):
128 renderer = renderer()
129 self.renderer = renderer
131 def order_fields(self, field_order):
132 """
133 Rearrange the fields according to field_order.
135 field_order is a list of field names specifying the order. Append fields
136 not included in the list in the default order for backward compatibility
137 with subclasses not overriding field_order. If field_order is None,
138 keep all fields in the order defined in the class. Ignore unknown
139 fields in field_order to allow disabling fields in form subclasses
140 without redefining ordering.
141 """
142 if field_order is None: 142 ↛ 144line 142 didn't jump to line 144, because the condition on line 142 was never false
143 return
144 fields = {}
145 for key in field_order:
146 try:
147 fields[key] = self.fields.pop(key)
148 except KeyError: # ignore unknown fields
149 pass
150 fields.update(self.fields) # add remaining fields in original order
151 self.fields = fields
153 def __repr__(self):
154 if self._errors is None:
155 is_valid = "Unknown"
156 else:
157 is_valid = self.is_bound and not self._errors
158 return "<%(cls)s bound=%(bound)s, valid=%(valid)s, fields=(%(fields)s)>" % {
159 "cls": self.__class__.__name__,
160 "bound": self.is_bound,
161 "valid": is_valid,
162 "fields": ";".join(self.fields),
163 }
165 def _bound_items(self):
166 """Yield (name, bf) pairs, where bf is a BoundField object."""
167 for name in self.fields:
168 yield name, self[name]
170 def __iter__(self):
171 """Yield the form's fields as BoundField objects."""
172 for name in self.fields:
173 yield self[name]
175 def __getitem__(self, name):
176 """Return a BoundField with the given name."""
177 try:
178 return self._bound_fields_cache[name]
179 except KeyError:
180 pass
181 try:
182 field = self.fields[name]
183 except KeyError:
184 raise KeyError(
185 "Key '%s' not found in '%s'. Choices are: %s."
186 % (
187 name,
188 self.__class__.__name__,
189 ", ".join(sorted(self.fields)),
190 )
191 )
192 bound_field = field.get_bound_field(self, name)
193 self._bound_fields_cache[name] = bound_field
194 return bound_field
196 @property
197 def errors(self):
198 """Return an ErrorDict for the data provided for the form."""
199 if self._errors is None:
200 self.full_clean()
201 return self._errors
203 def is_valid(self):
204 """Return True if the form has no errors, or False otherwise."""
205 return self.is_bound and not self.errors
207 def add_prefix(self, field_name):
208 """
209 Return the field name with a prefix appended, if this Form has a
210 prefix set.
212 Subclasses may wish to override.
213 """
214 return "%s-%s" % (self.prefix, field_name) if self.prefix else field_name
216 def add_initial_prefix(self, field_name):
217 """Add an 'initial' prefix for checking dynamic initial values."""
218 return "initial-%s" % self.add_prefix(field_name)
220 def _widget_data_value(self, widget, html_name):
221 # value_from_datadict() gets the data from the data dictionaries.
222 # Each widget type knows how to retrieve its own data, because some
223 # widgets split data over several HTML fields.
224 return widget.value_from_datadict(self.data, self.files, html_name)
226 def _html_output(
227 self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row
228 ):
229 "Output HTML. Used by as_table(), as_ul(), as_p()."
230 warnings.warn(
231 "django.forms.BaseForm._html_output() is deprecated. "
232 "Please use .render() and .get_context() instead.",
233 RemovedInDjango50Warning,
234 stacklevel=2,
235 )
236 # Errors that should be displayed above all fields.
237 top_errors = self.non_field_errors().copy()
238 output, hidden_fields = [], []
240 for name, bf in self._bound_items():
241 field = bf.field
242 html_class_attr = ""
243 bf_errors = self.error_class(bf.errors)
244 if bf.is_hidden:
245 if bf_errors:
246 top_errors.extend(
247 [
248 _("(Hidden field %(name)s) %(error)s")
249 % {"name": name, "error": str(e)}
250 for e in bf_errors
251 ]
252 )
253 hidden_fields.append(str(bf))
254 else:
255 # Create a 'class="..."' attribute if the row should have any
256 # CSS classes applied.
257 css_classes = bf.css_classes()
258 if css_classes:
259 html_class_attr = ' class="%s"' % css_classes
261 if errors_on_separate_row and bf_errors:
262 output.append(error_row % str(bf_errors))
264 if bf.label:
265 label = conditional_escape(bf.label)
266 label = bf.label_tag(label) or ""
267 else:
268 label = ""
270 if field.help_text:
271 help_text = help_text_html % field.help_text
272 else:
273 help_text = ""
275 output.append(
276 normal_row
277 % {
278 "errors": bf_errors,
279 "label": label,
280 "field": bf,
281 "help_text": help_text,
282 "html_class_attr": html_class_attr,
283 "css_classes": css_classes,
284 "field_name": bf.html_name,
285 }
286 )
288 if top_errors:
289 output.insert(0, error_row % top_errors)
291 if hidden_fields: # Insert any hidden fields in the last row.
292 str_hidden = "".join(hidden_fields)
293 if output:
294 last_row = output[-1]
295 # Chop off the trailing row_ender (e.g. '</td></tr>') and
296 # insert the hidden fields.
297 if not last_row.endswith(row_ender):
298 # This can happen in the as_p() case (and possibly others
299 # that users write): if there are only top errors, we may
300 # not be able to conscript the last row for our purposes,
301 # so insert a new, empty row.
302 last_row = normal_row % {
303 "errors": "",
304 "label": "",
305 "field": "",
306 "help_text": "",
307 "html_class_attr": html_class_attr,
308 "css_classes": "",
309 "field_name": "",
310 }
311 output.append(last_row)
312 output[-1] = last_row[: -len(row_ender)] + str_hidden + row_ender
313 else:
314 # If there aren't any rows in the output, just append the
315 # hidden fields.
316 output.append(str_hidden)
317 return mark_safe("\n".join(output))
319 def get_context(self):
320 fields = []
321 hidden_fields = []
322 top_errors = self.non_field_errors().copy()
323 for name, bf in self._bound_items():
324 bf_errors = self.error_class(bf.errors, renderer=self.renderer)
325 if bf.is_hidden:
326 if bf_errors:
327 top_errors += [
328 _("(Hidden field %(name)s) %(error)s")
329 % {"name": name, "error": str(e)}
330 for e in bf_errors
331 ]
332 hidden_fields.append(bf)
333 else:
334 errors_str = str(bf_errors)
335 # RemovedInDjango50Warning.
336 if not isinstance(errors_str, SafeString):
337 warnings.warn(
338 f"Returning a plain string from "
339 f"{self.error_class.__name__} is deprecated. Please "
340 f"customize via the template system instead.",
341 RemovedInDjango50Warning,
342 )
343 errors_str = mark_safe(errors_str)
344 fields.append((bf, errors_str))
345 return {
346 "form": self,
347 "fields": fields,
348 "hidden_fields": hidden_fields,
349 "errors": top_errors,
350 }
352 def non_field_errors(self):
353 """
354 Return an ErrorList of errors that aren't associated with a particular
355 field -- i.e., from Form.clean(). Return an empty ErrorList if there
356 are none.
357 """
358 return self.errors.get(
359 NON_FIELD_ERRORS,
360 self.error_class(error_class="nonfield", renderer=self.renderer),
361 )
363 def add_error(self, field, error):
364 """
365 Update the content of `self._errors`.
367 The `field` argument is the name of the field to which the errors
368 should be added. If it's None, treat the errors as NON_FIELD_ERRORS.
370 The `error` argument can be a single error, a list of errors, or a
371 dictionary that maps field names to lists of errors. An "error" can be
372 either a simple string or an instance of ValidationError with its
373 message attribute set and a "list or dictionary" can be an actual
374 `list` or `dict` or an instance of ValidationError with its
375 `error_list` or `error_dict` attribute set.
377 If `error` is a dictionary, the `field` argument *must* be None and
378 errors will be added to the fields that correspond to the keys of the
379 dictionary.
380 """
381 if not isinstance(error, ValidationError):
382 # Normalize to ValidationError and let its constructor
383 # do the hard work of making sense of the input.
384 error = ValidationError(error)
386 if hasattr(error, "error_dict"):
387 if field is not None:
388 raise TypeError(
389 "The argument `field` must be `None` when the `error` "
390 "argument contains errors for multiple fields."
391 )
392 else:
393 error = error.error_dict
394 else:
395 error = {field or NON_FIELD_ERRORS: error.error_list}
397 for field, error_list in error.items():
398 if field not in self.errors:
399 if field != NON_FIELD_ERRORS and field not in self.fields:
400 raise ValueError(
401 "'%s' has no field named '%s'."
402 % (self.__class__.__name__, field)
403 )
404 if field == NON_FIELD_ERRORS:
405 self._errors[field] = self.error_class(
406 error_class="nonfield", renderer=self.renderer
407 )
408 else:
409 self._errors[field] = self.error_class(renderer=self.renderer)
410 self._errors[field].extend(error_list)
411 if field in self.cleaned_data:
412 del self.cleaned_data[field]
414 def has_error(self, field, code=None):
415 return field in self.errors and (
416 code is None
417 or any(error.code == code for error in self.errors.as_data()[field])
418 )
420 def full_clean(self):
421 """
422 Clean all of self.data and populate self._errors and self.cleaned_data.
423 """
424 self._errors = ErrorDict()
425 if not self.is_bound: # Stop further processing. 425 ↛ 426line 425 didn't jump to line 426, because the condition on line 425 was never true
426 return
427 self.cleaned_data = {}
428 # If the form is permitted to be empty, and none of the form data has
429 # changed from the initial data, short circuit any validation.
430 if self.empty_permitted and not self.has_changed(): 430 ↛ 431line 430 didn't jump to line 431, because the condition on line 430 was never true
431 return
433 self._clean_fields()
434 self._clean_form()
435 self._post_clean()
437 def _clean_fields(self):
438 for name, bf in self._bound_items():
439 field = bf.field
440 value = bf.initial if field.disabled else bf.data
441 try:
442 if isinstance(field, FileField): 442 ↛ 443line 442 didn't jump to line 443, because the condition on line 442 was never true
443 value = field.clean(value, bf.initial)
444 else:
445 value = field.clean(value)
446 self.cleaned_data[name] = value
447 if hasattr(self, "clean_%s" % name): 447 ↛ 448line 447 didn't jump to line 448, because the condition on line 447 was never true
448 value = getattr(self, "clean_%s" % name)()
449 self.cleaned_data[name] = value
450 except ValidationError as e:
451 self.add_error(name, e)
453 def _clean_form(self):
454 try:
455 cleaned_data = self.clean()
456 except ValidationError as e:
457 self.add_error(None, e)
458 else:
459 if cleaned_data is not None: 459 ↛ exitline 459 didn't return from function '_clean_form', because the condition on line 459 was never false
460 self.cleaned_data = cleaned_data
462 def _post_clean(self):
463 """
464 An internal hook for performing additional cleaning after form cleaning
465 is complete. Used for model validation in model forms.
466 """
467 pass
469 def clean(self):
470 """
471 Hook for doing any extra form-wide cleaning after Field.clean() has been
472 called on every field. Any ValidationError raised by this method will
473 not be associated with a particular field; it will have a special-case
474 association with the field named '__all__'.
475 """
476 return self.cleaned_data
478 def has_changed(self):
479 """Return True if data differs from initial."""
480 return bool(self.changed_data)
482 @cached_property
483 def changed_data(self):
484 return [name for name, bf in self._bound_items() if bf._has_changed()]
486 @property
487 def media(self):
488 """Return all media required to render the widgets on this form."""
489 media = Media()
490 for field in self.fields.values():
491 media = media + field.widget.media
492 return media
494 def is_multipart(self):
495 """
496 Return True if the form needs to be multipart-encoded, i.e. it has
497 FileInput, or False otherwise.
498 """
499 return any(field.widget.needs_multipart_form for field in self.fields.values())
501 def hidden_fields(self):
502 """
503 Return a list of all the BoundField objects that are hidden fields.
504 Useful for manual form layout in templates.
505 """
506 return [field for field in self if field.is_hidden]
508 def visible_fields(self):
509 """
510 Return a list of BoundField objects that aren't hidden fields.
511 The opposite of the hidden_fields() method.
512 """
513 return [field for field in self if not field.is_hidden]
515 def get_initial_for_field(self, field, field_name):
516 """
517 Return initial data for field on form. Use initial data from the form
518 or the field, in that order. Evaluate callable values.
519 """
520 value = self.initial.get(field_name, field.initial)
521 if callable(value):
522 value = value()
523 # If this is an auto-generated default date, nix the microseconds
524 # for standardized handling. See #22502.
525 if (
526 isinstance(value, (datetime.datetime, datetime.time))
527 and not field.widget.supports_microseconds
528 ):
529 value = value.replace(microsecond=0)
530 return value
533class Form(BaseForm, metaclass=DeclarativeFieldsMetaclass):
534 "A collection of Fields, plus their associated data."
535 # This is a separate class from BaseForm in order to abstract the way
536 # self.fields is specified. This class (Form) is the one that does the
537 # fancy metaclass stuff purely for the semantic sugar -- it allows one
538 # to define a form using declarative syntax.
539 # BaseForm itself has no way of designating self.fields.