You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

formsets.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. from django.core.exceptions import ValidationError
  2. from django.forms import Form
  3. from django.forms.fields import BooleanField, IntegerField
  4. from django.forms.utils import ErrorList
  5. from django.forms.widgets import HiddenInput
  6. from django.utils.functional import cached_property
  7. from django.utils.html import html_safe
  8. from django.utils.safestring import mark_safe
  9. from django.utils.translation import gettext as _, ngettext
  10. __all__ = ('BaseFormSet', 'formset_factory', 'all_valid')
  11. # special field names
  12. TOTAL_FORM_COUNT = 'TOTAL_FORMS'
  13. INITIAL_FORM_COUNT = 'INITIAL_FORMS'
  14. MIN_NUM_FORM_COUNT = 'MIN_NUM_FORMS'
  15. MAX_NUM_FORM_COUNT = 'MAX_NUM_FORMS'
  16. ORDERING_FIELD_NAME = 'ORDER'
  17. DELETION_FIELD_NAME = 'DELETE'
  18. # default minimum number of forms in a formset
  19. DEFAULT_MIN_NUM = 0
  20. # default maximum number of forms in a formset, to prevent memory exhaustion
  21. DEFAULT_MAX_NUM = 1000
  22. class ManagementForm(Form):
  23. """
  24. Keep track of how many form instances are displayed on the page. If adding
  25. new forms via JavaScript, you should increment the count field of this form
  26. as well.
  27. """
  28. def __init__(self, *args, **kwargs):
  29. self.base_fields[TOTAL_FORM_COUNT] = IntegerField(widget=HiddenInput)
  30. self.base_fields[INITIAL_FORM_COUNT] = IntegerField(widget=HiddenInput)
  31. # MIN_NUM_FORM_COUNT and MAX_NUM_FORM_COUNT are output with the rest of
  32. # the management form, but only for the convenience of client-side
  33. # code. The POST value of them returned from the client is not checked.
  34. self.base_fields[MIN_NUM_FORM_COUNT] = IntegerField(required=False, widget=HiddenInput)
  35. self.base_fields[MAX_NUM_FORM_COUNT] = IntegerField(required=False, widget=HiddenInput)
  36. super().__init__(*args, **kwargs)
  37. @html_safe
  38. class BaseFormSet:
  39. """
  40. A collection of instances of the same Form class.
  41. """
  42. def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
  43. initial=None, error_class=ErrorList, form_kwargs=None):
  44. self.is_bound = data is not None or files is not None
  45. self.prefix = prefix or self.get_default_prefix()
  46. self.auto_id = auto_id
  47. self.data = data or {}
  48. self.files = files or {}
  49. self.initial = initial
  50. self.form_kwargs = form_kwargs or {}
  51. self.error_class = error_class
  52. self._errors = None
  53. self._non_form_errors = None
  54. def __str__(self):
  55. return self.as_table()
  56. def __iter__(self):
  57. """Yield the forms in the order they should be rendered."""
  58. return iter(self.forms)
  59. def __getitem__(self, index):
  60. """Return the form at the given index, based on the rendering order."""
  61. return self.forms[index]
  62. def __len__(self):
  63. return len(self.forms)
  64. def __bool__(self):
  65. """
  66. Return True since all formsets have a management form which is not
  67. included in the length.
  68. """
  69. return True
  70. @cached_property
  71. def management_form(self):
  72. """Return the ManagementForm instance for this FormSet."""
  73. if self.is_bound:
  74. form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix)
  75. if not form.is_valid():
  76. raise ValidationError(
  77. _('ManagementForm data is missing or has been tampered with'),
  78. code='missing_management_form',
  79. )
  80. else:
  81. form = ManagementForm(auto_id=self.auto_id, prefix=self.prefix, initial={
  82. TOTAL_FORM_COUNT: self.total_form_count(),
  83. INITIAL_FORM_COUNT: self.initial_form_count(),
  84. MIN_NUM_FORM_COUNT: self.min_num,
  85. MAX_NUM_FORM_COUNT: self.max_num
  86. })
  87. return form
  88. def total_form_count(self):
  89. """Return the total number of forms in this FormSet."""
  90. if self.is_bound:
  91. # return absolute_max if it is lower than the actual total form
  92. # count in the data; this is DoS protection to prevent clients
  93. # from forcing the server to instantiate arbitrary numbers of
  94. # forms
  95. return min(self.management_form.cleaned_data[TOTAL_FORM_COUNT], self.absolute_max)
  96. else:
  97. initial_forms = self.initial_form_count()
  98. total_forms = max(initial_forms, self.min_num) + self.extra
  99. # Allow all existing related objects/inlines to be displayed,
  100. # but don't allow extra beyond max_num.
  101. if initial_forms > self.max_num >= 0:
  102. total_forms = initial_forms
  103. elif total_forms > self.max_num >= 0:
  104. total_forms = self.max_num
  105. return total_forms
  106. def initial_form_count(self):
  107. """Return the number of forms that are required in this FormSet."""
  108. if self.is_bound:
  109. return self.management_form.cleaned_data[INITIAL_FORM_COUNT]
  110. else:
  111. # Use the length of the initial data if it's there, 0 otherwise.
  112. initial_forms = len(self.initial) if self.initial else 0
  113. return initial_forms
  114. @cached_property
  115. def forms(self):
  116. """Instantiate forms at first property access."""
  117. # DoS protection is included in total_form_count()
  118. forms = [self._construct_form(i, **self.get_form_kwargs(i))
  119. for i in range(self.total_form_count())]
  120. return forms
  121. def get_form_kwargs(self, index):
  122. """
  123. Return additional keyword arguments for each individual formset form.
  124. index will be None if the form being constructed is a new empty
  125. form.
  126. """
  127. return self.form_kwargs.copy()
  128. def _construct_form(self, i, **kwargs):
  129. """Instantiate and return the i-th form instance in a formset."""
  130. defaults = {
  131. 'auto_id': self.auto_id,
  132. 'prefix': self.add_prefix(i),
  133. 'error_class': self.error_class,
  134. # Don't render the HTML 'required' attribute as it may cause
  135. # incorrect validation for extra, optional, and deleted
  136. # forms in the formset.
  137. 'use_required_attribute': False,
  138. }
  139. if self.is_bound:
  140. defaults['data'] = self.data
  141. defaults['files'] = self.files
  142. if self.initial and 'initial' not in kwargs:
  143. try:
  144. defaults['initial'] = self.initial[i]
  145. except IndexError:
  146. pass
  147. # Allow extra forms to be empty, unless they're part of
  148. # the minimum forms.
  149. if i >= self.initial_form_count() and i >= self.min_num:
  150. defaults['empty_permitted'] = True
  151. defaults.update(kwargs)
  152. form = self.form(**defaults)
  153. self.add_fields(form, i)
  154. return form
  155. @property
  156. def initial_forms(self):
  157. """Return a list of all the initial forms in this formset."""
  158. return self.forms[:self.initial_form_count()]
  159. @property
  160. def extra_forms(self):
  161. """Return a list of all the extra forms in this formset."""
  162. return self.forms[self.initial_form_count():]
  163. @property
  164. def empty_form(self):
  165. form = self.form(
  166. auto_id=self.auto_id,
  167. prefix=self.add_prefix('__prefix__'),
  168. empty_permitted=True,
  169. use_required_attribute=False,
  170. **self.get_form_kwargs(None)
  171. )
  172. self.add_fields(form, None)
  173. return form
  174. @property
  175. def cleaned_data(self):
  176. """
  177. Return a list of form.cleaned_data dicts for every form in self.forms.
  178. """
  179. if not self.is_valid():
  180. raise AttributeError("'%s' object has no attribute 'cleaned_data'" % self.__class__.__name__)
  181. return [form.cleaned_data for form in self.forms]
  182. @property
  183. def deleted_forms(self):
  184. """Return a list of forms that have been marked for deletion."""
  185. if not self.is_valid() or not self.can_delete:
  186. return []
  187. # construct _deleted_form_indexes which is just a list of form indexes
  188. # that have had their deletion widget set to True
  189. if not hasattr(self, '_deleted_form_indexes'):
  190. self._deleted_form_indexes = []
  191. for i in range(0, self.total_form_count()):
  192. form = self.forms[i]
  193. # if this is an extra form and hasn't changed, don't consider it
  194. if i >= self.initial_form_count() and not form.has_changed():
  195. continue
  196. if self._should_delete_form(form):
  197. self._deleted_form_indexes.append(i)
  198. return [self.forms[i] for i in self._deleted_form_indexes]
  199. @property
  200. def ordered_forms(self):
  201. """
  202. Return a list of form in the order specified by the incoming data.
  203. Raise an AttributeError if ordering is not allowed.
  204. """
  205. if not self.is_valid() or not self.can_order:
  206. raise AttributeError("'%s' object has no attribute 'ordered_forms'" % self.__class__.__name__)
  207. # Construct _ordering, which is a list of (form_index, order_field_value)
  208. # tuples. After constructing this list, we'll sort it by order_field_value
  209. # so we have a way to get to the form indexes in the order specified
  210. # by the form data.
  211. if not hasattr(self, '_ordering'):
  212. self._ordering = []
  213. for i in range(0, self.total_form_count()):
  214. form = self.forms[i]
  215. # if this is an extra form and hasn't changed, don't consider it
  216. if i >= self.initial_form_count() and not form.has_changed():
  217. continue
  218. # don't add data marked for deletion to self.ordered_data
  219. if self.can_delete and self._should_delete_form(form):
  220. continue
  221. self._ordering.append((i, form.cleaned_data[ORDERING_FIELD_NAME]))
  222. # After we're done populating self._ordering, sort it.
  223. # A sort function to order things numerically ascending, but
  224. # None should be sorted below anything else. Allowing None as
  225. # a comparison value makes it so we can leave ordering fields
  226. # blank.
  227. def compare_ordering_key(k):
  228. if k[1] is None:
  229. return (1, 0) # +infinity, larger than any number
  230. return (0, k[1])
  231. self._ordering.sort(key=compare_ordering_key)
  232. # Return a list of form.cleaned_data dicts in the order specified by
  233. # the form data.
  234. return [self.forms[i[0]] for i in self._ordering]
  235. @classmethod
  236. def get_default_prefix(cls):
  237. return 'form'
  238. def non_form_errors(self):
  239. """
  240. Return an ErrorList of errors that aren't associated with a particular
  241. form -- i.e., from formset.clean(). Return an empty ErrorList if there
  242. are none.
  243. """
  244. if self._non_form_errors is None:
  245. self.full_clean()
  246. return self._non_form_errors
  247. @property
  248. def errors(self):
  249. """Return a list of form.errors for every form in self.forms."""
  250. if self._errors is None:
  251. self.full_clean()
  252. return self._errors
  253. def total_error_count(self):
  254. """Return the number of errors across all forms in the formset."""
  255. return len(self.non_form_errors()) +\
  256. sum(len(form_errors) for form_errors in self.errors)
  257. def _should_delete_form(self, form):
  258. """Return whether or not the form was marked for deletion."""
  259. return form.cleaned_data.get(DELETION_FIELD_NAME, False)
  260. def is_valid(self):
  261. """Return True if every form in self.forms is valid."""
  262. if not self.is_bound:
  263. return False
  264. # We loop over every form.errors here rather than short circuiting on the
  265. # first failure to make sure validation gets triggered for every form.
  266. forms_valid = True
  267. # This triggers a full clean.
  268. self.errors
  269. for i in range(0, self.total_form_count()):
  270. form = self.forms[i]
  271. if self.can_delete and self._should_delete_form(form):
  272. # This form is going to be deleted so any of its errors
  273. # shouldn't cause the entire formset to be invalid.
  274. continue
  275. forms_valid &= form.is_valid()
  276. return forms_valid and not self.non_form_errors()
  277. def full_clean(self):
  278. """
  279. Clean all of self.data and populate self._errors and
  280. self._non_form_errors.
  281. """
  282. self._errors = []
  283. self._non_form_errors = self.error_class()
  284. empty_forms_count = 0
  285. if not self.is_bound: # Stop further processing.
  286. return
  287. for i in range(0, self.total_form_count()):
  288. form = self.forms[i]
  289. # Empty forms are unchanged forms beyond those with initial data.
  290. if not form.has_changed() and i >= self.initial_form_count():
  291. empty_forms_count += 1
  292. # Accessing errors calls full_clean() if necessary.
  293. # _should_delete_form() requires cleaned_data.
  294. form_errors = form.errors
  295. if self.can_delete and self._should_delete_form(form):
  296. continue
  297. self._errors.append(form_errors)
  298. try:
  299. if (self.validate_max and
  300. self.total_form_count() - len(self.deleted_forms) > self.max_num) or \
  301. self.management_form.cleaned_data[TOTAL_FORM_COUNT] > self.absolute_max:
  302. raise ValidationError(ngettext(
  303. "Please submit %d or fewer forms.",
  304. "Please submit %d or fewer forms.", self.max_num) % self.max_num,
  305. code='too_many_forms',
  306. )
  307. if (self.validate_min and
  308. self.total_form_count() - len(self.deleted_forms) - empty_forms_count < self.min_num):
  309. raise ValidationError(ngettext(
  310. "Please submit %d or more forms.",
  311. "Please submit %d or more forms.", self.min_num) % self.min_num,
  312. code='too_few_forms')
  313. # Give self.clean() a chance to do cross-form validation.
  314. self.clean()
  315. except ValidationError as e:
  316. self._non_form_errors = self.error_class(e.error_list)
  317. def clean(self):
  318. """
  319. Hook for doing any extra formset-wide cleaning after Form.clean() has
  320. been called on every form. Any ValidationError raised by this method
  321. will not be associated with a particular form; it will be accessible
  322. via formset.non_form_errors()
  323. """
  324. pass
  325. def has_changed(self):
  326. """Return True if data in any form differs from initial."""
  327. return any(form.has_changed() for form in self)
  328. def add_fields(self, form, index):
  329. """A hook for adding extra fields on to each form instance."""
  330. if self.can_order:
  331. # Only pre-fill the ordering field for initial forms.
  332. if index is not None and index < self.initial_form_count():
  333. form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_('Order'), initial=index + 1, required=False)
  334. else:
  335. form.fields[ORDERING_FIELD_NAME] = IntegerField(label=_('Order'), required=False)
  336. if self.can_delete:
  337. form.fields[DELETION_FIELD_NAME] = BooleanField(label=_('Delete'), required=False)
  338. def add_prefix(self, index):
  339. return '%s-%s' % (self.prefix, index)
  340. def is_multipart(self):
  341. """
  342. Return True if the formset needs to be multipart, i.e. it
  343. has FileInput, or False otherwise.
  344. """
  345. if self.forms:
  346. return self.forms[0].is_multipart()
  347. else:
  348. return self.empty_form.is_multipart()
  349. @property
  350. def media(self):
  351. # All the forms on a FormSet are the same, so you only need to
  352. # interrogate the first form for media.
  353. if self.forms:
  354. return self.forms[0].media
  355. else:
  356. return self.empty_form.media
  357. def as_table(self):
  358. "Return this formset rendered as HTML <tr>s -- excluding the <table></table>."
  359. # XXX: there is no semantic division between forms here, there
  360. # probably should be. It might make sense to render each form as a
  361. # table row with each field as a td.
  362. forms = ' '.join(form.as_table() for form in self)
  363. return mark_safe(str(self.management_form) + '\n' + forms)
  364. def as_p(self):
  365. "Return this formset rendered as HTML <p>s."
  366. forms = ' '.join(form.as_p() for form in self)
  367. return mark_safe(str(self.management_form) + '\n' + forms)
  368. def as_ul(self):
  369. "Return this formset rendered as HTML <li>s."
  370. forms = ' '.join(form.as_ul() for form in self)
  371. return mark_safe(str(self.management_form) + '\n' + forms)
  372. def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
  373. can_delete=False, max_num=None, validate_max=False,
  374. min_num=None, validate_min=False):
  375. """Return a FormSet for the given form class."""
  376. if min_num is None:
  377. min_num = DEFAULT_MIN_NUM
  378. if max_num is None:
  379. max_num = DEFAULT_MAX_NUM
  380. # hard limit on forms instantiated, to prevent memory-exhaustion attacks
  381. # limit is simply max_num + DEFAULT_MAX_NUM (which is 2*DEFAULT_MAX_NUM
  382. # if max_num is None in the first place)
  383. absolute_max = max_num + DEFAULT_MAX_NUM
  384. attrs = {
  385. 'form': form,
  386. 'extra': extra,
  387. 'can_order': can_order,
  388. 'can_delete': can_delete,
  389. 'min_num': min_num,
  390. 'max_num': max_num,
  391. 'absolute_max': absolute_max,
  392. 'validate_min': validate_min,
  393. 'validate_max': validate_max,
  394. }
  395. return type(form.__name__ + 'FormSet', (formset,), attrs)
  396. def all_valid(formsets):
  397. """Validate every formset and return True if all are valid."""
  398. valid = True
  399. for formset in formsets:
  400. valid &= formset.is_valid()
  401. return valid