tests.py 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495
  1. from django.contrib.admin import ModelAdmin, TabularInline
  2. from django.contrib.admin.helpers import InlineAdminForm
  3. from django.contrib.admin.tests import AdminSeleniumTestCase
  4. from django.contrib.auth.models import Permission, User
  5. from django.contrib.contenttypes.models import ContentType
  6. from django.test import RequestFactory, TestCase, override_settings
  7. from django.test.selenium import screenshot_cases
  8. from django.urls import reverse
  9. from django.utils.translation import gettext
  10. from .admin import InnerInline
  11. from .admin import site as admin_site
  12. from .models import (
  13. Author,
  14. BinaryTree,
  15. Book,
  16. BothVerboseNameProfile,
  17. Chapter,
  18. Child,
  19. ChildModel1,
  20. ChildModel2,
  21. Fashionista,
  22. FootNote,
  23. Holder,
  24. Holder2,
  25. Holder3,
  26. Holder4,
  27. Inner,
  28. Inner2,
  29. Inner3,
  30. Inner4Stacked,
  31. Inner4Tabular,
  32. Novel,
  33. OutfitItem,
  34. Parent,
  35. ParentModelWithCustomPk,
  36. Person,
  37. Poll,
  38. Profile,
  39. ProfileCollection,
  40. Question,
  41. ShowInlineParent,
  42. Sighting,
  43. SomeChildModel,
  44. SomeParentModel,
  45. Teacher,
  46. UUIDChild,
  47. UUIDParent,
  48. VerboseNamePluralProfile,
  49. VerboseNameProfile,
  50. )
  51. INLINE_CHANGELINK_HTML = 'class="inlinechangelink">Change</a>'
  52. class TestDataMixin:
  53. @classmethod
  54. def setUpTestData(cls):
  55. cls.superuser = User.objects.create_superuser(
  56. username="super", email="super@example.com", password="secret"
  57. )
  58. @override_settings(ROOT_URLCONF="admin_inlines.urls")
  59. class TestInline(TestDataMixin, TestCase):
  60. factory = RequestFactory()
  61. @classmethod
  62. def setUpTestData(cls):
  63. super().setUpTestData()
  64. cls.holder = Holder.objects.create(dummy=13)
  65. Inner.objects.create(dummy=42, holder=cls.holder)
  66. cls.parent = SomeParentModel.objects.create(name="a")
  67. SomeChildModel.objects.create(name="b", position="0", parent=cls.parent)
  68. SomeChildModel.objects.create(name="c", position="1", parent=cls.parent)
  69. cls.view_only_user = User.objects.create_user(
  70. username="user",
  71. password="pwd",
  72. is_staff=True,
  73. )
  74. parent_ct = ContentType.objects.get_for_model(SomeParentModel)
  75. child_ct = ContentType.objects.get_for_model(SomeChildModel)
  76. permission = Permission.objects.get(
  77. codename="view_someparentmodel",
  78. content_type=parent_ct,
  79. )
  80. cls.view_only_user.user_permissions.add(permission)
  81. permission = Permission.objects.get(
  82. codename="view_somechildmodel",
  83. content_type=child_ct,
  84. )
  85. cls.view_only_user.user_permissions.add(permission)
  86. def setUp(self):
  87. self.client.force_login(self.superuser)
  88. def test_can_delete(self):
  89. """
  90. can_delete should be passed to inlineformset factory.
  91. """
  92. response = self.client.get(
  93. reverse("admin:admin_inlines_holder_change", args=(self.holder.id,))
  94. )
  95. inner_formset = response.context["inline_admin_formsets"][0].formset
  96. expected = InnerInline.can_delete
  97. actual = inner_formset.can_delete
  98. self.assertEqual(expected, actual, "can_delete must be equal")
  99. def test_readonly_stacked_inline_label(self):
  100. """Bug #13174."""
  101. holder = Holder.objects.create(dummy=42)
  102. Inner.objects.create(holder=holder, dummy=42, readonly="")
  103. response = self.client.get(
  104. reverse("admin:admin_inlines_holder_change", args=(holder.id,))
  105. )
  106. self.assertContains(response, "<label>Inner readonly label:</label>")
  107. def test_excluded_id_for_inlines_uses_hidden_field(self):
  108. parent = UUIDParent.objects.create()
  109. child = UUIDChild.objects.create(title="foo", parent=parent)
  110. response = self.client.get(
  111. reverse("admin:admin_inlines_uuidparent_change", args=(parent.id,))
  112. )
  113. self.assertContains(
  114. response,
  115. f'<input type="hidden" name="uuidchild_set-0-id" value="{child.id}" '
  116. 'id="id_uuidchild_set-0-id">',
  117. html=True,
  118. )
  119. def test_many_to_many_inlines(self):
  120. "Autogenerated many-to-many inlines are displayed correctly (#13407)"
  121. response = self.client.get(reverse("admin:admin_inlines_author_add"))
  122. # The heading for the m2m inline block uses the right text
  123. self.assertContains(
  124. response,
  125. (
  126. '<h2 id="Author_books-heading" class="inline-heading">'
  127. "Author-book relationships</h2>"
  128. ),
  129. html=True,
  130. )
  131. # The "add another" label is correct
  132. self.assertContains(response, "Add another Author-book relationship")
  133. # The '+' is dropped from the autogenerated form prefix (Author_books+)
  134. self.assertContains(response, 'id="id_Author_books-TOTAL_FORMS"')
  135. def test_inline_primary(self):
  136. person = Person.objects.create(firstname="Imelda")
  137. item = OutfitItem.objects.create(name="Shoes")
  138. # Imelda likes shoes, but can't carry her own bags.
  139. data = {
  140. "shoppingweakness_set-TOTAL_FORMS": 1,
  141. "shoppingweakness_set-INITIAL_FORMS": 0,
  142. "shoppingweakness_set-MAX_NUM_FORMS": 0,
  143. "_save": "Save",
  144. "person": person.id,
  145. "max_weight": 0,
  146. "shoppingweakness_set-0-item": item.id,
  147. }
  148. response = self.client.post(
  149. reverse("admin:admin_inlines_fashionista_add"), data
  150. )
  151. self.assertEqual(response.status_code, 302)
  152. self.assertEqual(len(Fashionista.objects.filter(person__firstname="Imelda")), 1)
  153. def test_tabular_inline_column_css_class(self):
  154. """
  155. Field names are included in the context to output a field-specific
  156. CSS class name in the column headers.
  157. """
  158. response = self.client.get(reverse("admin:admin_inlines_poll_add"))
  159. text_field, call_me_field = list(
  160. response.context["inline_admin_formset"].fields()
  161. )
  162. # Editable field.
  163. self.assertEqual(text_field["name"], "text")
  164. self.assertContains(response, '<th class="column-text required">')
  165. # Read-only field.
  166. self.assertEqual(call_me_field["name"], "call_me")
  167. self.assertContains(response, '<th class="column-call_me">')
  168. def test_custom_form_tabular_inline_label(self):
  169. """
  170. A model form with a form field specified (TitleForm.title1) should have
  171. its label rendered in the tabular inline.
  172. """
  173. response = self.client.get(reverse("admin:admin_inlines_titlecollection_add"))
  174. self.assertContains(
  175. response, '<th class="column-title1 required">Title1</th>', html=True
  176. )
  177. def test_custom_form_tabular_inline_extra_field_label(self):
  178. response = self.client.get(reverse("admin:admin_inlines_outfititem_add"))
  179. _, extra_field = list(response.context["inline_admin_formset"].fields())
  180. self.assertEqual(extra_field["label"], "Extra field")
  181. def test_non_editable_custom_form_tabular_inline_extra_field_label(self):
  182. response = self.client.get(reverse("admin:admin_inlines_chapter_add"))
  183. _, extra_field = list(response.context["inline_admin_formset"].fields())
  184. self.assertEqual(extra_field["label"], "Extra field")
  185. def test_custom_form_tabular_inline_overridden_label(self):
  186. """
  187. SomeChildModelForm.__init__() overrides the label of a form field.
  188. That label is displayed in the TabularInline.
  189. """
  190. response = self.client.get(reverse("admin:admin_inlines_someparentmodel_add"))
  191. field = list(response.context["inline_admin_formset"].fields())[0]
  192. self.assertEqual(field["label"], "new label")
  193. self.assertContains(
  194. response, '<th class="column-name required">New label</th>', html=True
  195. )
  196. def test_tabular_non_field_errors(self):
  197. """
  198. non_field_errors are displayed correctly, including the correct value
  199. for colspan.
  200. """
  201. data = {
  202. "title_set-TOTAL_FORMS": 1,
  203. "title_set-INITIAL_FORMS": 0,
  204. "title_set-MAX_NUM_FORMS": 0,
  205. "_save": "Save",
  206. "title_set-0-title1": "a title",
  207. "title_set-0-title2": "a different title",
  208. }
  209. response = self.client.post(
  210. reverse("admin:admin_inlines_titlecollection_add"), data
  211. )
  212. # Here colspan is "4": two fields (title1 and title2), one hidden field
  213. # and the delete checkbox.
  214. self.assertContains(
  215. response,
  216. '<tr class="row-form-errors"><td colspan="4">'
  217. '<ul class="errorlist nonfield">'
  218. "<li>The two titles must be the same</li></ul></td></tr>",
  219. )
  220. def test_no_parent_callable_lookup(self):
  221. """Admin inline `readonly_field` shouldn't invoke parent ModelAdmin callable"""
  222. # Identically named callable isn't present in the parent ModelAdmin,
  223. # rendering of the add view shouldn't explode
  224. response = self.client.get(reverse("admin:admin_inlines_novel_add"))
  225. # View should have the child inlines section
  226. self.assertContains(
  227. response,
  228. '<div class="js-inline-admin-formset inline-group" id="chapter_set-group"',
  229. )
  230. def test_callable_lookup(self):
  231. """
  232. Admin inline should invoke local callable when its name is listed in
  233. readonly_fields.
  234. """
  235. response = self.client.get(reverse("admin:admin_inlines_poll_add"))
  236. # Add parent object view should have the child inlines section
  237. self.assertContains(
  238. response,
  239. '<div class="js-inline-admin-formset inline-group" id="question_set-group"',
  240. )
  241. # The right callable should be used for the inline readonly_fields
  242. # column cells
  243. self.assertContains(response, "<p>Callable in QuestionInline</p>")
  244. def test_model_error_inline_with_readonly_field(self):
  245. poll = Poll.objects.create(name="Test poll")
  246. data = {
  247. "question_set-TOTAL_FORMS": 1,
  248. "question_set-INITIAL_FORMS": 0,
  249. "question_set-MAX_NUM_FORMS": 0,
  250. "_save": "Save",
  251. "question_set-0-text": "Question",
  252. "question_set-0-poll": poll.pk,
  253. }
  254. response = self.client.post(
  255. reverse("admin:admin_inlines_poll_change", args=(poll.pk,)),
  256. data,
  257. )
  258. self.assertContains(response, "Always invalid model.")
  259. def test_help_text(self):
  260. """
  261. The inlines' model field help texts are displayed when using both the
  262. stacked and tabular layouts.
  263. """
  264. response = self.client.get(reverse("admin:admin_inlines_holder4_add"))
  265. self.assertContains(response, "Awesome stacked help text is awesome.", 4)
  266. self.assertContains(
  267. response,
  268. '<img src="/static/admin/img/icon-unknown.svg" '
  269. 'class="help help-tooltip" width="10" height="10" '
  270. 'alt="(Awesome tabular help text is awesome.)" '
  271. 'title="Awesome tabular help text is awesome.">',
  272. 1,
  273. )
  274. # ReadOnly fields
  275. response = self.client.get(reverse("admin:admin_inlines_capofamiglia_add"))
  276. self.assertContains(
  277. response,
  278. '<img src="/static/admin/img/icon-unknown.svg" '
  279. 'class="help help-tooltip" width="10" height="10" '
  280. 'alt="(Help text for ReadOnlyInline)" '
  281. 'title="Help text for ReadOnlyInline">',
  282. 1,
  283. )
  284. def test_tabular_model_form_meta_readonly_field(self):
  285. """
  286. Tabular inlines use ModelForm.Meta.help_texts and labels for read-only
  287. fields.
  288. """
  289. response = self.client.get(reverse("admin:admin_inlines_someparentmodel_add"))
  290. self.assertContains(
  291. response,
  292. '<img src="/static/admin/img/icon-unknown.svg" '
  293. 'class="help help-tooltip" width="10" height="10" '
  294. 'alt="(Help text from ModelForm.Meta)" '
  295. 'title="Help text from ModelForm.Meta">',
  296. )
  297. self.assertContains(response, "Label from ModelForm.Meta")
  298. def test_inline_hidden_field_no_column(self):
  299. """#18263 -- Make sure hidden fields don't get a column in tabular inlines"""
  300. parent = SomeParentModel.objects.create(name="a")
  301. SomeChildModel.objects.create(name="b", position="0", parent=parent)
  302. SomeChildModel.objects.create(name="c", position="1", parent=parent)
  303. response = self.client.get(
  304. reverse("admin:admin_inlines_someparentmodel_change", args=(parent.pk,))
  305. )
  306. self.assertNotContains(response, '<td class="field-position">')
  307. self.assertInHTML(
  308. '<input id="id_somechildmodel_set-1-position" '
  309. 'name="somechildmodel_set-1-position" type="hidden" value="1">',
  310. response.rendered_content,
  311. )
  312. def test_tabular_inline_hidden_field_with_view_only_permissions(self):
  313. """
  314. Content of hidden field is not visible in tabular inline when user has
  315. view-only permission.
  316. """
  317. self.client.force_login(self.view_only_user)
  318. url = reverse(
  319. "tabular_inline_hidden_field_admin:admin_inlines_someparentmodel_change",
  320. args=(self.parent.pk,),
  321. )
  322. response = self.client.get(url)
  323. self.assertInHTML(
  324. '<th class="column-position hidden">Position'
  325. '<img src="/static/admin/img/icon-unknown.svg" '
  326. 'class="help help-tooltip" width="10" height="10" '
  327. 'alt="(Position help_text.)" '
  328. 'title="Position help_text.">'
  329. "</th>",
  330. response.rendered_content,
  331. )
  332. self.assertInHTML(
  333. '<td class="field-position hidden"><p>0</p></td>', response.rendered_content
  334. )
  335. self.assertInHTML(
  336. '<td class="field-position hidden"><p>1</p></td>', response.rendered_content
  337. )
  338. def test_stacked_inline_hidden_field_with_view_only_permissions(self):
  339. """
  340. Content of hidden field is not visible in stacked inline when user has
  341. view-only permission.
  342. """
  343. self.client.force_login(self.view_only_user)
  344. url = reverse(
  345. "stacked_inline_hidden_field_in_group_admin:"
  346. "admin_inlines_someparentmodel_change",
  347. args=(self.parent.pk,),
  348. )
  349. response = self.client.get(url)
  350. # The whole line containing name + position fields is not hidden.
  351. self.assertContains(
  352. response, '<div class="form-row field-name field-position">'
  353. )
  354. # The div containing the position field is hidden.
  355. self.assertInHTML(
  356. '<div class="flex-container fieldBox field-position hidden">'
  357. '<label class="inline">Position:</label>'
  358. '<div class="readonly">0</div></div>'
  359. '<div class="help hidden"><div>Position help_text.</div></div>',
  360. response.rendered_content,
  361. )
  362. self.assertInHTML(
  363. '<div class="flex-container fieldBox field-position hidden">'
  364. '<label class="inline">Position:</label>'
  365. '<div class="readonly">1</div></div>'
  366. '<div class="help hidden"><div>Position help_text.</div></div>',
  367. response.rendered_content,
  368. )
  369. def test_stacked_inline_single_hidden_field_in_line_with_view_only_permissions(
  370. self,
  371. ):
  372. """
  373. Content of hidden field is not visible in stacked inline when user has
  374. view-only permission and the field is grouped on a separate line.
  375. """
  376. self.client.force_login(self.view_only_user)
  377. url = reverse(
  378. "stacked_inline_hidden_field_on_single_line_admin:"
  379. "admin_inlines_someparentmodel_change",
  380. args=(self.parent.pk,),
  381. )
  382. response = self.client.get(url)
  383. # The whole line containing position field is hidden.
  384. self.assertInHTML(
  385. '<div class="form-row hidden field-position">'
  386. '<div><div class="flex-container"><label>Position:</label>'
  387. '<div class="readonly">0</div></div>'
  388. '<div class="help hidden"><div>Position help_text.</div></div>'
  389. "</div></div>",
  390. response.rendered_content,
  391. )
  392. self.assertInHTML(
  393. '<div class="form-row hidden field-position">'
  394. '<div><div class="flex-container"><label>Position:</label>'
  395. '<div class="readonly">1</div></div>'
  396. '<div class="help hidden"><div>Position help_text.</div></div>'
  397. "</div></div>",
  398. response.rendered_content,
  399. )
  400. def test_tabular_inline_with_hidden_field_non_field_errors_has_correct_colspan(
  401. self,
  402. ):
  403. """
  404. In tabular inlines, when a form has non-field errors, those errors
  405. are rendered in a table line with a single cell spanning the whole
  406. table width. Colspan must be equal to the number of visible columns.
  407. """
  408. parent = SomeParentModel.objects.create(name="a")
  409. child = SomeChildModel.objects.create(name="b", position="0", parent=parent)
  410. url = reverse(
  411. "tabular_inline_hidden_field_admin:admin_inlines_someparentmodel_change",
  412. args=(parent.id,),
  413. )
  414. data = {
  415. "name": parent.name,
  416. "somechildmodel_set-TOTAL_FORMS": 1,
  417. "somechildmodel_set-INITIAL_FORMS": 1,
  418. "somechildmodel_set-MIN_NUM_FORMS": 0,
  419. "somechildmodel_set-MAX_NUM_FORMS": 1000,
  420. "_save": "Save",
  421. "somechildmodel_set-0-id": child.id,
  422. "somechildmodel_set-0-parent": parent.id,
  423. "somechildmodel_set-0-name": child.name,
  424. "somechildmodel_set-0-position": 1,
  425. }
  426. response = self.client.post(url, data)
  427. # Form has 3 visible columns and 1 hidden column.
  428. self.assertInHTML(
  429. '<thead><tr><th class="original"></th>'
  430. '<th class="column-name required">Name</th>'
  431. '<th class="column-position required hidden">Position'
  432. '<img src="/static/admin/img/icon-unknown.svg" '
  433. 'class="help help-tooltip" width="10" height="10" '
  434. 'alt="(Position help_text.)" '
  435. 'title="Position help_text.">'
  436. "</th>"
  437. "<th>Delete?</th></tr></thead>",
  438. response.rendered_content,
  439. )
  440. # The non-field error must be spanned on 3 (visible) columns.
  441. self.assertInHTML(
  442. '<tr class="row-form-errors"><td colspan="3">'
  443. '<ul class="errorlist nonfield"><li>A non-field error</li></ul></td></tr>',
  444. response.rendered_content,
  445. )
  446. def test_non_related_name_inline(self):
  447. """
  448. Multiple inlines with related_name='+' have correct form prefixes.
  449. """
  450. response = self.client.get(reverse("admin:admin_inlines_capofamiglia_add"))
  451. self.assertContains(
  452. response, '<input type="hidden" name="-1-0-id" id="id_-1-0-id">', html=True
  453. )
  454. self.assertContains(
  455. response,
  456. '<input type="hidden" name="-1-0-capo_famiglia" '
  457. 'id="id_-1-0-capo_famiglia">',
  458. html=True,
  459. )
  460. self.assertContains(
  461. response,
  462. '<input id="id_-1-0-name" type="text" class="vTextField" name="-1-0-name" '
  463. 'maxlength="100" aria-describedby="id_-1-0-name_helptext">',
  464. html=True,
  465. )
  466. self.assertContains(
  467. response, '<input type="hidden" name="-2-0-id" id="id_-2-0-id">', html=True
  468. )
  469. self.assertContains(
  470. response,
  471. '<input type="hidden" name="-2-0-capo_famiglia" '
  472. 'id="id_-2-0-capo_famiglia">',
  473. html=True,
  474. )
  475. self.assertContains(
  476. response,
  477. '<input id="id_-2-0-name" type="text" class="vTextField" name="-2-0-name" '
  478. 'maxlength="100">',
  479. html=True,
  480. )
  481. @override_settings(USE_THOUSAND_SEPARATOR=True)
  482. def test_localize_pk_shortcut(self):
  483. """
  484. The "View on Site" link is correct for locales that use thousand
  485. separators.
  486. """
  487. holder = Holder.objects.create(pk=123456789, dummy=42)
  488. inner = Inner.objects.create(pk=987654321, holder=holder, dummy=42, readonly="")
  489. response = self.client.get(
  490. reverse("admin:admin_inlines_holder_change", args=(holder.id,))
  491. )
  492. inner_shortcut = "r/%s/%s/" % (
  493. ContentType.objects.get_for_model(inner).pk,
  494. inner.pk,
  495. )
  496. self.assertContains(response, inner_shortcut)
  497. def test_custom_pk_shortcut(self):
  498. """
  499. The "View on Site" link is correct for models with a custom primary key
  500. field.
  501. """
  502. parent = ParentModelWithCustomPk.objects.create(my_own_pk="foo", name="Foo")
  503. child1 = ChildModel1.objects.create(my_own_pk="bar", name="Bar", parent=parent)
  504. child2 = ChildModel2.objects.create(my_own_pk="baz", name="Baz", parent=parent)
  505. response = self.client.get(
  506. reverse("admin:admin_inlines_parentmodelwithcustompk_change", args=("foo",))
  507. )
  508. child1_shortcut = "r/%s/%s/" % (
  509. ContentType.objects.get_for_model(child1).pk,
  510. child1.pk,
  511. )
  512. child2_shortcut = "r/%s/%s/" % (
  513. ContentType.objects.get_for_model(child2).pk,
  514. child2.pk,
  515. )
  516. self.assertContains(response, child1_shortcut)
  517. self.assertContains(response, child2_shortcut)
  518. def test_create_inlines_on_inherited_model(self):
  519. """
  520. An object can be created with inlines when it inherits another class.
  521. """
  522. data = {
  523. "name": "Martian",
  524. "sighting_set-TOTAL_FORMS": 1,
  525. "sighting_set-INITIAL_FORMS": 0,
  526. "sighting_set-MAX_NUM_FORMS": 0,
  527. "sighting_set-0-place": "Zone 51",
  528. "_save": "Save",
  529. }
  530. response = self.client.post(
  531. reverse("admin:admin_inlines_extraterrestrial_add"), data
  532. )
  533. self.assertEqual(response.status_code, 302)
  534. self.assertEqual(Sighting.objects.filter(et__name="Martian").count(), 1)
  535. def test_custom_get_extra_form(self):
  536. bt_head = BinaryTree.objects.create(name="Tree Head")
  537. BinaryTree.objects.create(name="First Child", parent=bt_head)
  538. # The maximum number of forms should respect 'get_max_num' on the
  539. # ModelAdmin
  540. max_forms_input = (
  541. '<input id="id_binarytree_set-MAX_NUM_FORMS" '
  542. 'name="binarytree_set-MAX_NUM_FORMS" type="hidden" value="%d">'
  543. )
  544. # The total number of forms will remain the same in either case
  545. total_forms_hidden = (
  546. '<input id="id_binarytree_set-TOTAL_FORMS" '
  547. 'name="binarytree_set-TOTAL_FORMS" type="hidden" value="2">'
  548. )
  549. response = self.client.get(reverse("admin:admin_inlines_binarytree_add"))
  550. self.assertInHTML(max_forms_input % 3, response.rendered_content)
  551. self.assertInHTML(total_forms_hidden, response.rendered_content)
  552. response = self.client.get(
  553. reverse("admin:admin_inlines_binarytree_change", args=(bt_head.id,))
  554. )
  555. self.assertInHTML(max_forms_input % 2, response.rendered_content)
  556. self.assertInHTML(total_forms_hidden, response.rendered_content)
  557. def test_min_num(self):
  558. """
  559. min_num and extra determine number of forms.
  560. """
  561. class MinNumInline(TabularInline):
  562. model = BinaryTree
  563. min_num = 2
  564. extra = 3
  565. modeladmin = ModelAdmin(BinaryTree, admin_site)
  566. modeladmin.inlines = [MinNumInline]
  567. min_forms = (
  568. '<input id="id_binarytree_set-MIN_NUM_FORMS" '
  569. 'name="binarytree_set-MIN_NUM_FORMS" type="hidden" value="2">'
  570. )
  571. total_forms = (
  572. '<input id="id_binarytree_set-TOTAL_FORMS" '
  573. 'name="binarytree_set-TOTAL_FORMS" type="hidden" value="5">'
  574. )
  575. request = self.factory.get(reverse("admin:admin_inlines_binarytree_add"))
  576. request.user = User(username="super", is_superuser=True)
  577. response = modeladmin.changeform_view(request)
  578. self.assertInHTML(min_forms, response.rendered_content)
  579. self.assertInHTML(total_forms, response.rendered_content)
  580. def test_custom_min_num(self):
  581. bt_head = BinaryTree.objects.create(name="Tree Head")
  582. BinaryTree.objects.create(name="First Child", parent=bt_head)
  583. class MinNumInline(TabularInline):
  584. model = BinaryTree
  585. extra = 3
  586. def get_min_num(self, request, obj=None, **kwargs):
  587. if obj:
  588. return 5
  589. return 2
  590. modeladmin = ModelAdmin(BinaryTree, admin_site)
  591. modeladmin.inlines = [MinNumInline]
  592. min_forms = (
  593. '<input id="id_binarytree_set-MIN_NUM_FORMS" '
  594. 'name="binarytree_set-MIN_NUM_FORMS" type="hidden" value="%d">'
  595. )
  596. total_forms = (
  597. '<input id="id_binarytree_set-TOTAL_FORMS" '
  598. 'name="binarytree_set-TOTAL_FORMS" type="hidden" value="%d">'
  599. )
  600. request = self.factory.get(reverse("admin:admin_inlines_binarytree_add"))
  601. request.user = User(username="super", is_superuser=True)
  602. response = modeladmin.changeform_view(request)
  603. self.assertInHTML(min_forms % 2, response.rendered_content)
  604. self.assertInHTML(total_forms % 5, response.rendered_content)
  605. request = self.factory.get(
  606. reverse("admin:admin_inlines_binarytree_change", args=(bt_head.id,))
  607. )
  608. request.user = User(username="super", is_superuser=True)
  609. response = modeladmin.changeform_view(request, object_id=str(bt_head.id))
  610. self.assertInHTML(min_forms % 5, response.rendered_content)
  611. self.assertInHTML(total_forms % 8, response.rendered_content)
  612. def test_inline_nonauto_noneditable_pk(self):
  613. response = self.client.get(reverse("admin:admin_inlines_author_add"))
  614. self.assertContains(
  615. response,
  616. '<input id="id_nonautopkbook_set-0-rand_pk" '
  617. 'name="nonautopkbook_set-0-rand_pk" type="hidden">',
  618. html=True,
  619. )
  620. self.assertContains(
  621. response,
  622. '<input id="id_nonautopkbook_set-2-0-rand_pk" '
  623. 'name="nonautopkbook_set-2-0-rand_pk" type="hidden">',
  624. html=True,
  625. )
  626. def test_inline_nonauto_noneditable_inherited_pk(self):
  627. response = self.client.get(reverse("admin:admin_inlines_author_add"))
  628. self.assertContains(
  629. response,
  630. '<input id="id_nonautopkbookchild_set-0-nonautopkbook_ptr" '
  631. 'name="nonautopkbookchild_set-0-nonautopkbook_ptr" type="hidden">',
  632. html=True,
  633. )
  634. self.assertContains(
  635. response,
  636. '<input id="id_nonautopkbookchild_set-2-nonautopkbook_ptr" '
  637. 'name="nonautopkbookchild_set-2-nonautopkbook_ptr" type="hidden">',
  638. html=True,
  639. )
  640. def test_inline_editable_pk(self):
  641. response = self.client.get(reverse("admin:admin_inlines_author_add"))
  642. self.assertContains(
  643. response,
  644. '<input class="vIntegerField" id="id_editablepkbook_set-0-manual_pk" '
  645. 'name="editablepkbook_set-0-manual_pk" type="number">',
  646. html=True,
  647. count=1,
  648. )
  649. self.assertContains(
  650. response,
  651. '<input class="vIntegerField" id="id_editablepkbook_set-2-0-manual_pk" '
  652. 'name="editablepkbook_set-2-0-manual_pk" type="number">',
  653. html=True,
  654. count=1,
  655. )
  656. def test_stacked_inline_edit_form_contains_has_original_class(self):
  657. holder = Holder.objects.create(dummy=1)
  658. holder.inner_set.create(dummy=1)
  659. response = self.client.get(
  660. reverse("admin:admin_inlines_holder_change", args=(holder.pk,))
  661. )
  662. self.assertContains(
  663. response,
  664. '<div class="inline-related has_original" id="inner_set-0">',
  665. count=1,
  666. )
  667. self.assertContains(
  668. response, '<div class="inline-related" id="inner_set-1">', count=1
  669. )
  670. def test_inlines_show_change_link_registered(self):
  671. "Inlines `show_change_link` for registered models when enabled."
  672. holder = Holder4.objects.create(dummy=1)
  673. item1 = Inner4Stacked.objects.create(dummy=1, holder=holder)
  674. item2 = Inner4Tabular.objects.create(dummy=1, holder=holder)
  675. items = (
  676. ("inner4stacked", item1.pk),
  677. ("inner4tabular", item2.pk),
  678. )
  679. response = self.client.get(
  680. reverse("admin:admin_inlines_holder4_change", args=(holder.pk,))
  681. )
  682. self.assertTrue(
  683. response.context["inline_admin_formset"].opts.has_registered_model
  684. )
  685. for model, pk in items:
  686. url = reverse("admin:admin_inlines_%s_change" % model, args=(pk,))
  687. self.assertContains(
  688. response, '<a href="%s" %s' % (url, INLINE_CHANGELINK_HTML)
  689. )
  690. def test_inlines_show_change_link_unregistered(self):
  691. "Inlines `show_change_link` disabled for unregistered models."
  692. parent = ParentModelWithCustomPk.objects.create(my_own_pk="foo", name="Foo")
  693. ChildModel1.objects.create(my_own_pk="bar", name="Bar", parent=parent)
  694. ChildModel2.objects.create(my_own_pk="baz", name="Baz", parent=parent)
  695. response = self.client.get(
  696. reverse("admin:admin_inlines_parentmodelwithcustompk_change", args=("foo",))
  697. )
  698. self.assertFalse(
  699. response.context["inline_admin_formset"].opts.has_registered_model
  700. )
  701. self.assertNotContains(response, INLINE_CHANGELINK_HTML)
  702. def test_tabular_inline_show_change_link_false_registered(self):
  703. "Inlines `show_change_link` disabled by default."
  704. poll = Poll.objects.create(name="New poll")
  705. Question.objects.create(poll=poll)
  706. response = self.client.get(
  707. reverse("admin:admin_inlines_poll_change", args=(poll.pk,))
  708. )
  709. self.assertTrue(
  710. response.context["inline_admin_formset"].opts.has_registered_model
  711. )
  712. self.assertNotContains(response, INLINE_CHANGELINK_HTML)
  713. def test_noneditable_inline_has_field_inputs(self):
  714. """Inlines without change permission shows field inputs on add form."""
  715. response = self.client.get(
  716. reverse("admin:admin_inlines_novelreadonlychapter_add")
  717. )
  718. self.assertContains(
  719. response,
  720. '<input type="text" name="chapter_set-0-name" '
  721. 'class="vTextField" maxlength="40" id="id_chapter_set-0-name">',
  722. html=True,
  723. )
  724. def test_inlines_plural_heading_foreign_key(self):
  725. response = self.client.get(reverse("admin:admin_inlines_holder4_add"))
  726. self.assertContains(
  727. response,
  728. (
  729. '<h2 id="inner4stacked_set-heading" class="inline-heading">'
  730. "Inner4 stackeds</h2>"
  731. ),
  732. html=True,
  733. )
  734. self.assertContains(
  735. response,
  736. (
  737. '<h2 id="inner4tabular_set-heading" class="inline-heading">'
  738. "Inner4 tabulars</h2>"
  739. ),
  740. html=True,
  741. )
  742. def test_inlines_singular_heading_one_to_one(self):
  743. response = self.client.get(reverse("admin:admin_inlines_person_add"))
  744. self.assertContains(
  745. response,
  746. '<h2 id="author-heading" class="inline-heading">Author</h2>',
  747. html=True,
  748. ) # Tabular.
  749. self.assertContains(
  750. response,
  751. '<h2 id="fashionista-heading" class="inline-heading">Fashionista</h2>',
  752. html=True,
  753. ) # Stacked.
  754. def test_inlines_based_on_model_state(self):
  755. parent = ShowInlineParent.objects.create(show_inlines=False)
  756. data = {
  757. "show_inlines": "on",
  758. "_save": "Save",
  759. }
  760. change_url = reverse(
  761. "admin:admin_inlines_showinlineparent_change",
  762. args=(parent.id,),
  763. )
  764. response = self.client.post(change_url, data)
  765. self.assertEqual(response.status_code, 302)
  766. parent.refresh_from_db()
  767. self.assertIs(parent.show_inlines, True)
  768. @override_settings(ROOT_URLCONF="admin_inlines.urls")
  769. class TestInlineMedia(TestDataMixin, TestCase):
  770. def setUp(self):
  771. self.client.force_login(self.superuser)
  772. def test_inline_media_only_base(self):
  773. holder = Holder(dummy=13)
  774. holder.save()
  775. Inner(dummy=42, holder=holder).save()
  776. change_url = reverse("admin:admin_inlines_holder_change", args=(holder.id,))
  777. response = self.client.get(change_url)
  778. self.assertContains(response, "my_awesome_admin_scripts.js")
  779. def test_inline_media_only_inline(self):
  780. holder = Holder3(dummy=13)
  781. holder.save()
  782. Inner3(dummy=42, holder=holder).save()
  783. change_url = reverse("admin:admin_inlines_holder3_change", args=(holder.id,))
  784. response = self.client.get(change_url)
  785. self.assertEqual(
  786. response.context["inline_admin_formsets"][0].media._js,
  787. [
  788. "admin/js/vendor/jquery/jquery.min.js",
  789. "my_awesome_inline_scripts.js",
  790. "custom_number.js",
  791. "admin/js/jquery.init.js",
  792. "admin/js/inlines.js",
  793. ],
  794. )
  795. self.assertContains(response, "my_awesome_inline_scripts.js")
  796. def test_all_inline_media(self):
  797. holder = Holder2(dummy=13)
  798. holder.save()
  799. Inner2(dummy=42, holder=holder).save()
  800. change_url = reverse("admin:admin_inlines_holder2_change", args=(holder.id,))
  801. response = self.client.get(change_url)
  802. self.assertContains(response, "my_awesome_admin_scripts.js")
  803. self.assertContains(response, "my_awesome_inline_scripts.js")
  804. @override_settings(ROOT_URLCONF="admin_inlines.urls")
  805. class TestInlineAdminForm(TestCase):
  806. def test_immutable_content_type(self):
  807. """Regression for #9362
  808. The problem depends only on InlineAdminForm and its "original"
  809. argument, so we can safely set the other arguments to None/{}. We just
  810. need to check that the content_type argument of Child isn't altered by
  811. the internals of the inline form."""
  812. sally = Teacher.objects.create(name="Sally")
  813. john = Parent.objects.create(name="John")
  814. joe = Child.objects.create(name="Joe", teacher=sally, parent=john)
  815. iaf = InlineAdminForm(None, None, {}, {}, joe)
  816. parent_ct = ContentType.objects.get_for_model(Parent)
  817. self.assertEqual(iaf.original.content_type, parent_ct)
  818. @override_settings(ROOT_URLCONF="admin_inlines.urls")
  819. class TestInlineProtectedOnDelete(TestDataMixin, TestCase):
  820. def setUp(self):
  821. self.client.force_login(self.superuser)
  822. def test_deleting_inline_with_protected_delete_does_not_validate(self):
  823. lotr = Novel.objects.create(name="Lord of the rings")
  824. chapter = Chapter.objects.create(novel=lotr, name="Many Meetings")
  825. foot_note = FootNote.objects.create(chapter=chapter, note="yadda yadda")
  826. change_url = reverse("admin:admin_inlines_novel_change", args=(lotr.id,))
  827. response = self.client.get(change_url)
  828. data = {
  829. "name": lotr.name,
  830. "chapter_set-TOTAL_FORMS": 1,
  831. "chapter_set-INITIAL_FORMS": 1,
  832. "chapter_set-MAX_NUM_FORMS": 1000,
  833. "_save": "Save",
  834. "chapter_set-0-id": chapter.id,
  835. "chapter_set-0-name": chapter.name,
  836. "chapter_set-0-novel": lotr.id,
  837. "chapter_set-0-DELETE": "on",
  838. }
  839. response = self.client.post(change_url, data)
  840. self.assertContains(
  841. response,
  842. "Deleting chapter %s would require deleting "
  843. "the following protected related objects: foot note %s"
  844. % (chapter, foot_note),
  845. )
  846. @override_settings(ROOT_URLCONF="admin_inlines.urls")
  847. class TestInlinePermissions(TestCase):
  848. """
  849. Make sure the admin respects permissions for objects that are edited
  850. inline. Refs #8060.
  851. """
  852. @classmethod
  853. def setUpTestData(cls):
  854. cls.user = User(username="admin", is_staff=True, is_active=True)
  855. cls.user.set_password("secret")
  856. cls.user.save()
  857. cls.author_ct = ContentType.objects.get_for_model(Author)
  858. cls.holder_ct = ContentType.objects.get_for_model(Holder2)
  859. cls.book_ct = ContentType.objects.get_for_model(Book)
  860. cls.inner_ct = ContentType.objects.get_for_model(Inner2)
  861. # User always has permissions to add and change Authors, and Holders,
  862. # the main (parent) models of the inlines. Permissions on the inlines
  863. # vary per test.
  864. permission = Permission.objects.get(
  865. codename="add_author", content_type=cls.author_ct
  866. )
  867. cls.user.user_permissions.add(permission)
  868. permission = Permission.objects.get(
  869. codename="change_author", content_type=cls.author_ct
  870. )
  871. cls.user.user_permissions.add(permission)
  872. permission = Permission.objects.get(
  873. codename="add_holder2", content_type=cls.holder_ct
  874. )
  875. cls.user.user_permissions.add(permission)
  876. permission = Permission.objects.get(
  877. codename="change_holder2", content_type=cls.holder_ct
  878. )
  879. cls.user.user_permissions.add(permission)
  880. author = Author.objects.create(pk=1, name="The Author")
  881. cls.book = author.books.create(name="The inline Book")
  882. cls.author_change_url = reverse(
  883. "admin:admin_inlines_author_change", args=(author.id,)
  884. )
  885. # Get the ID of the automatically created intermediate model for the
  886. # Author-Book m2m.
  887. author_book_auto_m2m_intermediate = Author.books.through.objects.get(
  888. author=author, book=cls.book
  889. )
  890. cls.author_book_auto_m2m_intermediate_id = author_book_auto_m2m_intermediate.pk
  891. cls.holder = Holder2.objects.create(dummy=13)
  892. cls.inner2 = Inner2.objects.create(dummy=42, holder=cls.holder)
  893. def setUp(self):
  894. self.holder_change_url = reverse(
  895. "admin:admin_inlines_holder2_change", args=(self.holder.id,)
  896. )
  897. self.client.force_login(self.user)
  898. def test_inline_add_m2m_noperm(self):
  899. response = self.client.get(reverse("admin:admin_inlines_author_add"))
  900. # No change permission on books, so no inline
  901. self.assertNotContains(
  902. response,
  903. (
  904. '<h2 id="Author_books-heading" class="inline-heading">'
  905. "Author-book relationships</h2>"
  906. ),
  907. html=True,
  908. )
  909. self.assertNotContains(response, "Add another Author-Book Relationship")
  910. self.assertNotContains(response, 'id="id_Author_books-TOTAL_FORMS"')
  911. def test_inline_add_fk_noperm(self):
  912. response = self.client.get(reverse("admin:admin_inlines_holder2_add"))
  913. # No permissions on Inner2s, so no inline
  914. self.assertNotContains(
  915. response,
  916. '<h2 id="inner2_set-2-heading" class="inline-heading">Inner2s</h2>',
  917. html=True,
  918. )
  919. self.assertNotContains(response, "Add another Inner2")
  920. self.assertNotContains(response, 'id="id_inner2_set-TOTAL_FORMS"')
  921. def test_inline_change_m2m_noperm(self):
  922. response = self.client.get(self.author_change_url)
  923. # No change permission on books, so no inline
  924. self.assertNotContains(
  925. response,
  926. (
  927. '<h2 id="Author_books-heading" class="inline-heading">'
  928. "Author-book relationships</h2>"
  929. ),
  930. html=True,
  931. )
  932. self.assertNotContains(response, "Add another Author-Book Relationship")
  933. self.assertNotContains(response, 'id="id_Author_books-TOTAL_FORMS"')
  934. def test_inline_change_fk_noperm(self):
  935. response = self.client.get(self.holder_change_url)
  936. # No permissions on Inner2s, so no inline
  937. self.assertNotContains(
  938. response,
  939. '<h2 id="inner2_set-2-heading" class="inline-heading">Inner2s</h2>',
  940. html=True,
  941. )
  942. self.assertNotContains(response, "Add another Inner2")
  943. self.assertNotContains(response, 'id="id_inner2_set-TOTAL_FORMS"')
  944. def test_inline_add_m2m_view_only_perm(self):
  945. permission = Permission.objects.get(
  946. codename="view_book", content_type=self.book_ct
  947. )
  948. self.user.user_permissions.add(permission)
  949. response = self.client.get(reverse("admin:admin_inlines_author_add"))
  950. # View-only inlines. (It could be nicer to hide the empty, non-editable
  951. # inlines on the add page.)
  952. self.assertIs(
  953. response.context["inline_admin_formset"].has_view_permission, True
  954. )
  955. self.assertIs(
  956. response.context["inline_admin_formset"].has_add_permission, False
  957. )
  958. self.assertIs(
  959. response.context["inline_admin_formset"].has_change_permission, False
  960. )
  961. self.assertIs(
  962. response.context["inline_admin_formset"].has_delete_permission, False
  963. )
  964. self.assertContains(
  965. response,
  966. (
  967. '<h2 id="Author_books-heading" class="inline-heading">'
  968. "Author-book relationships</h2>"
  969. ),
  970. html=True,
  971. )
  972. self.assertContains(
  973. response,
  974. '<input type="hidden" name="Author_books-TOTAL_FORMS" value="0" '
  975. 'id="id_Author_books-TOTAL_FORMS">',
  976. html=True,
  977. )
  978. self.assertNotContains(response, "Add another Author-Book Relationship")
  979. def test_inline_add_m2m_add_perm(self):
  980. permission = Permission.objects.get(
  981. codename="add_book", content_type=self.book_ct
  982. )
  983. self.user.user_permissions.add(permission)
  984. response = self.client.get(reverse("admin:admin_inlines_author_add"))
  985. # No change permission on Books, so no inline
  986. self.assertNotContains(
  987. response,
  988. (
  989. '<h2 id="Author_books-heading" class="inline-heading">'
  990. "Author-book relationships</h2>"
  991. ),
  992. html=True,
  993. )
  994. self.assertNotContains(response, "Add another Author-Book Relationship")
  995. self.assertNotContains(response, 'id="id_Author_books-TOTAL_FORMS"')
  996. def test_inline_add_fk_add_perm(self):
  997. permission = Permission.objects.get(
  998. codename="add_inner2", content_type=self.inner_ct
  999. )
  1000. self.user.user_permissions.add(permission)
  1001. response = self.client.get(reverse("admin:admin_inlines_holder2_add"))
  1002. # Add permission on inner2s, so we get the inline
  1003. self.assertContains(
  1004. response,
  1005. '<h2 id="inner2_set-2-heading" class="inline-heading">Inner2s</h2>',
  1006. html=True,
  1007. )
  1008. self.assertContains(response, "Add another Inner2")
  1009. self.assertContains(
  1010. response,
  1011. '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" '
  1012. 'value="3" name="inner2_set-TOTAL_FORMS">',
  1013. html=True,
  1014. )
  1015. def test_inline_change_m2m_add_perm(self):
  1016. permission = Permission.objects.get(
  1017. codename="add_book", content_type=self.book_ct
  1018. )
  1019. self.user.user_permissions.add(permission)
  1020. response = self.client.get(self.author_change_url)
  1021. # No change permission on books, so no inline
  1022. self.assertNotContains(
  1023. response,
  1024. (
  1025. '<h2 id="Author_books-heading" class="inline-heading">'
  1026. "Author-book relationships</h2>"
  1027. ),
  1028. html=True,
  1029. )
  1030. self.assertNotContains(response, "Add another Author-Book Relationship")
  1031. self.assertNotContains(response, 'id="id_Author_books-TOTAL_FORMS"')
  1032. self.assertNotContains(response, 'id="id_Author_books-0-DELETE"')
  1033. def test_inline_change_m2m_view_only_perm(self):
  1034. permission = Permission.objects.get(
  1035. codename="view_book", content_type=self.book_ct
  1036. )
  1037. self.user.user_permissions.add(permission)
  1038. response = self.client.get(self.author_change_url)
  1039. # View-only inlines.
  1040. self.assertIs(
  1041. response.context["inline_admin_formset"].has_view_permission, True
  1042. )
  1043. self.assertIs(
  1044. response.context["inline_admin_formset"].has_add_permission, False
  1045. )
  1046. self.assertIs(
  1047. response.context["inline_admin_formset"].has_change_permission, False
  1048. )
  1049. self.assertIs(
  1050. response.context["inline_admin_formset"].has_delete_permission, False
  1051. )
  1052. self.assertContains(
  1053. response,
  1054. (
  1055. '<h2 id="Author_books-heading" class="inline-heading">'
  1056. "Author-book relationships</h2>"
  1057. ),
  1058. html=True,
  1059. )
  1060. self.assertContains(
  1061. response,
  1062. '<input type="hidden" name="Author_books-TOTAL_FORMS" value="1" '
  1063. 'id="id_Author_books-TOTAL_FORMS">',
  1064. html=True,
  1065. )
  1066. # The field in the inline is read-only.
  1067. self.assertContains(response, "<p>%s</p>" % self.book)
  1068. self.assertNotContains(
  1069. response,
  1070. '<input type="checkbox" name="Author_books-0-DELETE" '
  1071. 'id="id_Author_books-0-DELETE">',
  1072. html=True,
  1073. )
  1074. def test_inline_change_m2m_change_perm(self):
  1075. permission = Permission.objects.get(
  1076. codename="change_book", content_type=self.book_ct
  1077. )
  1078. self.user.user_permissions.add(permission)
  1079. response = self.client.get(self.author_change_url)
  1080. # We have change perm on books, so we can add/change/delete inlines
  1081. self.assertIs(
  1082. response.context["inline_admin_formset"].has_view_permission, True
  1083. )
  1084. self.assertIs(response.context["inline_admin_formset"].has_add_permission, True)
  1085. self.assertIs(
  1086. response.context["inline_admin_formset"].has_change_permission, True
  1087. )
  1088. self.assertIs(
  1089. response.context["inline_admin_formset"].has_delete_permission, True
  1090. )
  1091. self.assertContains(
  1092. response,
  1093. (
  1094. '<h2 id="Author_books-heading" class="inline-heading">'
  1095. "Author-book relationships</h2>"
  1096. ),
  1097. html=True,
  1098. )
  1099. self.assertContains(response, "Add another Author-book relationship")
  1100. self.assertContains(
  1101. response,
  1102. '<input type="hidden" id="id_Author_books-TOTAL_FORMS" '
  1103. 'value="4" name="Author_books-TOTAL_FORMS">',
  1104. html=True,
  1105. )
  1106. self.assertContains(
  1107. response,
  1108. '<input type="hidden" id="id_Author_books-0-id" value="%i" '
  1109. 'name="Author_books-0-id">' % self.author_book_auto_m2m_intermediate_id,
  1110. html=True,
  1111. )
  1112. self.assertContains(response, 'id="id_Author_books-0-DELETE"')
  1113. def test_inline_change_fk_add_perm(self):
  1114. permission = Permission.objects.get(
  1115. codename="add_inner2", content_type=self.inner_ct
  1116. )
  1117. self.user.user_permissions.add(permission)
  1118. response = self.client.get(self.holder_change_url)
  1119. # Add permission on inner2s, so we can add but not modify existing
  1120. self.assertContains(
  1121. response,
  1122. '<h2 id="inner2_set-2-heading" class="inline-heading">Inner2s</h2>',
  1123. html=True,
  1124. )
  1125. self.assertContains(response, "Add another Inner2")
  1126. # 3 extra forms only, not the existing instance form
  1127. self.assertContains(
  1128. response,
  1129. '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="3" '
  1130. 'name="inner2_set-TOTAL_FORMS">',
  1131. html=True,
  1132. )
  1133. self.assertNotContains(
  1134. response,
  1135. '<input type="hidden" id="id_inner2_set-0-id" value="%i" '
  1136. 'name="inner2_set-0-id">' % self.inner2.id,
  1137. html=True,
  1138. )
  1139. def test_inline_change_fk_change_perm(self):
  1140. permission = Permission.objects.get(
  1141. codename="change_inner2", content_type=self.inner_ct
  1142. )
  1143. self.user.user_permissions.add(permission)
  1144. response = self.client.get(self.holder_change_url)
  1145. # Change permission on inner2s, so we can change existing but not add new
  1146. self.assertContains(
  1147. response,
  1148. '<h2 id="inner2_set-heading" class="inline-heading">Inner2s</h2>',
  1149. html=True,
  1150. )
  1151. self.assertContains(
  1152. response,
  1153. '<h2 id="inner2_set-2-heading" class="inline-heading">Inner2s</h2>',
  1154. html=True,
  1155. )
  1156. # Just the one form for existing instances
  1157. self.assertContains(
  1158. response,
  1159. '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="1" '
  1160. 'name="inner2_set-TOTAL_FORMS">',
  1161. html=True,
  1162. )
  1163. self.assertContains(
  1164. response,
  1165. '<input type="hidden" id="id_inner2_set-0-id" value="%i" '
  1166. 'name="inner2_set-0-id">' % self.inner2.id,
  1167. html=True,
  1168. )
  1169. # max-num 0 means we can't add new ones
  1170. self.assertContains(
  1171. response,
  1172. '<input type="hidden" id="id_inner2_set-MAX_NUM_FORMS" value="0" '
  1173. 'name="inner2_set-MAX_NUM_FORMS">',
  1174. html=True,
  1175. )
  1176. # TabularInline
  1177. self.assertContains(
  1178. response, '<th class="column-dummy required">Dummy</th>', html=True
  1179. )
  1180. self.assertContains(
  1181. response,
  1182. '<input type="number" name="inner2_set-2-0-dummy" value="%s" '
  1183. 'class="vIntegerField" id="id_inner2_set-2-0-dummy">' % self.inner2.dummy,
  1184. html=True,
  1185. )
  1186. def test_inline_change_fk_add_change_perm(self):
  1187. permission = Permission.objects.get(
  1188. codename="add_inner2", content_type=self.inner_ct
  1189. )
  1190. self.user.user_permissions.add(permission)
  1191. permission = Permission.objects.get(
  1192. codename="change_inner2", content_type=self.inner_ct
  1193. )
  1194. self.user.user_permissions.add(permission)
  1195. response = self.client.get(self.holder_change_url)
  1196. # Add/change perm, so we can add new and change existing
  1197. self.assertContains(
  1198. response,
  1199. '<h2 id="inner2_set-2-heading" class="inline-heading">Inner2s</h2>',
  1200. html=True,
  1201. )
  1202. # One form for existing instance and three extra for new
  1203. self.assertContains(
  1204. response,
  1205. '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="4" '
  1206. 'name="inner2_set-TOTAL_FORMS">',
  1207. html=True,
  1208. )
  1209. self.assertContains(
  1210. response,
  1211. '<input type="hidden" id="id_inner2_set-0-id" value="%i" '
  1212. 'name="inner2_set-0-id">' % self.inner2.id,
  1213. html=True,
  1214. )
  1215. def test_inline_change_fk_change_del_perm(self):
  1216. permission = Permission.objects.get(
  1217. codename="change_inner2", content_type=self.inner_ct
  1218. )
  1219. self.user.user_permissions.add(permission)
  1220. permission = Permission.objects.get(
  1221. codename="delete_inner2", content_type=self.inner_ct
  1222. )
  1223. self.user.user_permissions.add(permission)
  1224. response = self.client.get(self.holder_change_url)
  1225. # Change/delete perm on inner2s, so we can change/delete existing
  1226. self.assertContains(
  1227. response,
  1228. '<h2 id="inner2_set-2-heading" class="inline-heading">Inner2s</h2>',
  1229. html=True,
  1230. )
  1231. # One form for existing instance only, no new
  1232. self.assertContains(
  1233. response,
  1234. '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="1" '
  1235. 'name="inner2_set-TOTAL_FORMS">',
  1236. html=True,
  1237. )
  1238. self.assertContains(
  1239. response,
  1240. '<input type="hidden" id="id_inner2_set-0-id" value="%i" '
  1241. 'name="inner2_set-0-id">' % self.inner2.id,
  1242. html=True,
  1243. )
  1244. self.assertContains(response, 'id="id_inner2_set-0-DELETE"')
  1245. def test_inline_change_fk_all_perms(self):
  1246. permission = Permission.objects.get(
  1247. codename="add_inner2", content_type=self.inner_ct
  1248. )
  1249. self.user.user_permissions.add(permission)
  1250. permission = Permission.objects.get(
  1251. codename="change_inner2", content_type=self.inner_ct
  1252. )
  1253. self.user.user_permissions.add(permission)
  1254. permission = Permission.objects.get(
  1255. codename="delete_inner2", content_type=self.inner_ct
  1256. )
  1257. self.user.user_permissions.add(permission)
  1258. response = self.client.get(self.holder_change_url)
  1259. # All perms on inner2s, so we can add/change/delete
  1260. self.assertContains(
  1261. response,
  1262. '<h2 id="inner2_set-heading" class="inline-heading">Inner2s</h2>',
  1263. html=True,
  1264. )
  1265. self.assertContains(
  1266. response,
  1267. '<h2 id="inner2_set-2-heading" class="inline-heading">Inner2s</h2>',
  1268. html=True,
  1269. )
  1270. # One form for existing instance only, three for new
  1271. self.assertContains(
  1272. response,
  1273. '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="4" '
  1274. 'name="inner2_set-TOTAL_FORMS">',
  1275. html=True,
  1276. )
  1277. self.assertContains(
  1278. response,
  1279. '<input type="hidden" id="id_inner2_set-0-id" value="%i" '
  1280. 'name="inner2_set-0-id">' % self.inner2.id,
  1281. html=True,
  1282. )
  1283. self.assertContains(response, 'id="id_inner2_set-0-DELETE"')
  1284. # TabularInline
  1285. self.assertContains(
  1286. response, '<th class="column-dummy required">Dummy</th>', html=True
  1287. )
  1288. self.assertContains(
  1289. response,
  1290. '<input type="number" name="inner2_set-2-0-dummy" value="%s" '
  1291. 'class="vIntegerField" id="id_inner2_set-2-0-dummy">' % self.inner2.dummy,
  1292. html=True,
  1293. )
  1294. @override_settings(ROOT_URLCONF="admin_inlines.urls")
  1295. class TestReadOnlyChangeViewInlinePermissions(TestCase):
  1296. @classmethod
  1297. def setUpTestData(cls):
  1298. cls.user = User.objects.create_user(
  1299. "testing", password="password", is_staff=True
  1300. )
  1301. cls.user.user_permissions.add(
  1302. Permission.objects.get(
  1303. codename="view_poll",
  1304. content_type=ContentType.objects.get_for_model(Poll),
  1305. )
  1306. )
  1307. cls.user.user_permissions.add(
  1308. *Permission.objects.filter(
  1309. codename__endswith="question",
  1310. content_type=ContentType.objects.get_for_model(Question),
  1311. ).values_list("pk", flat=True)
  1312. )
  1313. cls.poll = Poll.objects.create(name="Survey")
  1314. cls.add_url = reverse("admin:admin_inlines_poll_add")
  1315. cls.change_url = reverse("admin:admin_inlines_poll_change", args=(cls.poll.id,))
  1316. def setUp(self):
  1317. self.client.force_login(self.user)
  1318. def test_add_url_not_allowed(self):
  1319. response = self.client.get(self.add_url)
  1320. self.assertEqual(response.status_code, 403)
  1321. response = self.client.post(self.add_url, {})
  1322. self.assertEqual(response.status_code, 403)
  1323. def test_post_to_change_url_not_allowed(self):
  1324. response = self.client.post(self.change_url, {})
  1325. self.assertEqual(response.status_code, 403)
  1326. def test_get_to_change_url_is_allowed(self):
  1327. response = self.client.get(self.change_url)
  1328. self.assertEqual(response.status_code, 200)
  1329. def test_main_model_is_rendered_as_read_only(self):
  1330. response = self.client.get(self.change_url)
  1331. self.assertContains(
  1332. response, '<div class="readonly">%s</div>' % self.poll.name, html=True
  1333. )
  1334. input = (
  1335. '<input type="text" name="name" value="%s" class="vTextField" '
  1336. 'maxlength="40" required id="id_name">'
  1337. )
  1338. self.assertNotContains(response, input % self.poll.name, html=True)
  1339. def test_inlines_are_rendered_as_read_only(self):
  1340. question = Question.objects.create(
  1341. text="How will this be rendered?", poll=self.poll
  1342. )
  1343. response = self.client.get(self.change_url)
  1344. self.assertContains(
  1345. response, '<td class="field-text"><p>%s</p></td>' % question.text, html=True
  1346. )
  1347. self.assertNotContains(response, 'id="id_question_set-0-text"')
  1348. self.assertNotContains(response, 'id="id_related_objs-0-DELETE"')
  1349. def test_submit_line_shows_only_close_button(self):
  1350. response = self.client.get(self.change_url)
  1351. self.assertContains(
  1352. response,
  1353. '<a href="/admin/admin_inlines/poll/" class="closelink">Close</a>',
  1354. html=True,
  1355. )
  1356. delete_link = (
  1357. '<a href="/admin/admin_inlines/poll/%s/delete/" class="deletelink">Delete'
  1358. "</a>"
  1359. )
  1360. self.assertNotContains(response, delete_link % self.poll.id, html=True)
  1361. self.assertNotContains(
  1362. response,
  1363. '<input type="submit" value="Save and add another" name="_addanother">',
  1364. )
  1365. self.assertNotContains(
  1366. response,
  1367. '<input type="submit" value="Save and continue editing" name="_continue">',
  1368. )
  1369. def test_inline_delete_buttons_are_not_shown(self):
  1370. Question.objects.create(text="How will this be rendered?", poll=self.poll)
  1371. response = self.client.get(self.change_url)
  1372. self.assertNotContains(
  1373. response,
  1374. '<input type="checkbox" name="question_set-0-DELETE" '
  1375. 'id="id_question_set-0-DELETE">',
  1376. html=True,
  1377. )
  1378. def test_extra_inlines_are_not_shown(self):
  1379. response = self.client.get(self.change_url)
  1380. self.assertNotContains(response, 'id="id_question_set-0-text"')
  1381. @override_settings(ROOT_URLCONF="admin_inlines.urls")
  1382. class TestVerboseNameInlineForms(TestDataMixin, TestCase):
  1383. factory = RequestFactory()
  1384. def test_verbose_name_inline(self):
  1385. class NonVerboseProfileInline(TabularInline):
  1386. model = Profile
  1387. verbose_name = "Non-verbose childs"
  1388. class VerboseNameProfileInline(TabularInline):
  1389. model = VerboseNameProfile
  1390. verbose_name = "Childs with verbose name"
  1391. class VerboseNamePluralProfileInline(TabularInline):
  1392. model = VerboseNamePluralProfile
  1393. verbose_name = "Childs with verbose name plural"
  1394. class BothVerboseNameProfileInline(TabularInline):
  1395. model = BothVerboseNameProfile
  1396. verbose_name = "Childs with both verbose names"
  1397. modeladmin = ModelAdmin(ProfileCollection, admin_site)
  1398. modeladmin.inlines = [
  1399. NonVerboseProfileInline,
  1400. VerboseNameProfileInline,
  1401. VerboseNamePluralProfileInline,
  1402. BothVerboseNameProfileInline,
  1403. ]
  1404. obj = ProfileCollection.objects.create()
  1405. url = reverse("admin:admin_inlines_profilecollection_change", args=(obj.pk,))
  1406. request = self.factory.get(url)
  1407. request.user = self.superuser
  1408. response = modeladmin.changeform_view(request)
  1409. self.assertNotContains(response, "Add another Profile")
  1410. # Non-verbose model.
  1411. self.assertContains(
  1412. response,
  1413. (
  1414. '<h2 id="profile_set-heading" class="inline-heading">'
  1415. "Non-verbose childss</h2>"
  1416. ),
  1417. html=True,
  1418. )
  1419. self.assertContains(response, "Add another Non-verbose child")
  1420. self.assertNotContains(
  1421. response,
  1422. '<h2 id="profile_set-heading" class="inline-heading">Profiles</h2>',
  1423. html=True,
  1424. )
  1425. # Model with verbose name.
  1426. self.assertContains(
  1427. response,
  1428. (
  1429. '<h2 id="verbosenameprofile_set-heading" class="inline-heading">'
  1430. "Childs with verbose names</h2>"
  1431. ),
  1432. html=True,
  1433. )
  1434. self.assertContains(response, "Add another Childs with verbose name")
  1435. self.assertNotContains(
  1436. response,
  1437. '<h2 id="verbosenameprofile_set-heading" class="inline-heading">'
  1438. "Model with verbose name onlys</h2>",
  1439. html=True,
  1440. )
  1441. self.assertNotContains(response, "Add another Model with verbose name only")
  1442. # Model with verbose name plural.
  1443. self.assertContains(
  1444. response,
  1445. (
  1446. '<h2 id="verbosenamepluralprofile_set-heading" class="inline-heading">'
  1447. "Childs with verbose name plurals</h2>"
  1448. ),
  1449. html=True,
  1450. )
  1451. self.assertContains(response, "Add another Childs with verbose name plural")
  1452. self.assertNotContains(
  1453. response,
  1454. '<h2 id="verbosenamepluralprofile_set-heading" class="inline-heading">'
  1455. "Model with verbose name plural only</h2>",
  1456. html=True,
  1457. )
  1458. # Model with both verbose names.
  1459. self.assertContains(
  1460. response,
  1461. (
  1462. '<h2 id="bothverbosenameprofile_set-heading" class="inline-heading">'
  1463. "Childs with both verbose namess</h2>"
  1464. ),
  1465. html=True,
  1466. )
  1467. self.assertContains(response, "Add another Childs with both verbose names")
  1468. self.assertNotContains(
  1469. response,
  1470. '<h2 id="bothverbosenameprofile_set-heading" class="inline-heading">'
  1471. "Model with both - plural name</h2>",
  1472. html=True,
  1473. )
  1474. self.assertNotContains(response, "Add another Model with both - name")
  1475. def test_verbose_name_plural_inline(self):
  1476. class NonVerboseProfileInline(TabularInline):
  1477. model = Profile
  1478. verbose_name_plural = "Non-verbose childs"
  1479. class VerboseNameProfileInline(TabularInline):
  1480. model = VerboseNameProfile
  1481. verbose_name_plural = "Childs with verbose name"
  1482. class VerboseNamePluralProfileInline(TabularInline):
  1483. model = VerboseNamePluralProfile
  1484. verbose_name_plural = "Childs with verbose name plural"
  1485. class BothVerboseNameProfileInline(TabularInline):
  1486. model = BothVerboseNameProfile
  1487. verbose_name_plural = "Childs with both verbose names"
  1488. modeladmin = ModelAdmin(ProfileCollection, admin_site)
  1489. modeladmin.inlines = [
  1490. NonVerboseProfileInline,
  1491. VerboseNameProfileInline,
  1492. VerboseNamePluralProfileInline,
  1493. BothVerboseNameProfileInline,
  1494. ]
  1495. obj = ProfileCollection.objects.create()
  1496. url = reverse("admin:admin_inlines_profilecollection_change", args=(obj.pk,))
  1497. request = self.factory.get(url)
  1498. request.user = self.superuser
  1499. response = modeladmin.changeform_view(request)
  1500. # Non-verbose model.
  1501. self.assertContains(
  1502. response,
  1503. (
  1504. '<h2 id="profile_set-heading" class="inline-heading">'
  1505. "Non-verbose childs</h2>"
  1506. ),
  1507. html=True,
  1508. )
  1509. self.assertContains(response, "Add another Profile")
  1510. self.assertNotContains(
  1511. response,
  1512. '<h2 id="profile_set-heading" class="inline-heading">Profiles</h2>',
  1513. html=True,
  1514. )
  1515. # Model with verbose name.
  1516. self.assertContains(
  1517. response,
  1518. (
  1519. '<h2 id="verbosenameprofile_set-heading" class="inline-heading">'
  1520. "Childs with verbose name</h2>"
  1521. ),
  1522. html=True,
  1523. )
  1524. self.assertContains(response, "Add another Model with verbose name only")
  1525. self.assertNotContains(
  1526. response,
  1527. '<h2 id="verbosenameprofile_set-heading" class="inline-heading">'
  1528. "Model with verbose name onlys</h2>",
  1529. html=True,
  1530. )
  1531. # Model with verbose name plural.
  1532. self.assertContains(
  1533. response,
  1534. (
  1535. '<h2 id="verbosenamepluralprofile_set-heading" class="inline-heading">'
  1536. "Childs with verbose name plural</h2>"
  1537. ),
  1538. html=True,
  1539. )
  1540. self.assertContains(response, "Add another Profile")
  1541. self.assertNotContains(
  1542. response,
  1543. '<h2 id="verbosenamepluralprofile_set-heading" class="inline-heading">'
  1544. "Model with verbose name plural only</h2>",
  1545. html=True,
  1546. )
  1547. # Model with both verbose names.
  1548. self.assertContains(
  1549. response,
  1550. (
  1551. '<h2 id="bothverbosenameprofile_set-heading" class="inline-heading">'
  1552. "Childs with both verbose names</h2>"
  1553. ),
  1554. html=True,
  1555. )
  1556. self.assertContains(response, "Add another Model with both - name")
  1557. self.assertNotContains(
  1558. response,
  1559. '<h2 id="bothverbosenameprofile_set-heading" class="inline-heading">'
  1560. "Model with both - plural name</h2>",
  1561. html=True,
  1562. )
  1563. def test_both_verbose_names_inline(self):
  1564. class NonVerboseProfileInline(TabularInline):
  1565. model = Profile
  1566. verbose_name = "Non-verbose childs - name"
  1567. verbose_name_plural = "Non-verbose childs - plural name"
  1568. class VerboseNameProfileInline(TabularInline):
  1569. model = VerboseNameProfile
  1570. verbose_name = "Childs with verbose name - name"
  1571. verbose_name_plural = "Childs with verbose name - plural name"
  1572. class VerboseNamePluralProfileInline(TabularInline):
  1573. model = VerboseNamePluralProfile
  1574. verbose_name = "Childs with verbose name plural - name"
  1575. verbose_name_plural = "Childs with verbose name plural - plural name"
  1576. class BothVerboseNameProfileInline(TabularInline):
  1577. model = BothVerboseNameProfile
  1578. verbose_name = "Childs with both - name"
  1579. verbose_name_plural = "Childs with both - plural name"
  1580. modeladmin = ModelAdmin(ProfileCollection, admin_site)
  1581. modeladmin.inlines = [
  1582. NonVerboseProfileInline,
  1583. VerboseNameProfileInline,
  1584. VerboseNamePluralProfileInline,
  1585. BothVerboseNameProfileInline,
  1586. ]
  1587. obj = ProfileCollection.objects.create()
  1588. url = reverse("admin:admin_inlines_profilecollection_change", args=(obj.pk,))
  1589. request = self.factory.get(url)
  1590. request.user = self.superuser
  1591. response = modeladmin.changeform_view(request)
  1592. self.assertNotContains(response, "Add another Profile")
  1593. # Non-verbose model.
  1594. self.assertContains(
  1595. response,
  1596. (
  1597. '<h2 id="profile_set-heading" class="inline-heading">'
  1598. "Non-verbose childs - plural name</h2>"
  1599. ),
  1600. html=True,
  1601. )
  1602. self.assertContains(response, "Add another Non-verbose childs - name")
  1603. self.assertNotContains(
  1604. response,
  1605. '<h2 id="profile_set-heading" class="inline-heading">Profiles</h2>',
  1606. html=True,
  1607. )
  1608. # Model with verbose name.
  1609. self.assertContains(
  1610. response,
  1611. (
  1612. '<h2 id="verbosenameprofile_set-heading" class="inline-heading">'
  1613. "Childs with verbose name - plural name</h2>"
  1614. ),
  1615. html=True,
  1616. )
  1617. self.assertContains(response, "Add another Childs with verbose name - name")
  1618. self.assertNotContains(
  1619. response,
  1620. '<h2 id="verbosenameprofile_set-heading" class="inline-heading">'
  1621. "Model with verbose name onlys</h2>",
  1622. html=True,
  1623. )
  1624. # Model with verbose name plural.
  1625. self.assertContains(
  1626. response,
  1627. (
  1628. '<h2 id="verbosenamepluralprofile_set-heading" class="inline-heading">'
  1629. "Childs with verbose name plural - plural name</h2>"
  1630. ),
  1631. html=True,
  1632. )
  1633. self.assertContains(
  1634. response,
  1635. "Add another Childs with verbose name plural - name",
  1636. )
  1637. self.assertNotContains(
  1638. response,
  1639. '<h2 id="verbosenamepluralprofile_set-heading" class="inline-heading">'
  1640. "Model with verbose name plural only</h2>",
  1641. html=True,
  1642. )
  1643. # Model with both verbose names.
  1644. self.assertContains(
  1645. response,
  1646. '<h2 id="bothverbosenameprofile_set-heading" class="inline-heading">'
  1647. "Childs with both - plural name</h2>",
  1648. html=True,
  1649. )
  1650. self.assertContains(response, "Add another Childs with both - name")
  1651. self.assertNotContains(
  1652. response,
  1653. '<h2 id="bothverbosenameprofile_set-heading" class="inline-heading">'
  1654. "Model with both - plural name</h2>",
  1655. html=True,
  1656. )
  1657. self.assertNotContains(response, "Add another Model with both - name")
  1658. @override_settings(ROOT_URLCONF="admin_inlines.urls")
  1659. class TestInlineWithFieldsets(TestDataMixin, TestCase):
  1660. def setUp(self):
  1661. self.client.force_login(self.superuser)
  1662. @override_settings(DEBUG=True)
  1663. def test_fieldset_context_fully_set(self):
  1664. url = reverse("admin:admin_inlines_photographer_add")
  1665. with self.assertRaisesMessage(AssertionError, "no logs"):
  1666. with self.assertLogs("django.template", "DEBUG"):
  1667. self.client.get(url)
  1668. def test_inline_headings(self):
  1669. response = self.client.get(reverse("admin:admin_inlines_photographer_add"))
  1670. # Page main title.
  1671. self.assertContains(response, "<h1>Add photographer</h1>", html=True)
  1672. # Headings for the toplevel fieldsets. The first one has no name.
  1673. self.assertContains(response, '<fieldset class="module aligned ">')
  1674. # The second and third have the same "Advanced options" name, but the
  1675. # second one has the "collapse" class.
  1676. for x, classes in ((1, ""), (2, "collapse")):
  1677. heading_id = f"fieldset-0-{x}-heading"
  1678. with self.subTest(heading_id=heading_id):
  1679. self.assertContains(
  1680. response,
  1681. f'<fieldset class="module aligned {classes}" '
  1682. f'aria-labelledby="{heading_id}">',
  1683. )
  1684. self.assertContains(
  1685. response,
  1686. f'<h2 id="{heading_id}" class="fieldset-heading">'
  1687. "Advanced options</h2>",
  1688. )
  1689. self.assertContains(response, f'id="{heading_id}"', count=1)
  1690. # Headings and subheadings for all the inlines.
  1691. for inline_admin_formset in response.context["inline_admin_formsets"]:
  1692. prefix = inline_admin_formset.formset.prefix
  1693. heading_id = f"{prefix}-heading"
  1694. formset_heading = (
  1695. f'<h2 id="{heading_id}" class="inline-heading">Photos</h2>'
  1696. )
  1697. self.assertContains(response, formset_heading, html=True)
  1698. self.assertContains(response, f'id="{heading_id}"', count=1)
  1699. # If this is a TabularInline, do not make further asserts since
  1700. # fieldsets are not shown as such in this table layout.
  1701. if "tabular" in inline_admin_formset.opts.template:
  1702. continue
  1703. if "collapse" in inline_admin_formset.classes:
  1704. formset_heading = f"<summary>{formset_heading}</summary>"
  1705. self.assertContains(response, formset_heading, html=True, count=1)
  1706. # Headings for every formset (the amount depends on `extra`).
  1707. for y, inline_admin_form in enumerate(inline_admin_formset):
  1708. y_plus_one = y + 1
  1709. form_heading = (
  1710. f'<h3><b>Photo:</b> <span class="inline_label">#{y_plus_one}</span>'
  1711. "</h3>"
  1712. )
  1713. self.assertContains(response, form_heading, html=True)
  1714. # Every fieldset defined for an inline's form.
  1715. for z, fieldset in enumerate(inline_admin_form):
  1716. if fieldset.name:
  1717. heading_id = f"{prefix}-{y}-{z}-heading"
  1718. self.assertContains(
  1719. response,
  1720. f'<fieldset class="module aligned {fieldset.classes}" '
  1721. f'aria-labelledby="{heading_id}">',
  1722. )
  1723. fieldset_heading = (
  1724. f'<h4 id="{heading_id}" class="fieldset-heading">'
  1725. f"Details</h4>"
  1726. )
  1727. self.assertContains(response, fieldset_heading)
  1728. if "collapse" in fieldset.classes:
  1729. self.assertContains(
  1730. response,
  1731. f"<summary>{fieldset_heading}</summary>",
  1732. html=True,
  1733. )
  1734. self.assertContains(response, f'id="{heading_id}"', count=1)
  1735. else:
  1736. fieldset_html = (
  1737. f'<fieldset class="module aligned {fieldset.classes}">'
  1738. )
  1739. self.assertContains(response, fieldset_html)
  1740. @override_settings(ROOT_URLCONF="admin_inlines.urls")
  1741. class SeleniumTests(AdminSeleniumTestCase):
  1742. available_apps = ["admin_inlines"] + AdminSeleniumTestCase.available_apps
  1743. def setUp(self):
  1744. User.objects.create_superuser(
  1745. username="super", password="secret", email="super@example.com"
  1746. )
  1747. @screenshot_cases(["desktop_size", "mobile_size", "dark", "high_contrast"])
  1748. def test_add_stackeds(self):
  1749. """
  1750. The "Add another XXX" link correctly adds items to the stacked formset.
  1751. """
  1752. from selenium.webdriver.common.by import By
  1753. self.admin_login(username="super", password="secret")
  1754. self.selenium.get(
  1755. self.live_server_url + reverse("admin:admin_inlines_holder4_add")
  1756. )
  1757. inline_id = "#inner4stacked_set-group"
  1758. rows_selector = "%s .dynamic-inner4stacked_set" % inline_id
  1759. self.assertCountSeleniumElements(rows_selector, 3)
  1760. add_button = self.selenium.find_element(
  1761. By.LINK_TEXT, "Add another Inner4 stacked"
  1762. )
  1763. add_button.click()
  1764. self.assertCountSeleniumElements(rows_selector, 4)
  1765. self.take_screenshot("added")
  1766. def test_delete_stackeds(self):
  1767. from selenium.webdriver.common.by import By
  1768. self.admin_login(username="super", password="secret")
  1769. self.selenium.get(
  1770. self.live_server_url + reverse("admin:admin_inlines_holder4_add")
  1771. )
  1772. inline_id = "#inner4stacked_set-group"
  1773. rows_selector = "%s .dynamic-inner4stacked_set" % inline_id
  1774. self.assertCountSeleniumElements(rows_selector, 3)
  1775. add_button = self.selenium.find_element(
  1776. By.LINK_TEXT, "Add another Inner4 stacked"
  1777. )
  1778. add_button.click()
  1779. add_button.click()
  1780. self.assertCountSeleniumElements(rows_selector, 5)
  1781. for delete_link in self.selenium.find_elements(
  1782. By.CSS_SELECTOR, "%s .inline-deletelink" % inline_id
  1783. ):
  1784. delete_link.click()
  1785. with self.disable_implicit_wait():
  1786. self.assertCountSeleniumElements(rows_selector, 0)
  1787. def test_delete_invalid_stacked_inlines(self):
  1788. from selenium.common.exceptions import NoSuchElementException
  1789. from selenium.webdriver.common.by import By
  1790. self.admin_login(username="super", password="secret")
  1791. self.selenium.get(
  1792. self.live_server_url + reverse("admin:admin_inlines_holder4_add")
  1793. )
  1794. inline_id = "#inner4stacked_set-group"
  1795. rows_selector = "%s .dynamic-inner4stacked_set" % inline_id
  1796. self.assertCountSeleniumElements(rows_selector, 3)
  1797. add_button = self.selenium.find_element(
  1798. By.LINK_TEXT,
  1799. "Add another Inner4 stacked",
  1800. )
  1801. add_button.click()
  1802. add_button.click()
  1803. self.assertCountSeleniumElements("#id_inner4stacked_set-4-dummy", 1)
  1804. # Enter some data and click 'Save'.
  1805. self.selenium.find_element(By.NAME, "dummy").send_keys("1")
  1806. self.selenium.find_element(By.NAME, "inner4stacked_set-0-dummy").send_keys(
  1807. "100"
  1808. )
  1809. self.selenium.find_element(By.NAME, "inner4stacked_set-1-dummy").send_keys(
  1810. "101"
  1811. )
  1812. self.selenium.find_element(By.NAME, "inner4stacked_set-2-dummy").send_keys(
  1813. "222"
  1814. )
  1815. self.selenium.find_element(By.NAME, "inner4stacked_set-3-dummy").send_keys(
  1816. "103"
  1817. )
  1818. self.selenium.find_element(By.NAME, "inner4stacked_set-4-dummy").send_keys(
  1819. "222"
  1820. )
  1821. with self.wait_page_loaded():
  1822. self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click()
  1823. # Sanity check.
  1824. self.assertCountSeleniumElements(rows_selector, 5)
  1825. errorlist = self.selenium.find_element(
  1826. By.CSS_SELECTOR,
  1827. "%s .dynamic-inner4stacked_set .errorlist li" % inline_id,
  1828. )
  1829. self.assertEqual("Please correct the duplicate values below.", errorlist.text)
  1830. delete_link = self.selenium.find_element(
  1831. By.CSS_SELECTOR, "#inner4stacked_set-4 .inline-deletelink"
  1832. )
  1833. delete_link.click()
  1834. self.assertCountSeleniumElements(rows_selector, 4)
  1835. with self.disable_implicit_wait(), self.assertRaises(NoSuchElementException):
  1836. self.selenium.find_element(
  1837. By.CSS_SELECTOR,
  1838. "%s .dynamic-inner4stacked_set .errorlist li" % inline_id,
  1839. )
  1840. with self.wait_page_loaded():
  1841. self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click()
  1842. # The objects have been created in the database.
  1843. self.assertEqual(Inner4Stacked.objects.count(), 4)
  1844. def test_delete_invalid_tabular_inlines(self):
  1845. from selenium.common.exceptions import NoSuchElementException
  1846. from selenium.webdriver.common.by import By
  1847. self.admin_login(username="super", password="secret")
  1848. self.selenium.get(
  1849. self.live_server_url + reverse("admin:admin_inlines_holder4_add")
  1850. )
  1851. inline_id = "#inner4tabular_set-group"
  1852. rows_selector = "%s .dynamic-inner4tabular_set" % inline_id
  1853. self.assertCountSeleniumElements(rows_selector, 3)
  1854. add_button = self.selenium.find_element(
  1855. By.LINK_TEXT, "Add another Inner4 tabular"
  1856. )
  1857. add_button.click()
  1858. add_button.click()
  1859. self.assertCountSeleniumElements("#id_inner4tabular_set-4-dummy", 1)
  1860. # Enter some data and click 'Save'.
  1861. self.selenium.find_element(By.NAME, "dummy").send_keys("1")
  1862. self.selenium.find_element(By.NAME, "inner4tabular_set-0-dummy").send_keys(
  1863. "100"
  1864. )
  1865. self.selenium.find_element(By.NAME, "inner4tabular_set-1-dummy").send_keys(
  1866. "101"
  1867. )
  1868. self.selenium.find_element(By.NAME, "inner4tabular_set-2-dummy").send_keys(
  1869. "222"
  1870. )
  1871. self.selenium.find_element(By.NAME, "inner4tabular_set-3-dummy").send_keys(
  1872. "103"
  1873. )
  1874. self.selenium.find_element(By.NAME, "inner4tabular_set-4-dummy").send_keys(
  1875. "222"
  1876. )
  1877. with self.wait_page_loaded():
  1878. self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click()
  1879. # Sanity Check.
  1880. self.assertCountSeleniumElements(rows_selector, 5)
  1881. # Non-field errorlist is in its own <tr> just before
  1882. # tr#inner4tabular_set-3:
  1883. errorlist = self.selenium.find_element(
  1884. By.CSS_SELECTOR,
  1885. "%s #inner4tabular_set-3 + .row-form-errors .errorlist li" % inline_id,
  1886. )
  1887. self.assertEqual("Please correct the duplicate values below.", errorlist.text)
  1888. delete_link = self.selenium.find_element(
  1889. By.CSS_SELECTOR, "#inner4tabular_set-4 .inline-deletelink"
  1890. )
  1891. delete_link.click()
  1892. self.assertCountSeleniumElements(rows_selector, 4)
  1893. with self.disable_implicit_wait(), self.assertRaises(NoSuchElementException):
  1894. self.selenium.find_element(
  1895. By.CSS_SELECTOR,
  1896. "%s .dynamic-inner4tabular_set .errorlist li" % inline_id,
  1897. )
  1898. with self.wait_page_loaded():
  1899. self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click()
  1900. # The objects have been created in the database.
  1901. self.assertEqual(Inner4Tabular.objects.count(), 4)
  1902. def test_add_inlines(self):
  1903. """
  1904. The "Add another XXX" link correctly adds items to the inline form.
  1905. """
  1906. from selenium.webdriver.common.by import By
  1907. self.admin_login(username="super", password="secret")
  1908. self.selenium.get(
  1909. self.live_server_url + reverse("admin:admin_inlines_profilecollection_add")
  1910. )
  1911. # There's only one inline to start with and it has the correct ID.
  1912. self.assertCountSeleniumElements(".dynamic-profile_set", 1)
  1913. self.assertEqual(
  1914. self.selenium.find_elements(By.CSS_SELECTOR, ".dynamic-profile_set")[
  1915. 0
  1916. ].get_attribute("id"),
  1917. "profile_set-0",
  1918. )
  1919. self.assertCountSeleniumElements(
  1920. ".dynamic-profile_set#profile_set-0 input[name=profile_set-0-first_name]", 1
  1921. )
  1922. self.assertCountSeleniumElements(
  1923. ".dynamic-profile_set#profile_set-0 input[name=profile_set-0-last_name]", 1
  1924. )
  1925. # Add an inline
  1926. self.selenium.find_element(By.LINK_TEXT, "Add another Profile").click()
  1927. # The inline has been added, it has the right id, and it contains the
  1928. # correct fields.
  1929. self.assertCountSeleniumElements(".dynamic-profile_set", 2)
  1930. self.assertEqual(
  1931. self.selenium.find_elements(By.CSS_SELECTOR, ".dynamic-profile_set")[
  1932. 1
  1933. ].get_attribute("id"),
  1934. "profile_set-1",
  1935. )
  1936. self.assertCountSeleniumElements(
  1937. ".dynamic-profile_set#profile_set-1 input[name=profile_set-1-first_name]", 1
  1938. )
  1939. self.assertCountSeleniumElements(
  1940. ".dynamic-profile_set#profile_set-1 input[name=profile_set-1-last_name]", 1
  1941. )
  1942. # Let's add another one to be sure
  1943. self.selenium.find_element(By.LINK_TEXT, "Add another Profile").click()
  1944. self.assertCountSeleniumElements(".dynamic-profile_set", 3)
  1945. self.assertEqual(
  1946. self.selenium.find_elements(By.CSS_SELECTOR, ".dynamic-profile_set")[
  1947. 2
  1948. ].get_attribute("id"),
  1949. "profile_set-2",
  1950. )
  1951. self.assertCountSeleniumElements(
  1952. ".dynamic-profile_set#profile_set-2 input[name=profile_set-2-first_name]", 1
  1953. )
  1954. self.assertCountSeleniumElements(
  1955. ".dynamic-profile_set#profile_set-2 input[name=profile_set-2-last_name]", 1
  1956. )
  1957. # Enter some data and click 'Save'
  1958. self.selenium.find_element(By.NAME, "profile_set-0-first_name").send_keys(
  1959. "0 first name 1"
  1960. )
  1961. self.selenium.find_element(By.NAME, "profile_set-0-last_name").send_keys(
  1962. "0 last name 2"
  1963. )
  1964. self.selenium.find_element(By.NAME, "profile_set-1-first_name").send_keys(
  1965. "1 first name 1"
  1966. )
  1967. self.selenium.find_element(By.NAME, "profile_set-1-last_name").send_keys(
  1968. "1 last name 2"
  1969. )
  1970. self.selenium.find_element(By.NAME, "profile_set-2-first_name").send_keys(
  1971. "2 first name 1"
  1972. )
  1973. self.selenium.find_element(By.NAME, "profile_set-2-last_name").send_keys(
  1974. "2 last name 2"
  1975. )
  1976. with self.wait_page_loaded():
  1977. self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click()
  1978. # The objects have been created in the database
  1979. self.assertEqual(ProfileCollection.objects.count(), 1)
  1980. self.assertEqual(Profile.objects.count(), 3)
  1981. def test_add_inline_link_absent_for_view_only_parent_model(self):
  1982. from selenium.common.exceptions import NoSuchElementException
  1983. from selenium.webdriver.common.by import By
  1984. user = User.objects.create_user("testing", password="password", is_staff=True)
  1985. user.user_permissions.add(
  1986. Permission.objects.get(
  1987. codename="view_poll",
  1988. content_type=ContentType.objects.get_for_model(Poll),
  1989. )
  1990. )
  1991. user.user_permissions.add(
  1992. *Permission.objects.filter(
  1993. codename__endswith="question",
  1994. content_type=ContentType.objects.get_for_model(Question),
  1995. ).values_list("pk", flat=True)
  1996. )
  1997. self.admin_login(username="testing", password="password")
  1998. poll = Poll.objects.create(name="Survey")
  1999. change_url = reverse("admin:admin_inlines_poll_change", args=(poll.id,))
  2000. self.selenium.get(self.live_server_url + change_url)
  2001. with self.disable_implicit_wait():
  2002. with self.assertRaises(NoSuchElementException):
  2003. self.selenium.find_element(By.LINK_TEXT, "Add another Question")
  2004. def test_delete_inlines(self):
  2005. from selenium.webdriver.common.by import By
  2006. self.admin_login(username="super", password="secret")
  2007. self.selenium.get(
  2008. self.live_server_url + reverse("admin:admin_inlines_profilecollection_add")
  2009. )
  2010. # Add a few inlines
  2011. self.selenium.find_element(By.LINK_TEXT, "Add another Profile").click()
  2012. self.selenium.find_element(By.LINK_TEXT, "Add another Profile").click()
  2013. self.selenium.find_element(By.LINK_TEXT, "Add another Profile").click()
  2014. self.selenium.find_element(By.LINK_TEXT, "Add another Profile").click()
  2015. self.assertCountSeleniumElements(
  2016. "#profile_set-group table tr.dynamic-profile_set", 5
  2017. )
  2018. self.assertCountSeleniumElements(
  2019. "form#profilecollection_form tr.dynamic-profile_set#profile_set-0", 1
  2020. )
  2021. self.assertCountSeleniumElements(
  2022. "form#profilecollection_form tr.dynamic-profile_set#profile_set-1", 1
  2023. )
  2024. self.assertCountSeleniumElements(
  2025. "form#profilecollection_form tr.dynamic-profile_set#profile_set-2", 1
  2026. )
  2027. self.assertCountSeleniumElements(
  2028. "form#profilecollection_form tr.dynamic-profile_set#profile_set-3", 1
  2029. )
  2030. self.assertCountSeleniumElements(
  2031. "form#profilecollection_form tr.dynamic-profile_set#profile_set-4", 1
  2032. )
  2033. # Click on a few delete buttons
  2034. self.selenium.find_element(
  2035. By.CSS_SELECTOR,
  2036. "form#profilecollection_form tr.dynamic-profile_set#profile_set-1 "
  2037. "td.delete a",
  2038. ).click()
  2039. self.selenium.find_element(
  2040. By.CSS_SELECTOR,
  2041. "form#profilecollection_form tr.dynamic-profile_set#profile_set-2 "
  2042. "td.delete a",
  2043. ).click()
  2044. # The rows are gone and the IDs have been re-sequenced
  2045. self.assertCountSeleniumElements(
  2046. "#profile_set-group table tr.dynamic-profile_set", 3
  2047. )
  2048. self.assertCountSeleniumElements(
  2049. "form#profilecollection_form tr.dynamic-profile_set#profile_set-0", 1
  2050. )
  2051. self.assertCountSeleniumElements(
  2052. "form#profilecollection_form tr.dynamic-profile_set#profile_set-1", 1
  2053. )
  2054. self.assertCountSeleniumElements(
  2055. "form#profilecollection_form tr.dynamic-profile_set#profile_set-2", 1
  2056. )
  2057. @screenshot_cases(["desktop_size", "mobile_size", "rtl", "dark", "high_contrast"])
  2058. def test_collapsed_inlines(self):
  2059. from selenium.webdriver.common.by import By
  2060. # Collapsed inlines use details and summary elements.
  2061. self.admin_login(username="super", password="secret")
  2062. self.selenium.get(
  2063. self.live_server_url + reverse("admin:admin_inlines_author_add")
  2064. )
  2065. # One field is in a stacked inline, other in a tabular one.
  2066. test_fields = [
  2067. "#id_nonautopkbook_set-0-title",
  2068. "#id_nonautopkbook_set-2-0-title",
  2069. ]
  2070. summaries = self.selenium.find_elements(By.TAG_NAME, "summary")
  2071. self.assertEqual(len(summaries), 3)
  2072. self.take_screenshot("loaded")
  2073. for show_index, field_name in enumerate(test_fields, 0):
  2074. self.wait_until_invisible(field_name)
  2075. summaries[show_index].click()
  2076. self.wait_until_visible(field_name)
  2077. self.take_screenshot("expanded")
  2078. for hide_index, field_name in enumerate(test_fields, 0):
  2079. self.wait_until_visible(field_name)
  2080. summaries[hide_index].click()
  2081. self.wait_until_invisible(field_name)
  2082. self.take_screenshot("collapsed")
  2083. @screenshot_cases(["desktop_size", "mobile_size", "rtl", "dark", "high_contrast"])
  2084. def test_added_stacked_inline_with_collapsed_fields(self):
  2085. from selenium.webdriver.common.by import By
  2086. self.admin_login(username="super", password="secret")
  2087. self.selenium.get(
  2088. self.live_server_url + reverse("admin:admin_inlines_teacher_add")
  2089. )
  2090. add_text = gettext("Add another %(verbose_name)s") % {"verbose_name": "Child"}
  2091. self.selenium.find_element(By.LINK_TEXT, add_text).click()
  2092. test_fields = ["#id_child_set-0-name", "#id_child_set-1-name"]
  2093. summaries = self.selenium.find_elements(By.TAG_NAME, "summary")
  2094. self.assertEqual(len(summaries), 3)
  2095. self.take_screenshot("loaded")
  2096. for show_index, field_name in enumerate(test_fields, 0):
  2097. self.wait_until_invisible(field_name)
  2098. summaries[show_index].click()
  2099. self.wait_until_visible(field_name)
  2100. self.take_screenshot("expanded")
  2101. for hide_index, field_name in enumerate(test_fields, 0):
  2102. self.wait_until_visible(field_name)
  2103. summaries[hide_index].click()
  2104. self.wait_until_invisible(field_name)
  2105. self.take_screenshot("collapsed")
  2106. def assertBorder(self, element, border):
  2107. width, style, color = border.split(" ")
  2108. border_properties = [
  2109. "border-bottom-%s",
  2110. "border-left-%s",
  2111. "border-right-%s",
  2112. "border-top-%s",
  2113. ]
  2114. for prop in border_properties:
  2115. self.assertEqual(element.value_of_css_property(prop % "width"), width)
  2116. for prop in border_properties:
  2117. self.assertEqual(element.value_of_css_property(prop % "style"), style)
  2118. # Convert hex color to rgb.
  2119. self.assertRegex(color, "#[0-9a-f]{6}")
  2120. r, g, b = int(color[1:3], 16), int(color[3:5], 16), int(color[5:], 16)
  2121. # The value may be expressed as either rgb() or rgba() depending on the
  2122. # browser.
  2123. colors = [
  2124. "rgb(%d, %d, %d)" % (r, g, b),
  2125. "rgba(%d, %d, %d, 1)" % (r, g, b),
  2126. ]
  2127. for prop in border_properties:
  2128. self.assertIn(element.value_of_css_property(prop % "color"), colors)
  2129. def test_inline_formset_error_input_border(self):
  2130. from selenium.webdriver.common.by import By
  2131. self.admin_login(username="super", password="secret")
  2132. self.selenium.get(
  2133. self.live_server_url + reverse("admin:admin_inlines_holder5_add")
  2134. )
  2135. self.wait_until_visible("#id_dummy")
  2136. self.selenium.find_element(By.ID, "id_dummy").send_keys(1)
  2137. fields = ["id_inner5stacked_set-0-dummy", "id_inner5tabular_set-0-dummy"]
  2138. summaries = self.selenium.find_elements(By.TAG_NAME, "summary")
  2139. for show_index, field_name in enumerate(fields):
  2140. summaries[show_index].click()
  2141. self.wait_until_visible("#" + field_name)
  2142. self.selenium.find_element(By.ID, field_name).send_keys(1)
  2143. # Before save all inputs have default border
  2144. for inline in ("stacked", "tabular"):
  2145. for field_name in ("name", "select", "text"):
  2146. element_id = "id_inner5%s_set-0-%s" % (inline, field_name)
  2147. self.assertBorder(
  2148. self.selenium.find_element(By.ID, element_id),
  2149. "1px solid #cccccc",
  2150. )
  2151. self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click()
  2152. # Test the red border around inputs by css selectors
  2153. stacked_selectors = [".errors input", ".errors select", ".errors textarea"]
  2154. for selector in stacked_selectors:
  2155. self.assertBorder(
  2156. self.selenium.find_element(By.CSS_SELECTOR, selector),
  2157. "1px solid #ba2121",
  2158. )
  2159. tabular_selectors = [
  2160. "td ul.errorlist + input",
  2161. "td ul.errorlist + select",
  2162. "td ul.errorlist + textarea",
  2163. ]
  2164. for selector in tabular_selectors:
  2165. self.assertBorder(
  2166. self.selenium.find_element(By.CSS_SELECTOR, selector),
  2167. "1px solid #ba2121",
  2168. )
  2169. def test_inline_formset_error(self):
  2170. from selenium.webdriver.common.by import By
  2171. self.admin_login(username="super", password="secret")
  2172. self.selenium.get(
  2173. self.live_server_url + reverse("admin:admin_inlines_holder5_add")
  2174. )
  2175. stacked_inline_details_selector = (
  2176. "div#inner5stacked_set-group fieldset.module.collapse details"
  2177. )
  2178. tabular_inline_details_selector = (
  2179. "div#inner5tabular_set-group fieldset.module.collapse details"
  2180. )
  2181. # Inlines without errors, both inlines collapsed
  2182. self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click()
  2183. self.assertCountSeleniumElements(
  2184. stacked_inline_details_selector + ":not([open])", 1
  2185. )
  2186. self.assertCountSeleniumElements(
  2187. tabular_inline_details_selector + ":not([open])", 1
  2188. )
  2189. summaries = self.selenium.find_elements(By.TAG_NAME, "summary")
  2190. self.assertEqual(len(summaries), 2)
  2191. # Inlines with errors, both inlines expanded
  2192. test_fields = ["#id_inner5stacked_set-0-dummy", "#id_inner5tabular_set-0-dummy"]
  2193. for show_index, field_name in enumerate(test_fields):
  2194. summaries[show_index].click()
  2195. self.wait_until_visible(field_name)
  2196. self.selenium.find_element(By.ID, field_name[1:]).send_keys(1)
  2197. for hide_index, field_name in enumerate(test_fields):
  2198. summary = summaries[hide_index]
  2199. self.selenium.execute_script(
  2200. "window.scrollTo(0, %s);" % summary.location["y"]
  2201. )
  2202. summary.click()
  2203. self.wait_until_invisible(field_name)
  2204. with self.wait_page_loaded():
  2205. self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click()
  2206. self.assertCountSeleniumElements(stacked_inline_details_selector, 0)
  2207. self.assertCountSeleniumElements(tabular_inline_details_selector, 0)
  2208. def test_inlines_verbose_name(self):
  2209. """
  2210. The item added by the "Add another XXX" link must use the correct
  2211. verbose_name in the inline form.
  2212. """
  2213. from selenium.webdriver.common.by import By
  2214. self.admin_login(username="super", password="secret")
  2215. # Hide sidebar.
  2216. self.selenium.get(
  2217. self.live_server_url + reverse("admin:admin_inlines_course_add")
  2218. )
  2219. toggle_button = self.selenium.find_element(
  2220. By.CSS_SELECTOR, "#toggle-nav-sidebar"
  2221. )
  2222. toggle_button.click()
  2223. # Each combination of horizontal/vertical filter with stacked/tabular
  2224. # inlines.
  2225. tests = [
  2226. "admin:admin_inlines_course_add",
  2227. "admin:admin_inlines_courseproxy_add",
  2228. "admin:admin_inlines_courseproxy1_add",
  2229. "admin:admin_inlines_courseproxy2_add",
  2230. ]
  2231. css_available_selector = (
  2232. ".dynamic-class_set#class_set-%s .selector-available-title"
  2233. )
  2234. css_chosen_selector = ".dynamic-class_set#class_set-%s .selector-chosen-title"
  2235. for url_name in tests:
  2236. with self.subTest(url=url_name):
  2237. self.selenium.get(self.live_server_url + reverse(url_name))
  2238. # First inline shows the verbose_name.
  2239. available = self.selenium.find_element(
  2240. By.CSS_SELECTOR, css_available_selector % 0
  2241. )
  2242. chosen = self.selenium.find_element(
  2243. By.CSS_SELECTOR, css_chosen_selector % 0
  2244. )
  2245. self.assertIn("Available attendant", available.text)
  2246. self.assertIn("Chosen attendant", chosen.text)
  2247. # Added inline should also have the correct verbose_name.
  2248. self.selenium.find_element(By.LINK_TEXT, "Add another Class").click()
  2249. available = self.selenium.find_element(
  2250. By.CSS_SELECTOR, css_available_selector % 1
  2251. )
  2252. chosen = self.selenium.find_element(
  2253. By.CSS_SELECTOR, css_chosen_selector % 1
  2254. )
  2255. self.assertIn("Available attendant", available.text)
  2256. self.assertIn("Chosen attendant", chosen.text)
  2257. # Third inline should also have the correct verbose_name.
  2258. self.selenium.find_element(By.LINK_TEXT, "Add another Class").click()
  2259. available = self.selenium.find_element(
  2260. By.CSS_SELECTOR, css_available_selector % 2
  2261. )
  2262. chosen = self.selenium.find_element(
  2263. By.CSS_SELECTOR, css_chosen_selector % 2
  2264. )
  2265. self.assertIn("Available attendant", available.text)
  2266. self.assertIn("Chosen attendant", chosen.text)
  2267. def test_tabular_inline_layout(self):
  2268. from selenium.webdriver.common.by import By
  2269. self.admin_login(username="super", password="secret")
  2270. self.selenium.get(
  2271. self.live_server_url + reverse("admin:admin_inlines_photographer_add")
  2272. )
  2273. tabular_inline = self.selenium.find_element(
  2274. By.CSS_SELECTOR, "[data-inline-type='tabular']"
  2275. )
  2276. headers = tabular_inline.find_elements(By.TAG_NAME, "th")
  2277. self.assertEqual(
  2278. [h.get_attribute("innerText") for h in headers],
  2279. [
  2280. "",
  2281. "IMAGE",
  2282. "TITLE",
  2283. "DESCRIPTION",
  2284. "CREATION DATE",
  2285. "UPDATE DATE",
  2286. "UPDATED BY",
  2287. "DELETE?",
  2288. ],
  2289. )
  2290. # There are no fieldset section names rendered.
  2291. self.assertNotIn("Details", tabular_inline.text)
  2292. # There are no fieldset section descriptions rendered.
  2293. self.assertNotIn("First group", tabular_inline.text)
  2294. self.assertNotIn("Second group", tabular_inline.text)
  2295. self.assertNotIn("Third group", tabular_inline.text)
  2296. # There are no fieldset classes applied.
  2297. self.assertEqual(
  2298. tabular_inline.find_elements(By.CSS_SELECTOR, ".collapse"),
  2299. [],
  2300. )