PageRenderTime 1700ms CodeModel.GetById 1682ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/modeltests/model_formsets/tests.py

https://code.google.com/p/mango-py/
Python | 1167 lines | 1130 code | 20 blank | 17 comment | 0 complexity | 55bf10a4f8e5feb4ddb4bcba734f5976 MD5 | raw file
Possible License(s): BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. import datetime
  2. import re
  3. from datetime import date
  4. from decimal import Decimal
  5. from django import forms
  6. from django.db import models
  7. from django.forms.models import (_get_foreign_key, inlineformset_factory,
  8. modelformset_factory, modelformset_factory)
  9. from django.test import TestCase, skipUnlessDBFeature
  10. from modeltests.model_formsets.models import (
  11. Author, BetterAuthor, Book, BookWithCustomPK, Editor,
  12. BookWithOptionalAltEditor, AlternateBook, AuthorMeeting, CustomPrimaryKey,
  13. Place, Owner, Location, OwnerProfile, Restaurant, Product, Price,
  14. MexicanRestaurant, ClassyMexicanRestaurant, Repository, Revision,
  15. Person, Membership, Team, Player, Poet, Poem, Post)
  16. class DeletionTests(TestCase):
  17. def test_deletion(self):
  18. PoetFormSet = modelformset_factory(Poet, can_delete=True)
  19. poet = Poet.objects.create(name='test')
  20. data = {
  21. 'form-TOTAL_FORMS': u'1',
  22. 'form-INITIAL_FORMS': u'1',
  23. 'form-MAX_NUM_FORMS': u'0',
  24. 'form-0-id': str(poet.pk),
  25. 'form-0-name': u'test',
  26. 'form-0-DELETE': u'on',
  27. }
  28. formset = PoetFormSet(data, queryset=Poet.objects.all())
  29. formset.save()
  30. self.assertTrue(formset.is_valid())
  31. self.assertEqual(Poet.objects.count(), 0)
  32. def test_add_form_deletion_when_invalid(self):
  33. """
  34. Make sure that an add form that is filled out, but marked for deletion
  35. doesn't cause validation errors.
  36. """
  37. PoetFormSet = modelformset_factory(Poet, can_delete=True)
  38. data = {
  39. 'form-TOTAL_FORMS': u'1',
  40. 'form-INITIAL_FORMS': u'0',
  41. 'form-MAX_NUM_FORMS': u'0',
  42. 'form-0-id': u'',
  43. 'form-0-name': u'x' * 1000,
  44. }
  45. formset = PoetFormSet(data, queryset=Poet.objects.all())
  46. # Make sure this form doesn't pass validation.
  47. self.assertEqual(formset.is_valid(), False)
  48. self.assertEqual(Poet.objects.count(), 0)
  49. # Then make sure that it *does* pass validation and delete the object,
  50. # even though the data isn't actually valid.
  51. data['form-0-DELETE'] = 'on'
  52. formset = PoetFormSet(data, queryset=Poet.objects.all())
  53. self.assertEqual(formset.is_valid(), True)
  54. formset.save()
  55. self.assertEqual(Poet.objects.count(), 0)
  56. def test_change_form_deletion_when_invalid(self):
  57. """
  58. Make sure that an add form that is filled out, but marked for deletion
  59. doesn't cause validation errors.
  60. """
  61. PoetFormSet = modelformset_factory(Poet, can_delete=True)
  62. poet = Poet.objects.create(name='test')
  63. data = {
  64. 'form-TOTAL_FORMS': u'1',
  65. 'form-INITIAL_FORMS': u'1',
  66. 'form-MAX_NUM_FORMS': u'0',
  67. 'form-0-id': unicode(poet.id),
  68. 'form-0-name': u'x' * 1000,
  69. }
  70. formset = PoetFormSet(data, queryset=Poet.objects.all())
  71. # Make sure this form doesn't pass validation.
  72. self.assertEqual(formset.is_valid(), False)
  73. self.assertEqual(Poet.objects.count(), 1)
  74. # Then make sure that it *does* pass validation and delete the object,
  75. # even though the data isn't actually valid.
  76. data['form-0-DELETE'] = 'on'
  77. formset = PoetFormSet(data, queryset=Poet.objects.all())
  78. self.assertEqual(formset.is_valid(), True)
  79. formset.save()
  80. self.assertEqual(Poet.objects.count(), 0)
  81. class ModelFormsetTest(TestCase):
  82. def test_simple_save(self):
  83. qs = Author.objects.all()
  84. AuthorFormSet = modelformset_factory(Author, extra=3)
  85. formset = AuthorFormSet(queryset=qs)
  86. self.assertEqual(len(formset.forms), 3)
  87. self.assertEqual(formset.forms[0].as_p(),
  88. '<p><label for="id_form-0-name">Name:</label> <input id="id_form-0-name" type="text" name="form-0-name" maxlength="100" /><input type="hidden" name="form-0-id" id="id_form-0-id" /></p>')
  89. self.assertEqual(formset.forms[1].as_p(),
  90. '<p><label for="id_form-1-name">Name:</label> <input id="id_form-1-name" type="text" name="form-1-name" maxlength="100" /><input type="hidden" name="form-1-id" id="id_form-1-id" /></p>')
  91. self.assertEqual(formset.forms[2].as_p(),
  92. '<p><label for="id_form-2-name">Name:</label> <input id="id_form-2-name" type="text" name="form-2-name" maxlength="100" /><input type="hidden" name="form-2-id" id="id_form-2-id" /></p>')
  93. data = {
  94. 'form-TOTAL_FORMS': '3', # the number of forms rendered
  95. 'form-INITIAL_FORMS': '0', # the number of forms with initial data
  96. 'form-MAX_NUM_FORMS': '', # the max number of forms
  97. 'form-0-name': 'Charles Baudelaire',
  98. 'form-1-name': 'Arthur Rimbaud',
  99. 'form-2-name': '',
  100. }
  101. formset = AuthorFormSet(data=data, queryset=qs)
  102. self.assertTrue(formset.is_valid())
  103. saved = formset.save()
  104. self.assertEqual(len(saved), 2)
  105. author1, author2 = saved
  106. self.assertEqual(author1, Author.objects.get(name='Charles Baudelaire'))
  107. self.assertEqual(author2, Author.objects.get(name='Arthur Rimbaud'))
  108. authors = list(Author.objects.order_by('name'))
  109. self.assertEqual(authors, [author2, author1])
  110. # Gah! We forgot Paul Verlaine. Let's create a formset to edit the
  111. # existing authors with an extra form to add him. We *could* pass in a
  112. # queryset to restrict the Author objects we edit, but in this case
  113. # we'll use it to display them in alphabetical order by name.
  114. qs = Author.objects.order_by('name')
  115. AuthorFormSet = modelformset_factory(Author, extra=1, can_delete=False)
  116. formset = AuthorFormSet(queryset=qs)
  117. self.assertEqual(len(formset.forms), 3)
  118. self.assertEqual(formset.forms[0].as_p(),
  119. '<p><label for="id_form-0-name">Name:</label> <input id="id_form-0-name" type="text" name="form-0-name" value="Arthur Rimbaud" maxlength="100" /><input type="hidden" name="form-0-id" value="%d" id="id_form-0-id" /></p>' % author2.id)
  120. self.assertEqual(formset.forms[1].as_p(),
  121. '<p><label for="id_form-1-name">Name:</label> <input id="id_form-1-name" type="text" name="form-1-name" value="Charles Baudelaire" maxlength="100" /><input type="hidden" name="form-1-id" value="%d" id="id_form-1-id" /></p>' % author1.id)
  122. self.assertEqual(formset.forms[2].as_p(),
  123. '<p><label for="id_form-2-name">Name:</label> <input id="id_form-2-name" type="text" name="form-2-name" maxlength="100" /><input type="hidden" name="form-2-id" id="id_form-2-id" /></p>')
  124. data = {
  125. 'form-TOTAL_FORMS': '3', # the number of forms rendered
  126. 'form-INITIAL_FORMS': '2', # the number of forms with initial data
  127. 'form-MAX_NUM_FORMS': '', # the max number of forms
  128. 'form-0-id': str(author2.id),
  129. 'form-0-name': 'Arthur Rimbaud',
  130. 'form-1-id': str(author1.id),
  131. 'form-1-name': 'Charles Baudelaire',
  132. 'form-2-name': 'Paul Verlaine',
  133. }
  134. formset = AuthorFormSet(data=data, queryset=qs)
  135. self.assertTrue(formset.is_valid())
  136. # Only changed or new objects are returned from formset.save()
  137. saved = formset.save()
  138. self.assertEqual(len(saved), 1)
  139. author3 = saved[0]
  140. self.assertEqual(author3, Author.objects.get(name='Paul Verlaine'))
  141. authors = list(Author.objects.order_by('name'))
  142. self.assertEqual(authors, [author2, author1, author3])
  143. # This probably shouldn't happen, but it will. If an add form was
  144. # marked for deletion, make sure we don't save that form.
  145. qs = Author.objects.order_by('name')
  146. AuthorFormSet = modelformset_factory(Author, extra=1, can_delete=True)
  147. formset = AuthorFormSet(queryset=qs)
  148. self.assertEqual(len(formset.forms), 4)
  149. self.assertEqual(formset.forms[0].as_p(),
  150. '<p><label for="id_form-0-name">Name:</label> <input id="id_form-0-name" type="text" name="form-0-name" value="Arthur Rimbaud" maxlength="100" /></p>\n'
  151. '<p><label for="id_form-0-DELETE">Delete:</label> <input type="checkbox" name="form-0-DELETE" id="id_form-0-DELETE" /><input type="hidden" name="form-0-id" value="%d" id="id_form-0-id" /></p>' % author2.id)
  152. self.assertEqual(formset.forms[1].as_p(),
  153. '<p><label for="id_form-1-name">Name:</label> <input id="id_form-1-name" type="text" name="form-1-name" value="Charles Baudelaire" maxlength="100" /></p>\n'
  154. '<p><label for="id_form-1-DELETE">Delete:</label> <input type="checkbox" name="form-1-DELETE" id="id_form-1-DELETE" /><input type="hidden" name="form-1-id" value="%d" id="id_form-1-id" /></p>' % author1.id)
  155. self.assertEqual(formset.forms[2].as_p(),
  156. '<p><label for="id_form-2-name">Name:</label> <input id="id_form-2-name" type="text" name="form-2-name" value="Paul Verlaine" maxlength="100" /></p>\n'
  157. '<p><label for="id_form-2-DELETE">Delete:</label> <input type="checkbox" name="form-2-DELETE" id="id_form-2-DELETE" /><input type="hidden" name="form-2-id" value="%d" id="id_form-2-id" /></p>' % author3.id)
  158. self.assertEqual(formset.forms[3].as_p(),
  159. '<p><label for="id_form-3-name">Name:</label> <input id="id_form-3-name" type="text" name="form-3-name" maxlength="100" /></p>\n'
  160. '<p><label for="id_form-3-DELETE">Delete:</label> <input type="checkbox" name="form-3-DELETE" id="id_form-3-DELETE" /><input type="hidden" name="form-3-id" id="id_form-3-id" /></p>')
  161. data = {
  162. 'form-TOTAL_FORMS': '4', # the number of forms rendered
  163. 'form-INITIAL_FORMS': '3', # the number of forms with initial data
  164. 'form-MAX_NUM_FORMS': '', # the max number of forms
  165. 'form-0-id': str(author2.id),
  166. 'form-0-name': 'Arthur Rimbaud',
  167. 'form-1-id': str(author1.id),
  168. 'form-1-name': 'Charles Baudelaire',
  169. 'form-2-id': str(author3.id),
  170. 'form-2-name': 'Paul Verlaine',
  171. 'form-3-name': 'Walt Whitman',
  172. 'form-3-DELETE': 'on',
  173. }
  174. formset = AuthorFormSet(data=data, queryset=qs)
  175. self.assertTrue(formset.is_valid())
  176. # No objects were changed or saved so nothing will come back.
  177. self.assertEqual(formset.save(), [])
  178. authors = list(Author.objects.order_by('name'))
  179. self.assertEqual(authors, [author2, author1, author3])
  180. # Let's edit a record to ensure save only returns that one record.
  181. data = {
  182. 'form-TOTAL_FORMS': '4', # the number of forms rendered
  183. 'form-INITIAL_FORMS': '3', # the number of forms with initial data
  184. 'form-MAX_NUM_FORMS': '', # the max number of forms
  185. 'form-0-id': str(author2.id),
  186. 'form-0-name': 'Walt Whitman',
  187. 'form-1-id': str(author1.id),
  188. 'form-1-name': 'Charles Baudelaire',
  189. 'form-2-id': str(author3.id),
  190. 'form-2-name': 'Paul Verlaine',
  191. 'form-3-name': '',
  192. 'form-3-DELETE': '',
  193. }
  194. formset = AuthorFormSet(data=data, queryset=qs)
  195. self.assertTrue(formset.is_valid())
  196. # One record has changed.
  197. saved = formset.save()
  198. self.assertEqual(len(saved), 1)
  199. self.assertEqual(saved[0], Author.objects.get(name='Walt Whitman'))
  200. def test_commit_false(self):
  201. # Test the behavior of commit=False and save_m2m
  202. author1 = Author.objects.create(name='Charles Baudelaire')
  203. author2 = Author.objects.create(name='Paul Verlaine')
  204. author3 = Author.objects.create(name='Walt Whitman')
  205. meeting = AuthorMeeting.objects.create(created=date.today())
  206. meeting.authors = Author.objects.all()
  207. # create an Author instance to add to the meeting.
  208. author4 = Author.objects.create(name=u'John Steinbeck')
  209. AuthorMeetingFormSet = modelformset_factory(AuthorMeeting, extra=1, can_delete=True)
  210. data = {
  211. 'form-TOTAL_FORMS': '2', # the number of forms rendered
  212. 'form-INITIAL_FORMS': '1', # the number of forms with initial data
  213. 'form-MAX_NUM_FORMS': '', # the max number of forms
  214. 'form-0-id': str(meeting.id),
  215. 'form-0-name': '2nd Tuesday of the Week Meeting',
  216. 'form-0-authors': [author2.id, author1.id, author3.id, author4.id],
  217. 'form-1-name': '',
  218. 'form-1-authors': '',
  219. 'form-1-DELETE': '',
  220. }
  221. formset = AuthorMeetingFormSet(data=data, queryset=AuthorMeeting.objects.all())
  222. self.assertTrue(formset.is_valid())
  223. instances = formset.save(commit=False)
  224. for instance in instances:
  225. instance.created = date.today()
  226. instance.save()
  227. formset.save_m2m()
  228. self.assertQuerysetEqual(instances[0].authors.all(), [
  229. '<Author: Charles Baudelaire>',
  230. '<Author: John Steinbeck>',
  231. '<Author: Paul Verlaine>',
  232. '<Author: Walt Whitman>',
  233. ])
  234. def test_max_num(self):
  235. # Test the behavior of max_num with model formsets. It should allow
  236. # all existing related objects/inlines for a given object to be
  237. # displayed, but not allow the creation of new inlines beyond max_num.
  238. author1 = Author.objects.create(name='Charles Baudelaire')
  239. author2 = Author.objects.create(name='Paul Verlaine')
  240. author3 = Author.objects.create(name='Walt Whitman')
  241. qs = Author.objects.order_by('name')
  242. AuthorFormSet = modelformset_factory(Author, max_num=None, extra=3)
  243. formset = AuthorFormSet(queryset=qs)
  244. self.assertEqual(len(formset.forms), 6)
  245. self.assertEqual(len(formset.extra_forms), 3)
  246. AuthorFormSet = modelformset_factory(Author, max_num=4, extra=3)
  247. formset = AuthorFormSet(queryset=qs)
  248. self.assertEqual(len(formset.forms), 4)
  249. self.assertEqual(len(formset.extra_forms), 1)
  250. AuthorFormSet = modelformset_factory(Author, max_num=0, extra=3)
  251. formset = AuthorFormSet(queryset=qs)
  252. self.assertEqual(len(formset.forms), 3)
  253. self.assertEqual(len(formset.extra_forms), 0)
  254. AuthorFormSet = modelformset_factory(Author, max_num=None)
  255. formset = AuthorFormSet(queryset=qs)
  256. self.assertQuerysetEqual(formset.get_queryset(), [
  257. '<Author: Charles Baudelaire>',
  258. '<Author: Paul Verlaine>',
  259. '<Author: Walt Whitman>',
  260. ])
  261. AuthorFormSet = modelformset_factory(Author, max_num=0)
  262. formset = AuthorFormSet(queryset=qs)
  263. self.assertQuerysetEqual(formset.get_queryset(), [
  264. '<Author: Charles Baudelaire>',
  265. '<Author: Paul Verlaine>',
  266. '<Author: Walt Whitman>',
  267. ])
  268. AuthorFormSet = modelformset_factory(Author, max_num=4)
  269. formset = AuthorFormSet(queryset=qs)
  270. self.assertQuerysetEqual(formset.get_queryset(), [
  271. '<Author: Charles Baudelaire>',
  272. '<Author: Paul Verlaine>',
  273. '<Author: Walt Whitman>',
  274. ])
  275. def test_custom_save_method(self):
  276. class PoetForm(forms.ModelForm):
  277. def save(self, commit=True):
  278. # change the name to "Vladimir Mayakovsky" just to be a jerk.
  279. author = super(PoetForm, self).save(commit=False)
  280. author.name = u"Vladimir Mayakovsky"
  281. if commit:
  282. author.save()
  283. return author
  284. PoetFormSet = modelformset_factory(Poet, form=PoetForm)
  285. data = {
  286. 'form-TOTAL_FORMS': '3', # the number of forms rendered
  287. 'form-INITIAL_FORMS': '0', # the number of forms with initial data
  288. 'form-MAX_NUM_FORMS': '', # the max number of forms
  289. 'form-0-name': 'Walt Whitman',
  290. 'form-1-name': 'Charles Baudelaire',
  291. 'form-2-name': '',
  292. }
  293. qs = Poet.objects.all()
  294. formset = PoetFormSet(data=data, queryset=qs)
  295. self.assertTrue(formset.is_valid())
  296. poets = formset.save()
  297. self.assertEqual(len(poets), 2)
  298. poet1, poet2 = poets
  299. self.assertEqual(poet1.name, 'Vladimir Mayakovsky')
  300. self.assertEqual(poet2.name, 'Vladimir Mayakovsky')
  301. def test_model_inheritance(self):
  302. BetterAuthorFormSet = modelformset_factory(BetterAuthor)
  303. formset = BetterAuthorFormSet()
  304. self.assertEqual(len(formset.forms), 1)
  305. self.assertEqual(formset.forms[0].as_p(),
  306. '<p><label for="id_form-0-name">Name:</label> <input id="id_form-0-name" type="text" name="form-0-name" maxlength="100" /></p>\n'
  307. '<p><label for="id_form-0-write_speed">Write speed:</label> <input type="text" name="form-0-write_speed" id="id_form-0-write_speed" /><input type="hidden" name="form-0-author_ptr" id="id_form-0-author_ptr" /></p>')
  308. data = {
  309. 'form-TOTAL_FORMS': '1', # the number of forms rendered
  310. 'form-INITIAL_FORMS': '0', # the number of forms with initial data
  311. 'form-MAX_NUM_FORMS': '', # the max number of forms
  312. 'form-0-author_ptr': '',
  313. 'form-0-name': 'Ernest Hemingway',
  314. 'form-0-write_speed': '10',
  315. }
  316. formset = BetterAuthorFormSet(data)
  317. self.assertTrue(formset.is_valid())
  318. saved = formset.save()
  319. self.assertEqual(len(saved), 1)
  320. author1, = saved
  321. self.assertEqual(author1, BetterAuthor.objects.get(name='Ernest Hemingway'))
  322. hemingway_id = BetterAuthor.objects.get(name="Ernest Hemingway").pk
  323. formset = BetterAuthorFormSet()
  324. self.assertEqual(len(formset.forms), 2)
  325. self.assertEqual(formset.forms[0].as_p(),
  326. '<p><label for="id_form-0-name">Name:</label> <input id="id_form-0-name" type="text" name="form-0-name" value="Ernest Hemingway" maxlength="100" /></p>\n'
  327. '<p><label for="id_form-0-write_speed">Write speed:</label> <input type="text" name="form-0-write_speed" value="10" id="id_form-0-write_speed" /><input type="hidden" name="form-0-author_ptr" value="%d" id="id_form-0-author_ptr" /></p>' % hemingway_id)
  328. self.assertEqual(formset.forms[1].as_p(),
  329. '<p><label for="id_form-1-name">Name:</label> <input id="id_form-1-name" type="text" name="form-1-name" maxlength="100" /></p>\n'
  330. '<p><label for="id_form-1-write_speed">Write speed:</label> <input type="text" name="form-1-write_speed" id="id_form-1-write_speed" /><input type="hidden" name="form-1-author_ptr" id="id_form-1-author_ptr" /></p>')
  331. data = {
  332. 'form-TOTAL_FORMS': '2', # the number of forms rendered
  333. 'form-INITIAL_FORMS': '1', # the number of forms with initial data
  334. 'form-MAX_NUM_FORMS': '', # the max number of forms
  335. 'form-0-author_ptr': hemingway_id,
  336. 'form-0-name': 'Ernest Hemingway',
  337. 'form-0-write_speed': '10',
  338. 'form-1-author_ptr': '',
  339. 'form-1-name': '',
  340. 'form-1-write_speed': '',
  341. }
  342. formset = BetterAuthorFormSet(data)
  343. self.assertTrue(formset.is_valid())
  344. self.assertEqual(formset.save(), [])
  345. def test_inline_formsets(self):
  346. # We can also create a formset that is tied to a parent model. This is
  347. # how the admin system's edit inline functionality works.
  348. AuthorBooksFormSet = inlineformset_factory(Author, Book, can_delete=False, extra=3)
  349. author = Author.objects.create(name='Charles Baudelaire')
  350. formset = AuthorBooksFormSet(instance=author)
  351. self.assertEqual(len(formset.forms), 3)
  352. self.assertEqual(formset.forms[0].as_p(),
  353. '<p><label for="id_book_set-0-title">Title:</label> <input id="id_book_set-0-title" type="text" name="book_set-0-title" maxlength="100" /><input type="hidden" name="book_set-0-author" value="%d" id="id_book_set-0-author" /><input type="hidden" name="book_set-0-id" id="id_book_set-0-id" /></p>' % author.id)
  354. self.assertEqual(formset.forms[1].as_p(),
  355. '<p><label for="id_book_set-1-title">Title:</label> <input id="id_book_set-1-title" type="text" name="book_set-1-title" maxlength="100" /><input type="hidden" name="book_set-1-author" value="%d" id="id_book_set-1-author" /><input type="hidden" name="book_set-1-id" id="id_book_set-1-id" /></p>' % author.id)
  356. self.assertEqual(formset.forms[2].as_p(),
  357. '<p><label for="id_book_set-2-title">Title:</label> <input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100" /><input type="hidden" name="book_set-2-author" value="%d" id="id_book_set-2-author" /><input type="hidden" name="book_set-2-id" id="id_book_set-2-id" /></p>' % author.id)
  358. data = {
  359. 'book_set-TOTAL_FORMS': '3', # the number of forms rendered
  360. 'book_set-INITIAL_FORMS': '0', # the number of forms with initial data
  361. 'book_set-MAX_NUM_FORMS': '', # the max number of forms
  362. 'book_set-0-title': 'Les Fleurs du Mal',
  363. 'book_set-1-title': '',
  364. 'book_set-2-title': '',
  365. }
  366. formset = AuthorBooksFormSet(data, instance=author)
  367. self.assertTrue(formset.is_valid())
  368. saved = formset.save()
  369. self.assertEqual(len(saved), 1)
  370. book1, = saved
  371. self.assertEqual(book1, Book.objects.get(title='Les Fleurs du Mal'))
  372. self.assertQuerysetEqual(author.book_set.all(), ['<Book: Les Fleurs du Mal>'])
  373. # Now that we've added a book to Charles Baudelaire, let's try adding
  374. # another one. This time though, an edit form will be available for
  375. # every existing book.
  376. AuthorBooksFormSet = inlineformset_factory(Author, Book, can_delete=False, extra=2)
  377. author = Author.objects.get(name='Charles Baudelaire')
  378. formset = AuthorBooksFormSet(instance=author)
  379. self.assertEqual(len(formset.forms), 3)
  380. self.assertEqual(formset.forms[0].as_p(),
  381. '<p><label for="id_book_set-0-title">Title:</label> <input id="id_book_set-0-title" type="text" name="book_set-0-title" value="Les Fleurs du Mal" maxlength="100" /><input type="hidden" name="book_set-0-author" value="%d" id="id_book_set-0-author" /><input type="hidden" name="book_set-0-id" value="%d" id="id_book_set-0-id" /></p>' % (author.id, book1.id))
  382. self.assertEqual(formset.forms[1].as_p(),
  383. '<p><label for="id_book_set-1-title">Title:</label> <input id="id_book_set-1-title" type="text" name="book_set-1-title" maxlength="100" /><input type="hidden" name="book_set-1-author" value="%d" id="id_book_set-1-author" /><input type="hidden" name="book_set-1-id" id="id_book_set-1-id" /></p>' % author.id)
  384. self.assertEqual(formset.forms[2].as_p(),
  385. '<p><label for="id_book_set-2-title">Title:</label> <input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100" /><input type="hidden" name="book_set-2-author" value="%d" id="id_book_set-2-author" /><input type="hidden" name="book_set-2-id" id="id_book_set-2-id" /></p>' % author.id)
  386. data = {
  387. 'book_set-TOTAL_FORMS': '3', # the number of forms rendered
  388. 'book_set-INITIAL_FORMS': '1', # the number of forms with initial data
  389. 'book_set-MAX_NUM_FORMS': '', # the max number of forms
  390. 'book_set-0-id': str(book1.id),
  391. 'book_set-0-title': 'Les Fleurs du Mal',
  392. 'book_set-1-title': 'Les Paradis Artificiels',
  393. 'book_set-2-title': '',
  394. }
  395. formset = AuthorBooksFormSet(data, instance=author)
  396. self.assertTrue(formset.is_valid())
  397. saved = formset.save()
  398. self.assertEqual(len(saved), 1)
  399. book2, = saved
  400. self.assertEqual(book2, Book.objects.get(title='Les Paradis Artificiels'))
  401. # As you can see, 'Les Paradis Artificiels' is now a book belonging to
  402. # Charles Baudelaire.
  403. self.assertQuerysetEqual(author.book_set.order_by('title'), [
  404. '<Book: Les Fleurs du Mal>',
  405. '<Book: Les Paradis Artificiels>',
  406. ])
  407. def test_inline_formsets_save_as_new(self):
  408. # The save_as_new parameter lets you re-associate the data to a new
  409. # instance. This is used in the admin for save_as functionality.
  410. AuthorBooksFormSet = inlineformset_factory(Author, Book, can_delete=False, extra=2)
  411. author = Author.objects.create(name='Charles Baudelaire')
  412. data = {
  413. 'book_set-TOTAL_FORMS': '3', # the number of forms rendered
  414. 'book_set-INITIAL_FORMS': '2', # the number of forms with initial data
  415. 'book_set-MAX_NUM_FORMS': '', # the max number of forms
  416. 'book_set-0-id': '1',
  417. 'book_set-0-title': 'Les Fleurs du Mal',
  418. 'book_set-1-id': '2',
  419. 'book_set-1-title': 'Les Paradis Artificiels',
  420. 'book_set-2-title': '',
  421. }
  422. formset = AuthorBooksFormSet(data, instance=Author(), save_as_new=True)
  423. self.assertTrue(formset.is_valid())
  424. new_author = Author.objects.create(name='Charles Baudelaire')
  425. formset = AuthorBooksFormSet(data, instance=new_author, save_as_new=True)
  426. saved = formset.save()
  427. self.assertEqual(len(saved), 2)
  428. book1, book2 = saved
  429. self.assertEqual(book1.title, 'Les Fleurs du Mal')
  430. self.assertEqual(book2.title, 'Les Paradis Artificiels')
  431. # Test using a custom prefix on an inline formset.
  432. formset = AuthorBooksFormSet(prefix="test")
  433. self.assertEqual(len(formset.forms), 2)
  434. self.assertEqual(formset.forms[0].as_p(),
  435. '<p><label for="id_test-0-title">Title:</label> <input id="id_test-0-title" type="text" name="test-0-title" maxlength="100" /><input type="hidden" name="test-0-author" id="id_test-0-author" /><input type="hidden" name="test-0-id" id="id_test-0-id" /></p>')
  436. self.assertEqual(formset.forms[1].as_p(),
  437. '<p><label for="id_test-1-title">Title:</label> <input id="id_test-1-title" type="text" name="test-1-title" maxlength="100" /><input type="hidden" name="test-1-author" id="id_test-1-author" /><input type="hidden" name="test-1-id" id="id_test-1-id" /></p>')
  438. def test_inline_formsets_with_custom_pk(self):
  439. # Test inline formsets where the inline-edited object has a custom
  440. # primary key that is not the fk to the parent object.
  441. AuthorBooksFormSet2 = inlineformset_factory(Author, BookWithCustomPK, can_delete=False, extra=1)
  442. author = Author.objects.create(pk=1, name='Charles Baudelaire')
  443. formset = AuthorBooksFormSet2(instance=author)
  444. self.assertEqual(len(formset.forms), 1)
  445. self.assertEqual(formset.forms[0].as_p(),
  446. '<p><label for="id_bookwithcustompk_set-0-my_pk">My pk:</label> <input type="text" name="bookwithcustompk_set-0-my_pk" id="id_bookwithcustompk_set-0-my_pk" /></p>\n'
  447. '<p><label for="id_bookwithcustompk_set-0-title">Title:</label> <input id="id_bookwithcustompk_set-0-title" type="text" name="bookwithcustompk_set-0-title" maxlength="100" /><input type="hidden" name="bookwithcustompk_set-0-author" value="1" id="id_bookwithcustompk_set-0-author" /></p>')
  448. data = {
  449. 'bookwithcustompk_set-TOTAL_FORMS': '1', # the number of forms rendered
  450. 'bookwithcustompk_set-INITIAL_FORMS': '0', # the number of forms with initial data
  451. 'bookwithcustompk_set-MAX_NUM_FORMS': '', # the max number of forms
  452. 'bookwithcustompk_set-0-my_pk': '77777',
  453. 'bookwithcustompk_set-0-title': 'Les Fleurs du Mal',
  454. }
  455. formset = AuthorBooksFormSet2(data, instance=author)
  456. self.assertTrue(formset.is_valid())
  457. saved = formset.save()
  458. self.assertEqual(len(saved), 1)
  459. book1, = saved
  460. self.assertEqual(book1.pk, 77777)
  461. book1 = author.bookwithcustompk_set.get()
  462. self.assertEqual(book1.title, 'Les Fleurs du Mal')
  463. def test_inline_formsets_with_multi_table_inheritance(self):
  464. # Test inline formsets where the inline-edited object uses multi-table
  465. # inheritance, thus has a non AutoField yet auto-created primary key.
  466. AuthorBooksFormSet3 = inlineformset_factory(Author, AlternateBook, can_delete=False, extra=1)
  467. author = Author.objects.create(pk=1, name='Charles Baudelaire')
  468. formset = AuthorBooksFormSet3(instance=author)
  469. self.assertEqual(len(formset.forms), 1)
  470. self.assertEqual(formset.forms[0].as_p(),
  471. '<p><label for="id_alternatebook_set-0-title">Title:</label> <input id="id_alternatebook_set-0-title" type="text" name="alternatebook_set-0-title" maxlength="100" /></p>\n'
  472. '<p><label for="id_alternatebook_set-0-notes">Notes:</label> <input id="id_alternatebook_set-0-notes" type="text" name="alternatebook_set-0-notes" maxlength="100" /><input type="hidden" name="alternatebook_set-0-author" value="1" id="id_alternatebook_set-0-author" /><input type="hidden" name="alternatebook_set-0-book_ptr" id="id_alternatebook_set-0-book_ptr" /></p>')
  473. data = {
  474. 'alternatebook_set-TOTAL_FORMS': '1', # the number of forms rendered
  475. 'alternatebook_set-INITIAL_FORMS': '0', # the number of forms with initial data
  476. 'alternatebook_set-MAX_NUM_FORMS': '', # the max number of forms
  477. 'alternatebook_set-0-title': 'Flowers of Evil',
  478. 'alternatebook_set-0-notes': 'English translation of Les Fleurs du Mal'
  479. }
  480. formset = AuthorBooksFormSet3(data, instance=author)
  481. self.assertTrue(formset.is_valid())
  482. saved = formset.save()
  483. self.assertEqual(len(saved), 1)
  484. book1, = saved
  485. self.assertEqual(book1.title, 'Flowers of Evil')
  486. self.assertEqual(book1.notes, 'English translation of Les Fleurs du Mal')
  487. @skipUnlessDBFeature('ignores_nulls_in_unique_constraints')
  488. def test_inline_formsets_with_nullable_unique_together(self):
  489. # Test inline formsets where the inline-edited object has a
  490. # unique_together constraint with a nullable member
  491. AuthorBooksFormSet4 = inlineformset_factory(Author, BookWithOptionalAltEditor, can_delete=False, extra=2)
  492. author = Author.objects.create(pk=1, name='Charles Baudelaire')
  493. data = {
  494. 'bookwithoptionalalteditor_set-TOTAL_FORMS': '2', # the number of forms rendered
  495. 'bookwithoptionalalteditor_set-INITIAL_FORMS': '0', # the number of forms with initial data
  496. 'bookwithoptionalalteditor_set-MAX_NUM_FORMS': '', # the max number of forms
  497. 'bookwithoptionalalteditor_set-0-author': '1',
  498. 'bookwithoptionalalteditor_set-0-title': 'Les Fleurs du Mal',
  499. 'bookwithoptionalalteditor_set-1-author': '1',
  500. 'bookwithoptionalalteditor_set-1-title': 'Les Fleurs du Mal',
  501. }
  502. formset = AuthorBooksFormSet4(data, instance=author)
  503. self.assertTrue(formset.is_valid())
  504. saved = formset.save()
  505. self.assertEqual(len(saved), 2)
  506. book1, book2 = saved
  507. self.assertEqual(book1.author_id, 1)
  508. self.assertEqual(book1.title, 'Les Fleurs du Mal')
  509. self.assertEqual(book2.author_id, 1)
  510. self.assertEqual(book2.title, 'Les Fleurs du Mal')
  511. def test_inline_formsets_with_custom_save_method(self):
  512. AuthorBooksFormSet = inlineformset_factory(Author, Book, can_delete=False, extra=2)
  513. author = Author.objects.create(pk=1, name='Charles Baudelaire')
  514. book1 = Book.objects.create(pk=1, author=author, title='Les Paradis Artificiels')
  515. book2 = Book.objects.create(pk=2, author=author, title='Les Fleurs du Mal')
  516. book3 = Book.objects.create(pk=3, author=author, title='Flowers of Evil')
  517. class PoemForm(forms.ModelForm):
  518. def save(self, commit=True):
  519. # change the name to "Brooklyn Bridge" just to be a jerk.
  520. poem = super(PoemForm, self).save(commit=False)
  521. poem.name = u"Brooklyn Bridge"
  522. if commit:
  523. poem.save()
  524. return poem
  525. PoemFormSet = inlineformset_factory(Poet, Poem, form=PoemForm)
  526. data = {
  527. 'poem_set-TOTAL_FORMS': '3', # the number of forms rendered
  528. 'poem_set-INITIAL_FORMS': '0', # the number of forms with initial data
  529. 'poem_set-MAX_NUM_FORMS': '', # the max number of forms
  530. 'poem_set-0-name': 'The Cloud in Trousers',
  531. 'poem_set-1-name': 'I',
  532. 'poem_set-2-name': '',
  533. }
  534. poet = Poet.objects.create(name='Vladimir Mayakovsky')
  535. formset = PoemFormSet(data=data, instance=poet)
  536. self.assertTrue(formset.is_valid())
  537. saved = formset.save()
  538. self.assertEqual(len(saved), 2)
  539. poem1, poem2 = saved
  540. self.assertEqual(poem1.name, 'Brooklyn Bridge')
  541. self.assertEqual(poem2.name, 'Brooklyn Bridge')
  542. # We can provide a custom queryset to our InlineFormSet:
  543. custom_qs = Book.objects.order_by('-title')
  544. formset = AuthorBooksFormSet(instance=author, queryset=custom_qs)
  545. self.assertEqual(len(formset.forms), 5)
  546. self.assertEqual(formset.forms[0].as_p(),
  547. '<p><label for="id_book_set-0-title">Title:</label> <input id="id_book_set-0-title" type="text" name="book_set-0-title" value="Les Paradis Artificiels" maxlength="100" /><input type="hidden" name="book_set-0-author" value="1" id="id_book_set-0-author" /><input type="hidden" name="book_set-0-id" value="1" id="id_book_set-0-id" /></p>')
  548. self.assertEqual(formset.forms[1].as_p(),
  549. '<p><label for="id_book_set-1-title">Title:</label> <input id="id_book_set-1-title" type="text" name="book_set-1-title" value="Les Fleurs du Mal" maxlength="100" /><input type="hidden" name="book_set-1-author" value="1" id="id_book_set-1-author" /><input type="hidden" name="book_set-1-id" value="2" id="id_book_set-1-id" /></p>')
  550. self.assertEqual(formset.forms[2].as_p(),
  551. '<p><label for="id_book_set-2-title">Title:</label> <input id="id_book_set-2-title" type="text" name="book_set-2-title" value="Flowers of Evil" maxlength="100" /><input type="hidden" name="book_set-2-author" value="1" id="id_book_set-2-author" /><input type="hidden" name="book_set-2-id" value="3" id="id_book_set-2-id" /></p>')
  552. self.assertEqual(formset.forms[3].as_p(),
  553. '<p><label for="id_book_set-3-title">Title:</label> <input id="id_book_set-3-title" type="text" name="book_set-3-title" maxlength="100" /><input type="hidden" name="book_set-3-author" value="1" id="id_book_set-3-author" /><input type="hidden" name="book_set-3-id" id="id_book_set-3-id" /></p>')
  554. self.assertEqual(formset.forms[4].as_p(),
  555. '<p><label for="id_book_set-4-title">Title:</label> <input id="id_book_set-4-title" type="text" name="book_set-4-title" maxlength="100" /><input type="hidden" name="book_set-4-author" value="1" id="id_book_set-4-author" /><input type="hidden" name="book_set-4-id" id="id_book_set-4-id" /></p>')
  556. data = {
  557. 'book_set-TOTAL_FORMS': '5', # the number of forms rendered
  558. 'book_set-INITIAL_FORMS': '3', # the number of forms with initial data
  559. 'book_set-MAX_NUM_FORMS': '', # the max number of forms
  560. 'book_set-0-id': str(book1.id),
  561. 'book_set-0-title': 'Les Paradis Artificiels',
  562. 'book_set-1-id': str(book2.id),
  563. 'book_set-1-title': 'Les Fleurs du Mal',
  564. 'book_set-2-id': str(book3.id),
  565. 'book_set-2-title': 'Flowers of Evil',
  566. 'book_set-3-title': 'Revue des deux mondes',
  567. 'book_set-4-title': '',
  568. }
  569. formset = AuthorBooksFormSet(data, instance=author, queryset=custom_qs)
  570. self.assertTrue(formset.is_valid())
  571. custom_qs = Book.objects.filter(title__startswith='F')
  572. formset = AuthorBooksFormSet(instance=author, queryset=custom_qs)
  573. self.assertEqual(formset.forms[0].as_p(),
  574. '<p><label for="id_book_set-0-title">Title:</label> <input id="id_book_set-0-title" type="text" name="book_set-0-title" value="Flowers of Evil" maxlength="100" /><input type="hidden" name="book_set-0-author" value="1" id="id_book_set-0-author" /><input type="hidden" name="book_set-0-id" value="3" id="id_book_set-0-id" /></p>')
  575. self.assertEqual(formset.forms[1].as_p(),
  576. '<p><label for="id_book_set-1-title">Title:</label> <input id="id_book_set-1-title" type="text" name="book_set-1-title" maxlength="100" /><input type="hidden" name="book_set-1-author" value="1" id="id_book_set-1-author" /><input type="hidden" name="book_set-1-id" id="id_book_set-1-id" /></p>')
  577. self.assertEqual(formset.forms[2].as_p(),
  578. '<p><label for="id_book_set-2-title">Title:</label> <input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100" /><input type="hidden" name="book_set-2-author" value="1" id="id_book_set-2-author" /><input type="hidden" name="book_set-2-id" id="id_book_set-2-id" /></p>')
  579. data = {
  580. 'book_set-TOTAL_FORMS': '3', # the number of forms rendered
  581. 'book_set-INITIAL_FORMS': '1', # the number of forms with initial data
  582. 'book_set-MAX_NUM_FORMS': '', # the max number of forms
  583. 'book_set-0-id': str(book3.id),
  584. 'book_set-0-title': 'Flowers of Evil',
  585. 'book_set-1-title': 'Revue des deux mondes',
  586. 'book_set-2-title': '',
  587. }
  588. formset = AuthorBooksFormSet(data, instance=author, queryset=custom_qs)
  589. self.assertTrue(formset.is_valid())
  590. def test_custom_pk(self):
  591. # We need to ensure that it is displayed
  592. CustomPrimaryKeyFormSet = modelformset_factory(CustomPrimaryKey)
  593. formset = CustomPrimaryKeyFormSet()
  594. self.assertEqual(len(formset.forms), 1)
  595. self.assertEqual(formset.forms[0].as_p(),
  596. '<p><label for="id_form-0-my_pk">My pk:</label> <input id="id_form-0-my_pk" type="text" name="form-0-my_pk" maxlength="10" /></p>\n'
  597. '<p><label for="id_form-0-some_field">Some field:</label> <input id="id_form-0-some_field" type="text" name="form-0-some_field" maxlength="100" /></p>')
  598. # Custom primary keys with ForeignKey, OneToOneField and AutoField ############
  599. place = Place.objects.create(pk=1, name=u'Giordanos', city=u'Chicago')
  600. FormSet = inlineformset_factory(Place, Owner, extra=2, can_delete=False)
  601. formset = FormSet(instance=place)
  602. self.assertEqual(len(formset.forms), 2)
  603. self.assertEqual(formset.forms[0].as_p(),
  604. '<p><label for="id_owner_set-0-name">Name:</label> <input id="id_owner_set-0-name" type="text" name="owner_set-0-name" maxlength="100" /><input type="hidden" name="owner_set-0-place" value="1" id="id_owner_set-0-place" /><input type="hidden" name="owner_set-0-auto_id" id="id_owner_set-0-auto_id" /></p>')
  605. self.assertEqual(formset.forms[1].as_p(),
  606. '<p><label for="id_owner_set-1-name">Name:</label> <input id="id_owner_set-1-name" type="text" name="owner_set-1-name" maxlength="100" /><input type="hidden" name="owner_set-1-place" value="1" id="id_owner_set-1-place" /><input type="hidden" name="owner_set-1-auto_id" id="id_owner_set-1-auto_id" /></p>')
  607. data = {
  608. 'owner_set-TOTAL_FORMS': '2',
  609. 'owner_set-INITIAL_FORMS': '0',
  610. 'owner_set-MAX_NUM_FORMS': '',
  611. 'owner_set-0-auto_id': '',
  612. 'owner_set-0-name': u'Joe Perry',
  613. 'owner_set-1-auto_id': '',
  614. 'owner_set-1-name': '',
  615. }
  616. formset = FormSet(data, instance=place)
  617. self.assertTrue(formset.is_valid())
  618. saved = formset.save()
  619. self.assertEqual(len(saved), 1)
  620. owner1, = saved
  621. self.assertEqual(owner1.name, 'Joe Perry')
  622. self.assertEqual(owner1.place.name, 'Giordanos')
  623. formset = FormSet(instance=place)
  624. self.assertEqual(len(formset.forms), 3)
  625. self.assertEqual(formset.forms[0].as_p(),
  626. '<p><label for="id_owner_set-0-name">Name:</label> <input id="id_owner_set-0-name" type="text" name="owner_set-0-name" value="Joe Perry" maxlength="100" /><input type="hidden" name="owner_set-0-place" value="1" id="id_owner_set-0-place" /><input type="hidden" name="owner_set-0-auto_id" value="%d" id="id_owner_set-0-auto_id" /></p>'
  627. % owner1.auto_id)
  628. self.assertEqual(formset.forms[1].as_p(),
  629. '<p><label for="id_owner_set-1-name">Name:</label> <input id="id_owner_set-1-name" type="text" name="owner_set-1-name" maxlength="100" /><input type="hidden" name="owner_set-1-place" value="1" id="id_owner_set-1-place" /><input type="hidden" name="owner_set-1-auto_id" id="id_owner_set-1-auto_id" /></p>')
  630. self.assertEqual(formset.forms[2].as_p(),
  631. '<p><label for="id_owner_set-2-name">Name:</label> <input id="id_owner_set-2-name" type="text" name="owner_set-2-name" maxlength="100" /><input type="hidden" name="owner_set-2-place" value="1" id="id_owner_set-2-place" /><input type="hidden" name="owner_set-2-auto_id" id="id_owner_set-2-auto_id" /></p>')
  632. data = {
  633. 'owner_set-TOTAL_FORMS': '3',
  634. 'owner_set-INITIAL_FORMS': '1',
  635. 'owner_set-MAX_NUM_FORMS': '',
  636. 'owner_set-0-auto_id': unicode(owner1.auto_id),
  637. 'owner_set-0-name': u'Joe Perry',
  638. 'owner_set-1-auto_id': '',
  639. 'owner_set-1-name': u'Jack Berry',
  640. 'owner_set-2-auto_id': '',
  641. 'owner_set-2-name': '',
  642. }
  643. formset = FormSet(data, instance=place)
  644. self.assertTrue(formset.is_valid())
  645. saved = formset.save()
  646. self.assertEqual(len(saved), 1)
  647. owner2, = saved
  648. self.assertEqual(owner2.name, 'Jack Berry')
  649. self.assertEqual(owner2.place.name, 'Giordanos')
  650. # Ensure a custom primary key that is a ForeignKey or OneToOneField get rendered for the user to choose.
  651. FormSet = modelformset_factory(OwnerProfile)
  652. formset = FormSet()
  653. self.assertEqual(formset.forms[0].as_p(),
  654. '<p><label for="id_form-0-owner">Owner:</label> <select name="form-0-owner" id="id_form-0-owner">\n'
  655. '<option value="" selected="selected">---------</option>\n'
  656. '<option value="%d">Joe Perry at Giordanos</option>\n'
  657. '<option value="%d">Jack Berry at Giordanos</option>\n'
  658. '</select></p>\n'
  659. '<p><label for="id_form-0-age">Age:</label> <input type="text" name="form-0-age" id="id_form-0-age" /></p>'
  660. % (owner1.auto_id, owner2.auto_id))
  661. owner1 = Owner.objects.get(name=u'Joe Perry')
  662. FormSet = inlineformset_factory(Owner, OwnerProfile, max_num=1, can_delete=False)
  663. self.assertEqual(FormSet.max_num, 1)
  664. formset = FormSet(instance=owner1)
  665. self.assertEqual(len(formset.forms), 1)
  666. self.assertEqual(formset.forms[0].as_p(),
  667. '<p><label for="id_ownerprofile-0-age">Age:</label> <input type="text" name="ownerprofile-0-age" id="id_ownerprofile-0-age" /><input type="hidden" name="ownerprofile-0-owner" value="%d" id="id_ownerprofile-0-owner" /></p>'
  668. % owner1.auto_id)
  669. data = {
  670. 'ownerprofile-TOTAL_FORMS': '1',
  671. 'ownerprofile-INITIAL_FORMS': '0',
  672. 'ownerprofile-MAX_NUM_FORMS': '1',
  673. 'ownerprofile-0-owner': '',
  674. 'ownerprofile-0-age': u'54',
  675. }
  676. formset = FormSet(data, instance=owner1)
  677. self.assertTrue(formset.is_valid())
  678. saved = formset.save()
  679. self.assertEqual(len(saved), 1)
  680. profile1, = saved
  681. self.assertEqual(profile1.owner, owner1)
  682. self.assertEqual(profile1.age, 54)
  683. formset = FormSet(instance=owner1)
  684. self.assertEqual(len(formset.forms), 1)
  685. self.assertEqual(formset.forms[0].as_p(),
  686. '<p><label for="id_ownerprofile-0-age">Age:</label> <input type="text" name="ownerprofile-0-age" value="54" id="id_ownerprofile-0-age" /><input type="hidden" name="ownerprofile-0-owner" value="%d" id="id_ownerprofile-0-owner" /></p>'
  687. % owner1.auto_id)
  688. data = {
  689. 'ownerprofile-TOTAL_FORMS': '1',
  690. 'ownerprofile-INITIAL_FORMS': '1',
  691. 'ownerprofile-MAX_NUM_FORMS': '1',
  692. 'ownerprofile-0-owner': unicode(owner1.auto_id),
  693. 'ownerprofile-0-age': u'55',
  694. }
  695. formset = FormSet(data, instance=owner1)
  696. self.assertTrue(formset.is_valid())
  697. saved = formset.save()
  698. self.assertEqual(len(saved), 1)
  699. profile1, = saved
  700. self.assertEqual(profile1.owner, owner1)
  701. self.assertEqual(profile1.age, 55)
  702. def test_unique_true_enforces_max_num_one(self):
  703. # ForeignKey with unique=True should enforce max_num=1
  704. place = Place.objects.create(pk=1, name=u'Giordanos', city=u'Chicago')
  705. FormSet = inlineformset_factory(Place, Location, can_delete=False)
  706. self.assertEqual(FormSet.max_num, 1)
  707. formset = FormSet(instance=place)
  708. self.assertEqual(len(formset.forms), 1)
  709. self.assertEqual(formset.forms[0].as_p(),
  710. '<p><label for="id_location_set-0-lat">Lat:</label> <input id="id_location_set-0-lat" type="text" name="location_set-0-lat" maxlength="100" /></p>\n'
  711. '<p><label for="id_location_set-0-lon">Lon:</label> <input id="id_location_set-0-lon" type="text" name="location_set-0-lon" maxlength="100" /><input type="hidden" name="location_set-0-place" value="1" id="id_location_set-0-place" /><input type="hidden" name="location_set-0-id" id="id_location_set-0-id" /></p>')
  712. def test_foreign_keys_in_parents(self):
  713. self.assertEqual(type(_get_foreign_key(Restaurant, Owner)), models.ForeignKey)
  714. self.assertEqual(type(_get_foreign_key(MexicanRestaurant, Owner)), models.ForeignKey)
  715. def test_unique_validation(self):
  716. FormSet = modelformset_factory(Product, extra=1)
  717. data = {
  718. 'form-TOTAL_FORMS': '1',
  719. 'form-INITIAL_FORMS': '0',
  720. 'form-MAX_NUM_FORMS': '',
  721. 'form-0-slug': 'car-red',
  722. }
  723. formset = FormSet(data)
  724. self.assertTrue(formset.is_valid())
  725. saved = formset.save()
  726. self.assertEqual(len(saved), 1)
  727. product1, = saved
  728. self.assertEqual(product1.slug, 'car-red')
  729. data = {
  730. 'form-TOTAL_FORMS': '1',
  731. 'form-INITIAL_FORMS': '0',
  732. 'form-MAX_NUM_FORMS': '',
  733. 'form-0-slug': 'car-red',
  734. }
  735. formset = FormSet(data)
  736. self.assertFalse(formset.is_valid())
  737. self.assertEqual(formset.errors, [{'slug': [u'Product with this Slug already exists.']}])
  738. def test_unique_together_validation(self):
  739. FormSet = modelformset_factory(Price, extra=1)
  740. data = {
  741. 'form-TOTAL_FORMS': '1',
  742. 'form-INITIAL_FORMS': '0',
  743. 'form-MAX_NUM_FORMS': '',
  744. 'form-0-price': u'12.00',
  745. 'form-0-quantity': '1',
  746. }
  747. formset = FormSet(data)
  748. self.assertTrue(formset.is_valid())
  749. saved = formset.save()
  750. self.assertEqual(len(saved), 1)
  751. price1, = saved
  752. self.assertEqual(price1.price, Decimal('12.00'))
  753. self.assertEqual(price1.quantity, 1)
  754. data = {
  755. 'form-TOTAL_FORMS': '1',
  756. 'form-INITIAL_FORMS': '0',
  757. 'form-MAX_NUM_FORMS': '',
  758. 'form-0-price': u'12.00',
  759. 'form-0-quantity': '1',
  760. }
  761. formset = FormSet(data)
  762. self.assertFalse(formset.is_valid())
  763. self.assertEqual(formset.errors, [{'__all__': [u'Price with this Price and Quantity already exists.']}])
  764. def test_unique_together_with_inlineformset_factory(self):
  765. # Also see bug #8882.
  766. repository = Repository.objects.create(name=u'Test Repo')
  767. FormSet = inlineformset_factory(Repository, Revision, extra=1)
  768. data = {
  769. 'revision_set-TOTAL_FORMS': '1',
  770. 'revision_set-INITIAL_FORMS': '0',
  771. 'revision_set-MAX_NUM_FORMS': '',
  772. 'revision_set-0-repository': repository.pk,
  773. 'revision_set-0-revision': '146239817507f148d448db38840db7c3cbf47c76',
  774. 'revision_set-0-DELETE': '',
  775. }
  776. formset = FormSet(data, instance=repository)
  777. self.assertTrue(formset.is_valid())
  778. saved = formset.save()
  779. self.assertEqual(len(saved), 1)
  780. revision1, = saved
  781. self.assertEqual(revision1.repository, repository)
  782. self.assertEqual(revision1.revision, '146239817507f148d448db38840db7c3cbf47c76')
  783. # attempt to save the same revision against against the same repo.
  784. data = {
  785. 'revision_set-TOTAL_FORMS': '1',
  786. 'revision_set-INITIAL_FORMS': '0',
  787. 'revision_set-MAX_NUM_FORMS': '',
  788. 'revision_set-0-repository': repository.pk,
  789. 'revision_set-0-revision': '146239817507f148d448db38840db7c3cbf47c76',
  790. 'revision_set-0-DELETE': '',
  791. }
  792. formset = FormSet(data, instance=repository)
  793. self.assertFalse(formset.is_valid())
  794. self.assertEqual(formset.errors, [{'__all__': [u'Revision with this Repository and Revision already exists.']}])
  795. # unique_together with inlineformset_factory with overridden form fields
  796. # Also see #9494
  797. FormSet = inlineformset_factory(Repository, Revision, fields=('revision',), extra=1)
  798. data = {
  799. 'revision_set-TOTAL_FORMS': '1',
  800. 'revision_set-INITIAL_FORMS': '0',
  801. 'revision_set-MAX_NUM_FORMS': '',
  802. 'revision_set-0-repository': repository.pk,
  803. 'reviā€¦

Large files files are truncated, but you can click here to view the full file