tests.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. from __future__ import absolute_import, unicode_literals
  2. from django import forms
  3. from django.contrib.contenttypes.generic import generic_inlineformset_factory
  4. from django.contrib.contenttypes.models import ContentType
  5. from django.test import TestCase
  6. from .models import (TaggedItem, ValuableTaggedItem, Comparison, Animal,
  7. Vegetable, Mineral, Gecko, Rock)
  8. class GenericRelationsTests(TestCase):
  9. def test_generic_relations(self):
  10. # Create the world in 7 lines of code...
  11. lion = Animal.objects.create(common_name="Lion", latin_name="Panthera leo")
  12. platypus = Animal.objects.create(
  13. common_name="Platypus", latin_name="Ornithorhynchus anatinus"
  14. )
  15. eggplant = Vegetable.objects.create(name="Eggplant", is_yucky=True)
  16. bacon = Vegetable.objects.create(name="Bacon", is_yucky=False)
  17. quartz = Mineral.objects.create(name="Quartz", hardness=7)
  18. # Objects with declared GenericRelations can be tagged directly -- the
  19. # API mimics the many-to-many API.
  20. bacon.tags.create(tag="fatty")
  21. bacon.tags.create(tag="salty")
  22. lion.tags.create(tag="yellow")
  23. lion.tags.create(tag="hairy")
  24. platypus.tags.create(tag="fatty")
  25. self.assertQuerysetEqual(lion.tags.all(), [
  26. "<TaggedItem: hairy>",
  27. "<TaggedItem: yellow>"
  28. ])
  29. self.assertQuerysetEqual(bacon.tags.all(), [
  30. "<TaggedItem: fatty>",
  31. "<TaggedItem: salty>"
  32. ])
  33. # You can easily access the content object like a foreign key.
  34. t = TaggedItem.objects.get(tag="salty")
  35. self.assertEqual(t.content_object, bacon)
  36. # Recall that the Mineral class doesn't have an explicit GenericRelation
  37. # defined. That's OK, because you can create TaggedItems explicitly.
  38. tag1 = TaggedItem.objects.create(content_object=quartz, tag="shiny")
  39. tag2 = TaggedItem.objects.create(content_object=quartz, tag="clearish")
  40. # However, excluding GenericRelations means your lookups have to be a
  41. # bit more explicit.
  42. ctype = ContentType.objects.get_for_model(quartz)
  43. q = TaggedItem.objects.filter(
  44. content_type__pk=ctype.id, object_id=quartz.id
  45. )
  46. self.assertQuerysetEqual(q, [
  47. "<TaggedItem: clearish>",
  48. "<TaggedItem: shiny>"
  49. ])
  50. # You can set a generic foreign key in the way you'd expect.
  51. tag1.content_object = platypus
  52. tag1.save()
  53. self.assertQuerysetEqual(platypus.tags.all(), [
  54. "<TaggedItem: fatty>",
  55. "<TaggedItem: shiny>"
  56. ])
  57. q = TaggedItem.objects.filter(
  58. content_type__pk=ctype.id, object_id=quartz.id
  59. )
  60. self.assertQuerysetEqual(q, ["<TaggedItem: clearish>"])
  61. # Queries across generic relations respect the content types. Even
  62. # though there are two TaggedItems with a tag of "fatty", this query
  63. # only pulls out the one with the content type related to Animals.
  64. self.assertQuerysetEqual(Animal.objects.order_by('common_name'), [
  65. "<Animal: Lion>",
  66. "<Animal: Platypus>"
  67. ])
  68. self.assertQuerysetEqual(Animal.objects.filter(tags__tag='fatty'), [
  69. "<Animal: Platypus>"
  70. ])
  71. self.assertQuerysetEqual(Animal.objects.exclude(tags__tag='fatty'), [
  72. "<Animal: Lion>"
  73. ])
  74. # If you delete an object with an explicit Generic relation, the related
  75. # objects are deleted when the source object is deleted.
  76. # Original list of tags:
  77. comp_func = lambda obj: (
  78. obj.tag, obj.content_type.model_class(), obj.object_id
  79. )
  80. self.assertQuerysetEqual(TaggedItem.objects.all(), [
  81. ('clearish', Mineral, quartz.pk),
  82. ('fatty', Animal, platypus.pk),
  83. ('fatty', Vegetable, bacon.pk),
  84. ('hairy', Animal, lion.pk),
  85. ('salty', Vegetable, bacon.pk),
  86. ('shiny', Animal, platypus.pk),
  87. ('yellow', Animal, lion.pk)
  88. ],
  89. comp_func
  90. )
  91. lion.delete()
  92. self.assertQuerysetEqual(TaggedItem.objects.all(), [
  93. ('clearish', Mineral, quartz.pk),
  94. ('fatty', Animal, platypus.pk),
  95. ('fatty', Vegetable, bacon.pk),
  96. ('salty', Vegetable, bacon.pk),
  97. ('shiny', Animal, platypus.pk)
  98. ],
  99. comp_func
  100. )
  101. # If Generic Relation is not explicitly defined, any related objects
  102. # remain after deletion of the source object.
  103. quartz_pk = quartz.pk
  104. quartz.delete()
  105. self.assertQuerysetEqual(TaggedItem.objects.all(), [
  106. ('clearish', Mineral, quartz_pk),
  107. ('fatty', Animal, platypus.pk),
  108. ('fatty', Vegetable, bacon.pk),
  109. ('salty', Vegetable, bacon.pk),
  110. ('shiny', Animal, platypus.pk)
  111. ],
  112. comp_func
  113. )
  114. # If you delete a tag, the objects using the tag are unaffected
  115. # (other than losing a tag)
  116. tag = TaggedItem.objects.order_by("id")[0]
  117. tag.delete()
  118. self.assertQuerysetEqual(bacon.tags.all(), ["<TaggedItem: salty>"])
  119. self.assertQuerysetEqual(TaggedItem.objects.all(), [
  120. ('clearish', Mineral, quartz_pk),
  121. ('fatty', Animal, platypus.pk),
  122. ('salty', Vegetable, bacon.pk),
  123. ('shiny', Animal, platypus.pk)
  124. ],
  125. comp_func
  126. )
  127. TaggedItem.objects.filter(tag='fatty').delete()
  128. ctype = ContentType.objects.get_for_model(lion)
  129. self.assertQuerysetEqual(Animal.objects.filter(tags__content_type=ctype), [
  130. "<Animal: Platypus>"
  131. ])
  132. def test_multiple_gfk(self):
  133. # Simple tests for multiple GenericForeignKeys
  134. # only uses one model, since the above tests should be sufficient.
  135. tiger = Animal.objects.create(common_name="tiger")
  136. cheetah = Animal.objects.create(common_name="cheetah")
  137. bear = Animal.objects.create(common_name="bear")
  138. # Create directly
  139. Comparison.objects.create(
  140. first_obj=cheetah, other_obj=tiger, comparative="faster"
  141. )
  142. Comparison.objects.create(
  143. first_obj=tiger, other_obj=cheetah, comparative="cooler"
  144. )
  145. # Create using GenericRelation
  146. tiger.comparisons.create(other_obj=bear, comparative="cooler")
  147. tiger.comparisons.create(other_obj=cheetah, comparative="stronger")
  148. self.assertQuerysetEqual(cheetah.comparisons.all(), [
  149. "<Comparison: cheetah is faster than tiger>"
  150. ])
  151. # Filtering works
  152. self.assertQuerysetEqual(tiger.comparisons.filter(comparative="cooler"), [
  153. "<Comparison: tiger is cooler than cheetah>",
  154. "<Comparison: tiger is cooler than bear>",
  155. ], ordered=False)
  156. # Filtering and deleting works
  157. subjective = ["cooler"]
  158. tiger.comparisons.filter(comparative__in=subjective).delete()
  159. self.assertQuerysetEqual(Comparison.objects.all(), [
  160. "<Comparison: cheetah is faster than tiger>",
  161. "<Comparison: tiger is stronger than cheetah>"
  162. ], ordered=False)
  163. # If we delete cheetah, Comparisons with cheetah as 'first_obj' will be
  164. # deleted since Animal has an explicit GenericRelation to Comparison
  165. # through first_obj. Comparisons with cheetah as 'other_obj' will not
  166. # be deleted.
  167. cheetah.delete()
  168. self.assertQuerysetEqual(Comparison.objects.all(), [
  169. "<Comparison: tiger is stronger than None>"
  170. ])
  171. def test_gfk_subclasses(self):
  172. # GenericForeignKey should work with subclasses (see #8309)
  173. quartz = Mineral.objects.create(name="Quartz", hardness=7)
  174. valuedtag = ValuableTaggedItem.objects.create(
  175. content_object=quartz, tag="shiny", value=10
  176. )
  177. self.assertEqual(valuedtag.content_object, quartz)
  178. def test_generic_inline_formsets(self):
  179. GenericFormSet = generic_inlineformset_factory(TaggedItem, extra=1)
  180. formset = GenericFormSet()
  181. 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>
  182. <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>""")
  183. formset = GenericFormSet(instance=Animal())
  184. 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>
  185. <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>""")
  186. platypus = Animal.objects.create(
  187. common_name="Platypus", latin_name="Ornithorhynchus anatinus"
  188. )
  189. platypus.tags.create(tag="shiny")
  190. GenericFormSet = generic_inlineformset_factory(TaggedItem, extra=1)
  191. formset = GenericFormSet(instance=platypus)
  192. tagged_item_id = TaggedItem.objects.get(
  193. tag='shiny', object_id=platypus.id
  194. ).id
  195. 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>
  196. <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>
  197. <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)
  198. lion = Animal.objects.create(common_name="Lion", latin_name="Panthera leo")
  199. formset = GenericFormSet(instance=lion, prefix='x')
  200. 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>
  201. <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>""")
  202. def test_gfk_manager(self):
  203. # GenericForeignKey should not use the default manager (which may filter objects) #16048
  204. tailless = Gecko.objects.create(has_tail=False)
  205. tag = TaggedItem.objects.create(content_object=tailless, tag="lizard")
  206. self.assertEqual(tag.content_object, tailless)
  207. def test_subclasses_with_gen_rel(self):
  208. """
  209. Test that concrete model subclasses with generic relations work
  210. correctly (ticket 11263).
  211. """
  212. granite = Rock.objects.create(name='granite', hardness=5)
  213. TaggedItem.objects.create(content_object=granite, tag="countertop")
  214. self.assertEqual(Rock.objects.filter(tags__tag="countertop").count(), 1)
  215. class CustomWidget(forms.TextInput):
  216. pass
  217. class TaggedItemForm(forms.ModelForm):
  218. class Meta:
  219. model = TaggedItem
  220. fields = '__all__'
  221. widgets = {'tag': CustomWidget}
  222. class GenericInlineFormsetTest(TestCase):
  223. """
  224. Regression for #14572: Using base forms with widgets
  225. defined in Meta should not raise errors.
  226. """
  227. def test_generic_inlineformset_factory(self):
  228. Formset = generic_inlineformset_factory(TaggedItem, TaggedItemForm)
  229. form = Formset().forms[0]
  230. self.assertTrue(isinstance(form['tag'].field.widget, CustomWidget))