tests.py 96 KB

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