Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/django/forms/forms.py: 29%
246 statements
« prev ^ index » next coverage.py v7.0.5, created at 2023-01-17 06:13 +0000
« prev ^ index » next coverage.py v7.0.5, created at 2023-01-17 06:13 +0000
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:
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_div = "django/forms/div.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:
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:
112 self.use_required_attribute = use_required_attribute
114 if self.empty_permitted and self.use_required_attribute:
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:
123 if self.default_renderer is None:
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:
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 field = self.fields[name]
179 except KeyError:
180 raise KeyError(
181 "Key '%s' not found in '%s'. Choices are: %s."
182 % (
183 name,
184 self.__class__.__name__,
185 ", ".join(sorted(self.fields)),
186 )
187 )
188 if name not in self._bound_fields_cache:
189 self._bound_fields_cache[name] = field.get_bound_field(self, name)
190 return self._bound_fields_cache[name]
192 @property
193 def errors(self):
194 """Return an ErrorDict for the data provided for the form."""
195 if self._errors is None:
196 self.full_clean()
197 return self._errors
199 def is_valid(self):
200 """Return True if the form has no errors, or False otherwise."""
201 return self.is_bound and not self.errors
203 def add_prefix(self, field_name):
204 """
205 Return the field name with a prefix appended, if this Form has a
206 prefix set.
208 Subclasses may wish to override.
209 """
210 return "%s-%s" % (self.prefix, field_name) if self.prefix else field_name
212 def add_initial_prefix(self, field_name):
213 """Add an 'initial' prefix for checking dynamic initial values."""
214 return "initial-%s" % self.add_prefix(field_name)
216 def _widget_data_value(self, widget, html_name):
217 # value_from_datadict() gets the data from the data dictionaries.
218 # Each widget type knows how to retrieve its own data, because some
219 # widgets split data over several HTML fields.
220 return widget.value_from_datadict(self.data, self.files, html_name)
222 def _html_output(
223 self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row
224 ):
225 "Output HTML. Used by as_table(), as_ul(), as_p()."
226 warnings.warn(
227 "django.forms.BaseForm._html_output() is deprecated. "
228 "Please use .render() and .get_context() instead.",
229 RemovedInDjango50Warning,
230 stacklevel=2,
231 )
232 # Errors that should be displayed above all fields.
233 top_errors = self.non_field_errors().copy()
234 output, hidden_fields = [], []
236 for name, bf in self._bound_items():
237 field = bf.field
238 html_class_attr = ""
239 bf_errors = self.error_class(bf.errors)
240 if bf.is_hidden:
241 if bf_errors:
242 top_errors.extend(
243 [
244 _("(Hidden field %(name)s) %(error)s")
245 % {"name": name, "error": str(e)}
246 for e in bf_errors
247 ]
248 )
249 hidden_fields.append(str(bf))
250 else:
251 # Create a 'class="..."' attribute if the row should have any
252 # CSS classes applied.
253 css_classes = bf.css_classes()
254 if css_classes:
255 html_class_attr = ' class="%s"' % css_classes
257 if errors_on_separate_row and bf_errors:
258 output.append(error_row % str(bf_errors))
260 if bf.label:
261 label = conditional_escape(bf.label)
262 label = bf.label_tag(label) or ""
263 else:
264 label = ""
266 if field.help_text:
267 help_text = help_text_html % field.help_text
268 else:
269 help_text = ""
271 output.append(
272 normal_row
273 % {
274 "errors": bf_errors,
275 "label": label,
276 "field": bf,
277 "help_text": help_text,
278 "html_class_attr": html_class_attr,
279 "css_classes": css_classes,
280 "field_name": bf.html_name,
281 }
282 )
284 if top_errors:
285 output.insert(0, error_row % top_errors)
287 if hidden_fields: # Insert any hidden fields in the last row.
288 str_hidden = "".join(hidden_fields)
289 if output:
290 last_row = output[-1]
291 # Chop off the trailing row_ender (e.g. '</td></tr>') and
292 # insert the hidden fields.
293 if not last_row.endswith(row_ender):
294 # This can happen in the as_p() case (and possibly others
295 # that users write): if there are only top errors, we may
296 # not be able to conscript the last row for our purposes,
297 # so insert a new, empty row.
298 last_row = normal_row % {
299 "errors": "",
300 "label": "",
301 "field": "",
302 "help_text": "",
303 "html_class_attr": html_class_attr,
304 "css_classes": "",
305 "field_name": "",
306 }
307 output.append(last_row)
308 output[-1] = last_row[: -len(row_ender)] + str_hidden + row_ender
309 else:
310 # If there aren't any rows in the output, just append the
311 # hidden fields.
312 output.append(str_hidden)
313 return mark_safe("\n".join(output))
315 @property
316 def template_name(self):
317 return self.renderer.form_template_name
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.
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():
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):
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):
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:
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 += 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.