tests.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. from __future__ import unicode_literals
  2. from django import forms
  3. from django.contrib.contenttypes.forms import generic_inlineformset_factory
  4. from django.contrib.contenttypes.models import ContentType
  5. from django.core.exceptions import FieldError
  6. from django.db import IntegrityError
  7. from django.db.models import Q
  8. from django.test import SimpleTestCase, TestCase
  9. from django.utils import six
  10. from .models import (
  11. AllowsNullGFK, Animal, Comparison, ConcreteRelatedModel,
  12. ForConcreteModelModel, ForProxyModelModel, Gecko, ManualPK, Mineral,
  13. ProxyRelatedModel, Rock, TaggedItem, ValuableTaggedItem, Vegetable,
  14. )
  15. class GenericRelationsTests(TestCase):
  16. def setUp(self):
  17. self.lion = Animal.objects.create(
  18. common_name="Lion", latin_name="Panthera leo")
  19. self.platypus = Animal.objects.create(
  20. common_name="Platypus", latin_name="Ornithorhynchus anatinus")
  21. Vegetable.objects.create(name="Eggplant", is_yucky=True)
  22. self.bacon = Vegetable.objects.create(name="Bacon", is_yucky=False)
  23. self.quartz = Mineral.objects.create(name="Quartz", hardness=7)
  24. # Tagging stuff.
  25. self.bacon.tags.create(tag="fatty")
  26. self.bacon.tags.create(tag="salty")
  27. self.lion.tags.create(tag="yellow")
  28. self.lion.tags.create(tag="hairy")
  29. # Original list of tags:
  30. self.comp_func = lambda obj: (
  31. obj.tag, obj.content_type.model_class(), obj.object_id
  32. )
  33. def test_generic_update_or_create_when_created(self):
  34. """
  35. Should be able to use update_or_create from the generic related manager
  36. to create a tag. Refs #23611.
  37. """
  38. count = self.bacon.tags.count()
  39. tag, created = self.bacon.tags.update_or_create(tag='stinky')
  40. self.assertTrue(created)
  41. self.assertEqual(count + 1, self.bacon.tags.count())
  42. def test_generic_update_or_create_when_updated(self):
  43. """
  44. Should be able to use update_or_create from the generic related manager
  45. to update a tag. Refs #23611.
  46. """
  47. count = self.bacon.tags.count()
  48. tag = self.bacon.tags.create(tag='stinky')
  49. self.assertEqual(count + 1, self.bacon.tags.count())
  50. tag, created = self.bacon.tags.update_or_create(defaults={'tag': 'juicy'}, id=tag.id)
  51. self.assertFalse(created)
  52. self.assertEqual(count + 1, self.bacon.tags.count())
  53. self.assertEqual(tag.tag, 'juicy')
  54. def test_generic_get_or_create_when_created(self):
  55. """
  56. Should be able to use get_or_create from the generic related manager
  57. to create a tag. Refs #23611.
  58. """
  59. count = self.bacon.tags.count()
  60. tag, created = self.bacon.tags.get_or_create(tag='stinky')
  61. self.assertTrue(created)
  62. self.assertEqual(count + 1, self.bacon.tags.count())
  63. def test_generic_get_or_create_when_exists(self):
  64. """
  65. Should be able to use get_or_create from the generic related manager
  66. to get a tag. Refs #23611.
  67. """
  68. count = self.bacon.tags.count()
  69. tag = self.bacon.tags.create(tag="stinky")
  70. self.assertEqual(count + 1, self.bacon.tags.count())
  71. tag, created = self.bacon.tags.get_or_create(id=tag.id, defaults={'tag': 'juicy'})
  72. self.assertFalse(created)
  73. self.assertEqual(count + 1, self.bacon.tags.count())
  74. # shouldn't had changed the tag
  75. self.assertEqual(tag.tag, 'stinky')
  76. def test_generic_relations_m2m_mimic(self):
  77. """
  78. Objects with declared GenericRelations can be tagged directly -- the
  79. API mimics the many-to-many API.
  80. """
  81. self.assertQuerysetEqual(self.lion.tags.all(), [
  82. "<TaggedItem: hairy>",
  83. "<TaggedItem: yellow>"
  84. ])
  85. self.assertQuerysetEqual(self.bacon.tags.all(), [
  86. "<TaggedItem: fatty>",
  87. "<TaggedItem: salty>"
  88. ])
  89. def test_access_content_object(self):
  90. """
  91. Test accessing the content object like a foreign key.
  92. """
  93. tagged_item = TaggedItem.objects.get(tag="salty")
  94. self.assertEqual(tagged_item.content_object, self.bacon)
  95. def test_query_content_object(self):
  96. qs = TaggedItem.objects.filter(
  97. animal__isnull=False).order_by('animal__common_name', 'tag')
  98. self.assertQuerysetEqual(
  99. qs, ["<TaggedItem: hairy>", "<TaggedItem: yellow>"]
  100. )
  101. mpk = ManualPK.objects.create(id=1)
  102. mpk.tags.create(tag='mpk')
  103. qs = TaggedItem.objects.filter(
  104. Q(animal__isnull=False) | Q(manualpk__id=1)).order_by('tag')
  105. self.assertQuerysetEqual(
  106. qs, ["hairy", "mpk", "yellow"], lambda x: x.tag)
  107. def test_exclude_generic_relations(self):
  108. """
  109. Test lookups over an object without GenericRelations.
  110. """
  111. # Recall that the Mineral class doesn't have an explicit GenericRelation
  112. # defined. That's OK, because you can create TaggedItems explicitly.
  113. # However, excluding GenericRelations means your lookups have to be a
  114. # bit more explicit.
  115. TaggedItem.objects.create(content_object=self.quartz, tag="shiny")
  116. TaggedItem.objects.create(content_object=self.quartz, tag="clearish")
  117. ctype = ContentType.objects.get_for_model(self.quartz)
  118. q = TaggedItem.objects.filter(
  119. content_type__pk=ctype.id, object_id=self.quartz.id
  120. )
  121. self.assertQuerysetEqual(q, [
  122. "<TaggedItem: clearish>",
  123. "<TaggedItem: shiny>"
  124. ])
  125. def test_access_via_content_type(self):
  126. """
  127. Test lookups through content type.
  128. """
  129. self.lion.delete()
  130. self.platypus.tags.create(tag="fatty")
  131. ctype = ContentType.objects.get_for_model(self.platypus)
  132. self.assertQuerysetEqual(
  133. Animal.objects.filter(tags__content_type=ctype),
  134. ["<Animal: Platypus>"])
  135. def test_set_foreign_key(self):
  136. """
  137. You can set a generic foreign key in the way you'd expect.
  138. """
  139. tag1 = TaggedItem.objects.create(content_object=self.quartz, tag="shiny")
  140. tag1.content_object = self.platypus
  141. tag1.save()
  142. self.assertQuerysetEqual(
  143. self.platypus.tags.all(),
  144. ["<TaggedItem: shiny>"])
  145. def test_queries_across_generic_relations(self):
  146. """
  147. Queries across generic relations respect the content types. Even though
  148. there are two TaggedItems with a tag of "fatty", this query only pulls
  149. out the one with the content type related to Animals.
  150. """
  151. self.assertQuerysetEqual(Animal.objects.order_by('common_name'), [
  152. "<Animal: Lion>",
  153. "<Animal: Platypus>"
  154. ])
  155. def test_queries_content_type_restriction(self):
  156. """
  157. Create another fatty tagged instance with different PK to ensure there
  158. is a content type restriction in the generated queries below.
  159. """
  160. mpk = ManualPK.objects.create(id=self.lion.pk)
  161. mpk.tags.create(tag="fatty")
  162. self.platypus.tags.create(tag="fatty")
  163. self.assertQuerysetEqual(
  164. Animal.objects.filter(tags__tag='fatty'), ["<Animal: Platypus>"])
  165. self.assertQuerysetEqual(
  166. Animal.objects.exclude(tags__tag='fatty'), ["<Animal: Lion>"])
  167. def test_object_deletion_with_generic_relation(self):
  168. """
  169. If you delete an object with an explicit Generic relation, the related
  170. objects are deleted when the source object is deleted.
  171. """
  172. self.assertQuerysetEqual(TaggedItem.objects.all(), [
  173. ('fatty', Vegetable, self.bacon.pk),
  174. ('hairy', Animal, self.lion.pk),
  175. ('salty', Vegetable, self.bacon.pk),
  176. ('yellow', Animal, self.lion.pk)
  177. ],
  178. self.comp_func
  179. )
  180. self.lion.delete()
  181. self.assertQuerysetEqual(TaggedItem.objects.all(), [
  182. ('fatty', Vegetable, self.bacon.pk),
  183. ('salty', Vegetable, self.bacon.pk),
  184. ],
  185. self.comp_func
  186. )
  187. def test_object_deletion_without_generic_relation(self):
  188. """
  189. If Generic Relation is not explicitly defined, any related objects
  190. remain after deletion of the source object.
  191. """
  192. TaggedItem.objects.create(content_object=self.quartz, tag="clearish")
  193. quartz_pk = self.quartz.pk
  194. self.quartz.delete()
  195. self.assertQuerysetEqual(TaggedItem.objects.all(), [
  196. ('clearish', Mineral, quartz_pk),
  197. ('fatty', Vegetable, self.bacon.pk),
  198. ('hairy', Animal, self.lion.pk),
  199. ('salty', Vegetable, self.bacon.pk),
  200. ('yellow', Animal, self.lion.pk),
  201. ],
  202. self.comp_func
  203. )
  204. def test_tag_deletion_related_objects_unaffected(self):
  205. """
  206. If you delete a tag, the objects using the tag are unaffected (other
  207. than losing a tag).
  208. """
  209. ctype = ContentType.objects.get_for_model(self.lion)
  210. tag = TaggedItem.objects.get(
  211. content_type__pk=ctype.id, object_id=self.lion.id, tag="hairy")
  212. tag.delete()
  213. self.assertQuerysetEqual(self.lion.tags.all(), ["<TaggedItem: yellow>"])
  214. self.assertQuerysetEqual(TaggedItem.objects.all(), [
  215. ('fatty', Vegetable, self.bacon.pk),
  216. ('salty', Vegetable, self.bacon.pk),
  217. ('yellow', Animal, self.lion.pk)
  218. ],
  219. self.comp_func
  220. )
  221. def test_add_bulk(self):
  222. bacon = Vegetable.objects.create(name="Bacon", is_yucky=False)
  223. t1 = TaggedItem.objects.create(content_object=self.quartz, tag="shiny")
  224. t2 = TaggedItem.objects.create(content_object=self.quartz, tag="clearish")
  225. # One update() query.
  226. with self.assertNumQueries(1):
  227. bacon.tags.add(t1, t2)
  228. self.assertEqual(t1.content_object, bacon)
  229. self.assertEqual(t2.content_object, bacon)
  230. def test_add_bulk_false(self):
  231. bacon = Vegetable.objects.create(name="Bacon", is_yucky=False)
  232. t1 = TaggedItem.objects.create(content_object=self.quartz, tag="shiny")
  233. t2 = TaggedItem.objects.create(content_object=self.quartz, tag="clearish")
  234. # One save() for each object.
  235. with self.assertNumQueries(2):
  236. bacon.tags.add(t1, t2, bulk=False)
  237. self.assertEqual(t1.content_object, bacon)
  238. self.assertEqual(t2.content_object, bacon)
  239. def test_add_rejects_unsaved_objects(self):
  240. t1 = TaggedItem(content_object=self.quartz, tag="shiny")
  241. msg = "<TaggedItem: shiny> instance isn't saved. Use bulk=False or save the object first."
  242. with self.assertRaisesMessage(ValueError, msg):
  243. self.bacon.tags.add(t1)
  244. def test_set(self):
  245. bacon = Vegetable.objects.create(name="Bacon", is_yucky=False)
  246. fatty = bacon.tags.create(tag="fatty")
  247. salty = bacon.tags.create(tag="salty")
  248. bacon.tags.set([fatty, salty])
  249. self.assertQuerysetEqual(bacon.tags.all(), [
  250. "<TaggedItem: fatty>",
  251. "<TaggedItem: salty>",
  252. ])
  253. bacon.tags.set([fatty])
  254. self.assertQuerysetEqual(bacon.tags.all(), [
  255. "<TaggedItem: fatty>",
  256. ])
  257. bacon.tags.set([])
  258. self.assertQuerysetEqual(bacon.tags.all(), [])
  259. bacon.tags.set([fatty, salty], bulk=False, clear=True)
  260. self.assertQuerysetEqual(bacon.tags.all(), [
  261. "<TaggedItem: fatty>",
  262. "<TaggedItem: salty>",
  263. ])
  264. bacon.tags.set([fatty], bulk=False, clear=True)
  265. self.assertQuerysetEqual(bacon.tags.all(), [
  266. "<TaggedItem: fatty>",
  267. ])
  268. bacon.tags.set([], clear=True)
  269. self.assertQuerysetEqual(bacon.tags.all(), [])
  270. def test_assign(self):
  271. bacon = Vegetable.objects.create(name="Bacon", is_yucky=False)
  272. fatty = bacon.tags.create(tag="fatty")
  273. salty = bacon.tags.create(tag="salty")
  274. bacon.tags = [fatty, salty]
  275. self.assertQuerysetEqual(bacon.tags.all(), [
  276. "<TaggedItem: fatty>",
  277. "<TaggedItem: salty>",
  278. ])
  279. bacon.tags = [fatty]
  280. self.assertQuerysetEqual(bacon.tags.all(), [
  281. "<TaggedItem: fatty>",
  282. ])
  283. bacon.tags = []
  284. self.assertQuerysetEqual(bacon.tags.all(), [])
  285. def test_assign_with_queryset(self):
  286. # Ensure that querysets used in reverse GFK assignments are pre-evaluated
  287. # so their value isn't affected by the clearing operation in
  288. # ManyRelatedObjectsDescriptor.__set__. Refs #19816.
  289. bacon = Vegetable.objects.create(name="Bacon", is_yucky=False)
  290. bacon.tags.create(tag="fatty")
  291. bacon.tags.create(tag="salty")
  292. self.assertEqual(2, bacon.tags.count())
  293. qs = bacon.tags.filter(tag="fatty")
  294. bacon.tags = qs
  295. self.assertEqual(1, bacon.tags.count())
  296. self.assertEqual(1, qs.count())
  297. def test_generic_relation_related_name_default(self):
  298. # Test that GenericRelation by default isn't usable from
  299. # the reverse side.
  300. with self.assertRaises(FieldError):
  301. TaggedItem.objects.filter(vegetable__isnull=True)
  302. def test_multiple_gfk(self):
  303. # Simple tests for multiple GenericForeignKeys
  304. # only uses one model, since the above tests should be sufficient.
  305. tiger = Animal.objects.create(common_name="tiger")
  306. cheetah = Animal.objects.create(common_name="cheetah")
  307. bear = Animal.objects.create(common_name="bear")
  308. # Create directly
  309. Comparison.objects.create(
  310. first_obj=cheetah, other_obj=tiger, comparative="faster"
  311. )
  312. Comparison.objects.create(
  313. first_obj=tiger, other_obj=cheetah, comparative="cooler"
  314. )
  315. # Create using GenericRelation
  316. tiger.comparisons.create(other_obj=bear, comparative="cooler")
  317. tiger.comparisons.create(other_obj=cheetah, comparative="stronger")
  318. self.assertQuerysetEqual(cheetah.comparisons.all(), [
  319. "<Comparison: cheetah is faster than tiger>"
  320. ])
  321. # Filtering works
  322. self.assertQuerysetEqual(tiger.comparisons.filter(comparative="cooler"), [
  323. "<Comparison: tiger is cooler than cheetah>",
  324. "<Comparison: tiger is cooler than bear>",
  325. ], ordered=False)
  326. # Filtering and deleting works
  327. subjective = ["cooler"]
  328. tiger.comparisons.filter(comparative__in=subjective).delete()
  329. self.assertQuerysetEqual(Comparison.objects.all(), [
  330. "<Comparison: cheetah is faster than tiger>",
  331. "<Comparison: tiger is stronger than cheetah>"
  332. ], ordered=False)
  333. # If we delete cheetah, Comparisons with cheetah as 'first_obj' will be
  334. # deleted since Animal has an explicit GenericRelation to Comparison
  335. # through first_obj. Comparisons with cheetah as 'other_obj' will not
  336. # be deleted.
  337. cheetah.delete()
  338. self.assertQuerysetEqual(Comparison.objects.all(), [
  339. "<Comparison: tiger is stronger than None>"
  340. ])
  341. def test_gfk_subclasses(self):
  342. # GenericForeignKey should work with subclasses (see #8309)
  343. quartz = Mineral.objects.create(name="Quartz", hardness=7)
  344. valuedtag = ValuableTaggedItem.objects.create(
  345. content_object=quartz, tag="shiny", value=10
  346. )
  347. self.assertEqual(valuedtag.content_object, quartz)
  348. def test_generic_inline_formsets(self):
  349. GenericFormSet = generic_inlineformset_factory(TaggedItem, extra=1)
  350. formset = GenericFormSet()
  351. self.assertHTMLEqual(''.join(form.as_p() for form in formset.forms), """<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag">Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" maxlength="50" /></p>
  352. <p><label for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">Delete:</label> <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE" /><input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id" id="id_generic_relations-taggeditem-content_type-object_id-0-id" /></p>""")
  353. formset = GenericFormSet(instance=Animal())
  354. self.assertHTMLEqual(''.join(form.as_p() for form in formset.forms), """<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag">Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" maxlength="50" /></p>
  355. <p><label for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">Delete:</label> <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE" /><input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id" id="id_generic_relations-taggeditem-content_type-object_id-0-id" /></p>""")
  356. platypus = Animal.objects.create(
  357. common_name="Platypus", latin_name="Ornithorhynchus anatinus"
  358. )
  359. platypus.tags.create(tag="shiny")
  360. GenericFormSet = generic_inlineformset_factory(TaggedItem, extra=1)
  361. formset = GenericFormSet(instance=platypus)
  362. tagged_item_id = TaggedItem.objects.get(
  363. tag='shiny', object_id=platypus.id
  364. ).id
  365. self.assertHTMLEqual(''.join(form.as_p() for form in formset.forms), """<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag">Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" value="shiny" maxlength="50" /></p>
  366. <p><label for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">Delete:</label> <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE" /><input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id" value="%s" id="id_generic_relations-taggeditem-content_type-object_id-0-id" /></p><p><label for="id_generic_relations-taggeditem-content_type-object_id-1-tag">Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-1-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-1-tag" maxlength="50" /></p>
  367. <p><label for="id_generic_relations-taggeditem-content_type-object_id-1-DELETE">Delete:</label> <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-1-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-1-DELETE" /><input type="hidden" name="generic_relations-taggeditem-content_type-object_id-1-id" id="id_generic_relations-taggeditem-content_type-object_id-1-id" /></p>""" % tagged_item_id)
  368. lion = Animal.objects.create(common_name="Lion", latin_name="Panthera leo")
  369. formset = GenericFormSet(instance=lion, prefix='x')
  370. self.assertHTMLEqual(''.join(form.as_p() for form in formset.forms), """<p><label for="id_x-0-tag">Tag:</label> <input id="id_x-0-tag" type="text" name="x-0-tag" maxlength="50" /></p>
  371. <p><label for="id_x-0-DELETE">Delete:</label> <input type="checkbox" name="x-0-DELETE" id="id_x-0-DELETE" /><input type="hidden" name="x-0-id" id="id_x-0-id" /></p>""")
  372. def test_gfk_manager(self):
  373. # GenericForeignKey should not use the default manager (which may filter objects) #16048
  374. tailless = Gecko.objects.create(has_tail=False)
  375. tag = TaggedItem.objects.create(content_object=tailless, tag="lizard")
  376. self.assertEqual(tag.content_object, tailless)
  377. def test_subclasses_with_gen_rel(self):
  378. """
  379. Test that concrete model subclasses with generic relations work
  380. correctly (ticket 11263).
  381. """
  382. granite = Rock.objects.create(name='granite', hardness=5)
  383. TaggedItem.objects.create(content_object=granite, tag="countertop")
  384. self.assertEqual(Rock.objects.filter(tags__tag="countertop").count(), 1)
  385. def test_generic_inline_formsets_initial(self):
  386. """
  387. Test for #17927 Initial values support for BaseGenericInlineFormSet.
  388. """
  389. quartz = Mineral.objects.create(name="Quartz", hardness=7)
  390. GenericFormSet = generic_inlineformset_factory(TaggedItem, extra=1)
  391. ctype = ContentType.objects.get_for_model(quartz)
  392. initial_data = [{
  393. 'tag': 'lizard',
  394. 'content_type': ctype.pk,
  395. 'object_id': quartz.pk,
  396. }]
  397. formset = GenericFormSet(initial=initial_data)
  398. self.assertEqual(formset.forms[0].initial, initial_data[0])
  399. def test_get_or_create(self):
  400. # get_or_create should work with virtual fields (content_object)
  401. quartz = Mineral.objects.create(name="Quartz", hardness=7)
  402. tag, created = TaggedItem.objects.get_or_create(tag="shiny",
  403. defaults={'content_object': quartz})
  404. self.assertTrue(created)
  405. self.assertEqual(tag.tag, "shiny")
  406. self.assertEqual(tag.content_object.id, quartz.id)
  407. def test_update_or_create_defaults(self):
  408. # update_or_create should work with virtual fields (content_object)
  409. quartz = Mineral.objects.create(name="Quartz", hardness=7)
  410. diamond = Mineral.objects.create(name="Diamond", hardness=7)
  411. tag, created = TaggedItem.objects.update_or_create(tag="shiny",
  412. defaults={'content_object': quartz})
  413. self.assertTrue(created)
  414. self.assertEqual(tag.content_object.id, quartz.id)
  415. tag, created = TaggedItem.objects.update_or_create(tag="shiny",
  416. defaults={'content_object': diamond})
  417. self.assertFalse(created)
  418. self.assertEqual(tag.content_object.id, diamond.id)
  419. def test_query_content_type(self):
  420. msg = "Field 'content_object' does not generate an automatic reverse relation"
  421. with self.assertRaisesMessage(FieldError, msg):
  422. TaggedItem.objects.get(content_object='')
  423. def test_unsaved_instance_on_generic_foreign_key(self):
  424. """
  425. Assigning an unsaved object to GenericForeignKey should raise an
  426. exception on model.save().
  427. """
  428. quartz = Mineral(name="Quartz", hardness=7)
  429. with self.assertRaises(IntegrityError):
  430. TaggedItem.objects.create(tag="shiny", content_object=quartz)
  431. class CustomWidget(forms.TextInput):
  432. pass
  433. class TaggedItemForm(forms.ModelForm):
  434. class Meta:
  435. model = TaggedItem
  436. fields = '__all__'
  437. widgets = {'tag': CustomWidget}
  438. class GenericInlineFormsetTest(TestCase):
  439. def test_generic_inlineformset_factory(self):
  440. """
  441. Regression for #14572: Using base forms with widgets
  442. defined in Meta should not raise errors.
  443. """
  444. Formset = generic_inlineformset_factory(TaggedItem, TaggedItemForm)
  445. form = Formset().forms[0]
  446. self.assertIsInstance(form['tag'].field.widget, CustomWidget)
  447. def test_save_new_uses_form_save(self):
  448. """
  449. Regression for #16260: save_new should call form.save()
  450. """
  451. class SaveTestForm(forms.ModelForm):
  452. def save(self, *args, **kwargs):
  453. self.instance.saved_by = "custom method"
  454. return super(SaveTestForm, self).save(*args, **kwargs)
  455. Formset = generic_inlineformset_factory(
  456. ForProxyModelModel, fields='__all__', form=SaveTestForm)
  457. instance = ProxyRelatedModel.objects.create()
  458. data = {
  459. 'form-TOTAL_FORMS': '1',
  460. 'form-INITIAL_FORMS': '0',
  461. 'form-MAX_NUM_FORMS': '',
  462. 'form-0-title': 'foo',
  463. }
  464. formset = Formset(data, instance=instance, prefix='form')
  465. self.assertTrue(formset.is_valid())
  466. new_obj = formset.save()[0]
  467. self.assertEqual(new_obj.saved_by, "custom method")
  468. def test_save_new_for_proxy(self):
  469. Formset = generic_inlineformset_factory(ForProxyModelModel,
  470. fields='__all__', for_concrete_model=False)
  471. instance = ProxyRelatedModel.objects.create()
  472. data = {
  473. 'form-TOTAL_FORMS': '1',
  474. 'form-INITIAL_FORMS': '0',
  475. 'form-MAX_NUM_FORMS': '',
  476. 'form-0-title': 'foo',
  477. }
  478. formset = Formset(data, instance=instance, prefix='form')
  479. self.assertTrue(formset.is_valid())
  480. new_obj, = formset.save()
  481. self.assertEqual(new_obj.obj, instance)
  482. def test_save_new_for_concrete(self):
  483. Formset = generic_inlineformset_factory(ForProxyModelModel,
  484. fields='__all__', for_concrete_model=True)
  485. instance = ProxyRelatedModel.objects.create()
  486. data = {
  487. 'form-TOTAL_FORMS': '1',
  488. 'form-INITIAL_FORMS': '0',
  489. 'form-MAX_NUM_FORMS': '',
  490. 'form-0-title': 'foo',
  491. }
  492. formset = Formset(data, instance=instance, prefix='form')
  493. self.assertTrue(formset.is_valid())
  494. new_obj, = formset.save()
  495. self.assertNotIsInstance(new_obj.obj, ProxyRelatedModel)
  496. class ProxyRelatedModelTest(TestCase):
  497. def test_default_behavior(self):
  498. """
  499. The default for for_concrete_model should be True
  500. """
  501. base = ForConcreteModelModel()
  502. base.obj = rel = ProxyRelatedModel.objects.create()
  503. base.save()
  504. base = ForConcreteModelModel.objects.get(pk=base.pk)
  505. rel = ConcreteRelatedModel.objects.get(pk=rel.pk)
  506. self.assertEqual(base.obj, rel)
  507. def test_works_normally(self):
  508. """
  509. When for_concrete_model is False, we should still be able to get
  510. an instance of the concrete class.
  511. """
  512. base = ForProxyModelModel()
  513. base.obj = rel = ConcreteRelatedModel.objects.create()
  514. base.save()
  515. base = ForProxyModelModel.objects.get(pk=base.pk)
  516. self.assertEqual(base.obj, rel)
  517. def test_proxy_is_returned(self):
  518. """
  519. Instances of the proxy should be returned when
  520. for_concrete_model is False.
  521. """
  522. base = ForProxyModelModel()
  523. base.obj = ProxyRelatedModel.objects.create()
  524. base.save()
  525. base = ForProxyModelModel.objects.get(pk=base.pk)
  526. self.assertIsInstance(base.obj, ProxyRelatedModel)
  527. def test_query(self):
  528. base = ForProxyModelModel()
  529. base.obj = rel = ConcreteRelatedModel.objects.create()
  530. base.save()
  531. self.assertEqual(rel, ConcreteRelatedModel.objects.get(bases__id=base.id))
  532. def test_query_proxy(self):
  533. base = ForProxyModelModel()
  534. base.obj = rel = ProxyRelatedModel.objects.create()
  535. base.save()
  536. self.assertEqual(rel, ProxyRelatedModel.objects.get(bases__id=base.id))
  537. def test_generic_relation(self):
  538. base = ForProxyModelModel()
  539. base.obj = ProxyRelatedModel.objects.create()
  540. base.save()
  541. base = ForProxyModelModel.objects.get(pk=base.pk)
  542. rel = ProxyRelatedModel.objects.get(pk=base.obj.pk)
  543. self.assertEqual(base, rel.bases.get())
  544. def test_generic_relation_set(self):
  545. base = ForProxyModelModel()
  546. base.obj = ConcreteRelatedModel.objects.create()
  547. base.save()
  548. newrel = ConcreteRelatedModel.objects.create()
  549. newrel.bases = [base]
  550. newrel = ConcreteRelatedModel.objects.get(pk=newrel.pk)
  551. self.assertEqual(base, newrel.bases.get())
  552. class TestInitWithNoneArgument(SimpleTestCase):
  553. def test_none_not_allowed(self):
  554. # TaggedItem requires a content_type, initializing with None should
  555. # raise a ValueError.
  556. with six.assertRaisesRegex(self, ValueError,
  557. 'Cannot assign None: "TaggedItem.content_type" does not allow null values'):
  558. TaggedItem(content_object=None)
  559. def test_none_allowed(self):
  560. # AllowsNullGFK doesn't require a content_type, so None argument should
  561. # also be allowed.
  562. AllowsNullGFK(content_object=None)