formsets.py 18 KB

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