tests.py 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  1. from django import forms
  2. from django.contrib import admin
  3. from django.contrib.admin import AdminSite
  4. from django.contrib.auth.backends import ModelBackend
  5. from django.contrib.auth.middleware import AuthenticationMiddleware
  6. from django.contrib.contenttypes.admin import GenericStackedInline
  7. from django.contrib.messages.middleware import MessageMiddleware
  8. from django.contrib.sessions.middleware import SessionMiddleware
  9. from django.core import checks
  10. from django.test import SimpleTestCase, override_settings
  11. from .models import Album, Author, Book, City, Influence, Song, State, TwoAlbumFKAndAnE
  12. class SongForm(forms.ModelForm):
  13. pass
  14. class ValidFields(admin.ModelAdmin):
  15. form = SongForm
  16. fields = ["title"]
  17. class ValidFormFieldsets(admin.ModelAdmin):
  18. def get_form(self, request, obj=None, **kwargs):
  19. class ExtraFieldForm(SongForm):
  20. name = forms.CharField(max_length=50)
  21. return ExtraFieldForm
  22. fieldsets = (
  23. (
  24. None,
  25. {
  26. "fields": ("name",),
  27. },
  28. ),
  29. )
  30. class MyAdmin(admin.ModelAdmin):
  31. def check(self, **kwargs):
  32. return ["error!"]
  33. class AuthenticationMiddlewareSubclass(AuthenticationMiddleware):
  34. pass
  35. class MessageMiddlewareSubclass(MessageMiddleware):
  36. pass
  37. class ModelBackendSubclass(ModelBackend):
  38. pass
  39. class SessionMiddlewareSubclass(SessionMiddleware):
  40. pass
  41. @override_settings(
  42. SILENCED_SYSTEM_CHECKS=["fields.W342"], # ForeignKey(unique=True)
  43. INSTALLED_APPS=[
  44. "django.contrib.admin",
  45. "django.contrib.auth",
  46. "django.contrib.contenttypes",
  47. "django.contrib.messages",
  48. "admin_checks",
  49. ],
  50. )
  51. class SystemChecksTestCase(SimpleTestCase):
  52. databases = "__all__"
  53. def test_checks_are_performed(self):
  54. admin.site.register(Song, MyAdmin)
  55. try:
  56. errors = checks.run_checks()
  57. expected = ["error!"]
  58. self.assertEqual(errors, expected)
  59. finally:
  60. admin.site.unregister(Song)
  61. @override_settings(INSTALLED_APPS=["django.contrib.admin"])
  62. def test_apps_dependencies(self):
  63. errors = admin.checks.check_dependencies()
  64. expected = [
  65. checks.Error(
  66. "'django.contrib.contenttypes' must be in "
  67. "INSTALLED_APPS in order to use the admin application.",
  68. id="admin.E401",
  69. ),
  70. checks.Error(
  71. "'django.contrib.auth' must be in INSTALLED_APPS in order "
  72. "to use the admin application.",
  73. id="admin.E405",
  74. ),
  75. checks.Error(
  76. "'django.contrib.messages' must be in INSTALLED_APPS in order "
  77. "to use the admin application.",
  78. id="admin.E406",
  79. ),
  80. ]
  81. self.assertEqual(errors, expected)
  82. @override_settings(TEMPLATES=[])
  83. def test_no_template_engines(self):
  84. self.assertEqual(
  85. admin.checks.check_dependencies(),
  86. [
  87. checks.Error(
  88. "A 'django.template.backends.django.DjangoTemplates' "
  89. "instance must be configured in TEMPLATES in order to use "
  90. "the admin application.",
  91. id="admin.E403",
  92. )
  93. ],
  94. )
  95. @override_settings(
  96. TEMPLATES=[
  97. {
  98. "BACKEND": "django.template.backends.django.DjangoTemplates",
  99. "DIRS": [],
  100. "APP_DIRS": True,
  101. "OPTIONS": {
  102. "context_processors": [],
  103. },
  104. }
  105. ],
  106. )
  107. def test_context_processor_dependencies(self):
  108. expected = [
  109. checks.Error(
  110. "'django.contrib.auth.context_processors.auth' must be "
  111. "enabled in DjangoTemplates (TEMPLATES) if using the default "
  112. "auth backend in order to use the admin application.",
  113. id="admin.E402",
  114. ),
  115. checks.Error(
  116. "'django.contrib.messages.context_processors.messages' must "
  117. "be enabled in DjangoTemplates (TEMPLATES) in order to use "
  118. "the admin application.",
  119. id="admin.E404",
  120. ),
  121. checks.Warning(
  122. "'django.template.context_processors.request' must be enabled "
  123. "in DjangoTemplates (TEMPLATES) in order to use the admin "
  124. "navigation sidebar.",
  125. id="admin.W411",
  126. ),
  127. ]
  128. self.assertEqual(admin.checks.check_dependencies(), expected)
  129. # The first error doesn't happen if
  130. # 'django.contrib.auth.backends.ModelBackend' isn't in
  131. # AUTHENTICATION_BACKENDS.
  132. with self.settings(AUTHENTICATION_BACKENDS=[]):
  133. self.assertEqual(admin.checks.check_dependencies(), expected[1:])
  134. @override_settings(
  135. AUTHENTICATION_BACKENDS=["admin_checks.tests.ModelBackendSubclass"],
  136. TEMPLATES=[
  137. {
  138. "BACKEND": "django.template.backends.django.DjangoTemplates",
  139. "DIRS": [],
  140. "APP_DIRS": True,
  141. "OPTIONS": {
  142. "context_processors": [
  143. "django.template.context_processors.request",
  144. "django.contrib.messages.context_processors.messages",
  145. ],
  146. },
  147. }
  148. ],
  149. )
  150. def test_context_processor_dependencies_model_backend_subclass(self):
  151. self.assertEqual(
  152. admin.checks.check_dependencies(),
  153. [
  154. checks.Error(
  155. "'django.contrib.auth.context_processors.auth' must be "
  156. "enabled in DjangoTemplates (TEMPLATES) if using the default "
  157. "auth backend in order to use the admin application.",
  158. id="admin.E402",
  159. ),
  160. ],
  161. )
  162. @override_settings(
  163. TEMPLATES=[
  164. {
  165. "BACKEND": "django.template.backends.dummy.TemplateStrings",
  166. "DIRS": [],
  167. "APP_DIRS": True,
  168. },
  169. {
  170. "BACKEND": "django.template.backends.django.DjangoTemplates",
  171. "DIRS": [],
  172. "APP_DIRS": True,
  173. "OPTIONS": {
  174. "context_processors": [
  175. "django.template.context_processors.request",
  176. "django.contrib.auth.context_processors.auth",
  177. "django.contrib.messages.context_processors.messages",
  178. ],
  179. },
  180. },
  181. ],
  182. )
  183. def test_several_templates_backends(self):
  184. self.assertEqual(admin.checks.check_dependencies(), [])
  185. @override_settings(MIDDLEWARE=[])
  186. def test_middleware_dependencies(self):
  187. errors = admin.checks.check_dependencies()
  188. expected = [
  189. checks.Error(
  190. "'django.contrib.auth.middleware.AuthenticationMiddleware' "
  191. "must be in MIDDLEWARE in order to use the admin application.",
  192. id="admin.E408",
  193. ),
  194. checks.Error(
  195. "'django.contrib.messages.middleware.MessageMiddleware' "
  196. "must be in MIDDLEWARE in order to use the admin application.",
  197. id="admin.E409",
  198. ),
  199. checks.Error(
  200. "'django.contrib.sessions.middleware.SessionMiddleware' "
  201. "must be in MIDDLEWARE in order to use the admin application.",
  202. hint=(
  203. "Insert "
  204. "'django.contrib.sessions.middleware.SessionMiddleware' "
  205. "before "
  206. "'django.contrib.auth.middleware.AuthenticationMiddleware'."
  207. ),
  208. id="admin.E410",
  209. ),
  210. ]
  211. self.assertEqual(errors, expected)
  212. @override_settings(
  213. MIDDLEWARE=[
  214. "admin_checks.tests.AuthenticationMiddlewareSubclass",
  215. "admin_checks.tests.MessageMiddlewareSubclass",
  216. "admin_checks.tests.SessionMiddlewareSubclass",
  217. ]
  218. )
  219. def test_middleware_subclasses(self):
  220. self.assertEqual(admin.checks.check_dependencies(), [])
  221. @override_settings(
  222. MIDDLEWARE=[
  223. "django.contrib.does.not.Exist",
  224. "django.contrib.auth.middleware.AuthenticationMiddleware",
  225. "django.contrib.messages.middleware.MessageMiddleware",
  226. "django.contrib.sessions.middleware.SessionMiddleware",
  227. ]
  228. )
  229. def test_admin_check_ignores_import_error_in_middleware(self):
  230. self.assertEqual(admin.checks.check_dependencies(), [])
  231. def test_custom_adminsite(self):
  232. class CustomAdminSite(admin.AdminSite):
  233. pass
  234. custom_site = CustomAdminSite()
  235. custom_site.register(Song, MyAdmin)
  236. try:
  237. errors = checks.run_checks()
  238. expected = ["error!"]
  239. self.assertEqual(errors, expected)
  240. finally:
  241. custom_site.unregister(Song)
  242. def test_allows_checks_relying_on_other_modeladmins(self):
  243. class MyBookAdmin(admin.ModelAdmin):
  244. def check(self, **kwargs):
  245. errors = super().check(**kwargs)
  246. if not self.admin_site.is_registered(Author):
  247. errors.append("AuthorAdmin missing!")
  248. return errors
  249. class MyAuthorAdmin(admin.ModelAdmin):
  250. pass
  251. admin.site.register(Book, MyBookAdmin)
  252. admin.site.register(Author, MyAuthorAdmin)
  253. try:
  254. self.assertEqual(admin.site.check(None), [])
  255. finally:
  256. admin.site.unregister(Book)
  257. admin.site.unregister(Author)
  258. def test_field_name_not_in_list_display(self):
  259. class SongAdmin(admin.ModelAdmin):
  260. list_editable = ["original_release"]
  261. errors = SongAdmin(Song, AdminSite()).check()
  262. expected = [
  263. checks.Error(
  264. "The value of 'list_editable[0]' refers to 'original_release', "
  265. "which is not contained in 'list_display'.",
  266. obj=SongAdmin,
  267. id="admin.E122",
  268. )
  269. ]
  270. self.assertEqual(errors, expected)
  271. def test_list_editable_not_a_list_or_tuple(self):
  272. class SongAdmin(admin.ModelAdmin):
  273. list_editable = "test"
  274. self.assertEqual(
  275. SongAdmin(Song, AdminSite()).check(),
  276. [
  277. checks.Error(
  278. "The value of 'list_editable' must be a list or tuple.",
  279. obj=SongAdmin,
  280. id="admin.E120",
  281. )
  282. ],
  283. )
  284. def test_list_editable_missing_field(self):
  285. class SongAdmin(admin.ModelAdmin):
  286. list_editable = ("test",)
  287. self.assertEqual(
  288. SongAdmin(Song, AdminSite()).check(),
  289. [
  290. checks.Error(
  291. "The value of 'list_editable[0]' refers to 'test', which is "
  292. "not a field of 'admin_checks.Song'.",
  293. obj=SongAdmin,
  294. id="admin.E121",
  295. )
  296. ],
  297. )
  298. def test_readonly_and_editable(self):
  299. class SongAdmin(admin.ModelAdmin):
  300. readonly_fields = ["original_release"]
  301. list_display = ["pk", "original_release"]
  302. list_editable = ["original_release"]
  303. fieldsets = [
  304. (
  305. None,
  306. {
  307. "fields": ["title", "original_release"],
  308. },
  309. ),
  310. ]
  311. errors = SongAdmin(Song, AdminSite()).check()
  312. expected = [
  313. checks.Error(
  314. "The value of 'list_editable[0]' refers to 'original_release', "
  315. "which is not editable through the admin.",
  316. obj=SongAdmin,
  317. id="admin.E125",
  318. )
  319. ]
  320. self.assertEqual(errors, expected)
  321. def test_pk_not_editable(self):
  322. # PKs cannot be edited in the list.
  323. class SongAdmin(admin.ModelAdmin):
  324. list_display = ["title", "id"]
  325. list_editable = ["id"]
  326. errors = SongAdmin(Song, AdminSite()).check()
  327. expected = [
  328. checks.Error(
  329. "The value of 'list_editable[0]' refers to 'id', which is not editable "
  330. "through the admin.",
  331. obj=SongAdmin,
  332. id="admin.E125",
  333. )
  334. ]
  335. self.assertEqual(errors, expected)
  336. def test_editable(self):
  337. class SongAdmin(admin.ModelAdmin):
  338. list_display = ["pk", "title"]
  339. list_editable = ["title"]
  340. fieldsets = [
  341. (
  342. None,
  343. {
  344. "fields": ["title", "original_release"],
  345. },
  346. ),
  347. ]
  348. errors = SongAdmin(Song, AdminSite()).check()
  349. self.assertEqual(errors, [])
  350. def test_custom_modelforms_with_fields_fieldsets(self):
  351. """
  352. # Regression test for #8027: custom ModelForms with fields/fieldsets
  353. """
  354. errors = ValidFields(Song, AdminSite()).check()
  355. self.assertEqual(errors, [])
  356. def test_custom_get_form_with_fieldsets(self):
  357. """
  358. The fieldsets checks are skipped when the ModelAdmin.get_form() method
  359. is overridden.
  360. """
  361. errors = ValidFormFieldsets(Song, AdminSite()).check()
  362. self.assertEqual(errors, [])
  363. def test_fieldsets_fields_non_tuple(self):
  364. """
  365. The first fieldset's fields must be a list/tuple.
  366. """
  367. class NotATupleAdmin(admin.ModelAdmin):
  368. list_display = ["pk", "title"]
  369. list_editable = ["title"]
  370. fieldsets = [
  371. (None, {"fields": "title"}), # not a tuple
  372. ]
  373. errors = NotATupleAdmin(Song, AdminSite()).check()
  374. expected = [
  375. checks.Error(
  376. "The value of 'fieldsets[0][1]['fields']' must be a list or tuple.",
  377. obj=NotATupleAdmin,
  378. id="admin.E008",
  379. )
  380. ]
  381. self.assertEqual(errors, expected)
  382. def test_nonfirst_fieldset(self):
  383. """
  384. The second fieldset's fields must be a list/tuple.
  385. """
  386. class NotATupleAdmin(admin.ModelAdmin):
  387. fieldsets = [
  388. (None, {"fields": ("title",)}),
  389. ("foo", {"fields": "author"}), # not a tuple
  390. ]
  391. errors = NotATupleAdmin(Song, AdminSite()).check()
  392. expected = [
  393. checks.Error(
  394. "The value of 'fieldsets[1][1]['fields']' must be a list or tuple.",
  395. obj=NotATupleAdmin,
  396. id="admin.E008",
  397. )
  398. ]
  399. self.assertEqual(errors, expected)
  400. def test_exclude_values(self):
  401. """
  402. Tests for basic system checks of 'exclude' option values (#12689)
  403. """
  404. class ExcludedFields1(admin.ModelAdmin):
  405. exclude = "foo"
  406. errors = ExcludedFields1(Book, AdminSite()).check()
  407. expected = [
  408. checks.Error(
  409. "The value of 'exclude' must be a list or tuple.",
  410. obj=ExcludedFields1,
  411. id="admin.E014",
  412. )
  413. ]
  414. self.assertEqual(errors, expected)
  415. def test_exclude_duplicate_values(self):
  416. class ExcludedFields2(admin.ModelAdmin):
  417. exclude = ("name", "name")
  418. errors = ExcludedFields2(Book, AdminSite()).check()
  419. expected = [
  420. checks.Error(
  421. "The value of 'exclude' contains duplicate field(s).",
  422. obj=ExcludedFields2,
  423. id="admin.E015",
  424. )
  425. ]
  426. self.assertEqual(errors, expected)
  427. def test_exclude_in_inline(self):
  428. class ExcludedFieldsInline(admin.TabularInline):
  429. model = Song
  430. exclude = "foo"
  431. class ExcludedFieldsAlbumAdmin(admin.ModelAdmin):
  432. model = Album
  433. inlines = [ExcludedFieldsInline]
  434. errors = ExcludedFieldsAlbumAdmin(Album, AdminSite()).check()
  435. expected = [
  436. checks.Error(
  437. "The value of 'exclude' must be a list or tuple.",
  438. obj=ExcludedFieldsInline,
  439. id="admin.E014",
  440. )
  441. ]
  442. self.assertEqual(errors, expected)
  443. def test_exclude_inline_model_admin(self):
  444. """
  445. Regression test for #9932 - exclude in InlineModelAdmin should not
  446. contain the ForeignKey field used in ModelAdmin.model
  447. """
  448. class SongInline(admin.StackedInline):
  449. model = Song
  450. exclude = ["album"]
  451. class AlbumAdmin(admin.ModelAdmin):
  452. model = Album
  453. inlines = [SongInline]
  454. errors = AlbumAdmin(Album, AdminSite()).check()
  455. expected = [
  456. checks.Error(
  457. "Cannot exclude the field 'album', because it is the foreign key "
  458. "to the parent model 'admin_checks.Album'.",
  459. obj=SongInline,
  460. id="admin.E201",
  461. )
  462. ]
  463. self.assertEqual(errors, expected)
  464. def test_valid_generic_inline_model_admin(self):
  465. """
  466. Regression test for #22034 - check that generic inlines don't look for
  467. normal ForeignKey relations.
  468. """
  469. class InfluenceInline(GenericStackedInline):
  470. model = Influence
  471. class SongAdmin(admin.ModelAdmin):
  472. inlines = [InfluenceInline]
  473. errors = SongAdmin(Song, AdminSite()).check()
  474. self.assertEqual(errors, [])
  475. def test_generic_inline_model_admin_non_generic_model(self):
  476. """
  477. A model without a GenericForeignKey raises problems if it's included
  478. in a GenericInlineModelAdmin definition.
  479. """
  480. class BookInline(GenericStackedInline):
  481. model = Book
  482. class SongAdmin(admin.ModelAdmin):
  483. inlines = [BookInline]
  484. errors = SongAdmin(Song, AdminSite()).check()
  485. expected = [
  486. checks.Error(
  487. "'admin_checks.Book' has no GenericForeignKey.",
  488. obj=BookInline,
  489. id="admin.E301",
  490. )
  491. ]
  492. self.assertEqual(errors, expected)
  493. def test_generic_inline_model_admin_bad_ct_field(self):
  494. """
  495. A GenericInlineModelAdmin errors if the ct_field points to a
  496. nonexistent field.
  497. """
  498. class InfluenceInline(GenericStackedInline):
  499. model = Influence
  500. ct_field = "nonexistent"
  501. class SongAdmin(admin.ModelAdmin):
  502. inlines = [InfluenceInline]
  503. errors = SongAdmin(Song, AdminSite()).check()
  504. expected = [
  505. checks.Error(
  506. "'ct_field' references 'nonexistent', which is not a field on "
  507. "'admin_checks.Influence'.",
  508. obj=InfluenceInline,
  509. id="admin.E302",
  510. )
  511. ]
  512. self.assertEqual(errors, expected)
  513. def test_generic_inline_model_admin_bad_fk_field(self):
  514. """
  515. A GenericInlineModelAdmin errors if the ct_fk_field points to a
  516. nonexistent field.
  517. """
  518. class InfluenceInline(GenericStackedInline):
  519. model = Influence
  520. ct_fk_field = "nonexistent"
  521. class SongAdmin(admin.ModelAdmin):
  522. inlines = [InfluenceInline]
  523. errors = SongAdmin(Song, AdminSite()).check()
  524. expected = [
  525. checks.Error(
  526. "'ct_fk_field' references 'nonexistent', which is not a field on "
  527. "'admin_checks.Influence'.",
  528. obj=InfluenceInline,
  529. id="admin.E303",
  530. )
  531. ]
  532. self.assertEqual(errors, expected)
  533. def test_generic_inline_model_admin_non_gfk_ct_field(self):
  534. """
  535. A GenericInlineModelAdmin raises problems if the ct_field points to a
  536. field that isn't part of a GenericForeignKey.
  537. """
  538. class InfluenceInline(GenericStackedInline):
  539. model = Influence
  540. ct_field = "name"
  541. class SongAdmin(admin.ModelAdmin):
  542. inlines = [InfluenceInline]
  543. errors = SongAdmin(Song, AdminSite()).check()
  544. expected = [
  545. checks.Error(
  546. "'admin_checks.Influence' has no GenericForeignKey using "
  547. "content type field 'name' and object ID field 'object_id'.",
  548. obj=InfluenceInline,
  549. id="admin.E304",
  550. )
  551. ]
  552. self.assertEqual(errors, expected)
  553. def test_generic_inline_model_admin_non_gfk_fk_field(self):
  554. """
  555. A GenericInlineModelAdmin raises problems if the ct_fk_field points to
  556. a field that isn't part of a GenericForeignKey.
  557. """
  558. class InfluenceInline(GenericStackedInline):
  559. model = Influence
  560. ct_fk_field = "name"
  561. class SongAdmin(admin.ModelAdmin):
  562. inlines = [InfluenceInline]
  563. errors = SongAdmin(Song, AdminSite()).check()
  564. expected = [
  565. checks.Error(
  566. "'admin_checks.Influence' has no GenericForeignKey using "
  567. "content type field 'content_type' and object ID field 'name'.",
  568. obj=InfluenceInline,
  569. id="admin.E304",
  570. )
  571. ]
  572. self.assertEqual(errors, expected)
  573. def test_app_label_in_admin_checks(self):
  574. class RawIdNonexistentAdmin(admin.ModelAdmin):
  575. raw_id_fields = ("nonexistent",)
  576. errors = RawIdNonexistentAdmin(Album, AdminSite()).check()
  577. expected = [
  578. checks.Error(
  579. "The value of 'raw_id_fields[0]' refers to 'nonexistent', "
  580. "which is not a field of 'admin_checks.Album'.",
  581. obj=RawIdNonexistentAdmin,
  582. id="admin.E002",
  583. )
  584. ]
  585. self.assertEqual(errors, expected)
  586. def test_fk_exclusion(self):
  587. """
  588. Regression test for #11709 - when testing for fk excluding (when exclude is
  589. given) make sure fk_name is honored or things blow up when there is more
  590. than one fk to the parent model.
  591. """
  592. class TwoAlbumFKAndAnEInline(admin.TabularInline):
  593. model = TwoAlbumFKAndAnE
  594. exclude = ("e",)
  595. fk_name = "album1"
  596. class MyAdmin(admin.ModelAdmin):
  597. inlines = [TwoAlbumFKAndAnEInline]
  598. errors = MyAdmin(Album, AdminSite()).check()
  599. self.assertEqual(errors, [])
  600. def test_inline_self_check(self):
  601. class TwoAlbumFKAndAnEInline(admin.TabularInline):
  602. model = TwoAlbumFKAndAnE
  603. class MyAdmin(admin.ModelAdmin):
  604. inlines = [TwoAlbumFKAndAnEInline]
  605. errors = MyAdmin(Album, AdminSite()).check()
  606. expected = [
  607. checks.Error(
  608. "'admin_checks.TwoAlbumFKAndAnE' has more than one ForeignKey "
  609. "to 'admin_checks.Album'. You must specify a 'fk_name' "
  610. "attribute.",
  611. obj=TwoAlbumFKAndAnEInline,
  612. id="admin.E202",
  613. )
  614. ]
  615. self.assertEqual(errors, expected)
  616. def test_inline_with_specified(self):
  617. class TwoAlbumFKAndAnEInline(admin.TabularInline):
  618. model = TwoAlbumFKAndAnE
  619. fk_name = "album1"
  620. class MyAdmin(admin.ModelAdmin):
  621. inlines = [TwoAlbumFKAndAnEInline]
  622. errors = MyAdmin(Album, AdminSite()).check()
  623. self.assertEqual(errors, [])
  624. def test_inlines_property(self):
  625. class CitiesInline(admin.TabularInline):
  626. model = City
  627. class StateAdmin(admin.ModelAdmin):
  628. @property
  629. def inlines(self):
  630. return [CitiesInline]
  631. errors = StateAdmin(State, AdminSite()).check()
  632. self.assertEqual(errors, [])
  633. def test_readonly(self):
  634. class SongAdmin(admin.ModelAdmin):
  635. readonly_fields = ("title",)
  636. errors = SongAdmin(Song, AdminSite()).check()
  637. self.assertEqual(errors, [])
  638. def test_readonly_on_method(self):
  639. @admin.display
  640. def my_function(obj):
  641. pass
  642. class SongAdmin(admin.ModelAdmin):
  643. readonly_fields = (my_function,)
  644. errors = SongAdmin(Song, AdminSite()).check()
  645. self.assertEqual(errors, [])
  646. def test_readonly_on_modeladmin(self):
  647. class SongAdmin(admin.ModelAdmin):
  648. readonly_fields = ("readonly_method_on_modeladmin",)
  649. @admin.display
  650. def readonly_method_on_modeladmin(self, obj):
  651. pass
  652. errors = SongAdmin(Song, AdminSite()).check()
  653. self.assertEqual(errors, [])
  654. def test_readonly_dynamic_attribute_on_modeladmin(self):
  655. class SongAdmin(admin.ModelAdmin):
  656. readonly_fields = ("dynamic_method",)
  657. def __getattr__(self, item):
  658. if item == "dynamic_method":
  659. @admin.display
  660. def method(obj):
  661. pass
  662. return method
  663. raise AttributeError
  664. errors = SongAdmin(Song, AdminSite()).check()
  665. self.assertEqual(errors, [])
  666. def test_readonly_method_on_model(self):
  667. class SongAdmin(admin.ModelAdmin):
  668. readonly_fields = ("readonly_method_on_model",)
  669. errors = SongAdmin(Song, AdminSite()).check()
  670. self.assertEqual(errors, [])
  671. def test_nonexistent_field(self):
  672. class SongAdmin(admin.ModelAdmin):
  673. readonly_fields = ("title", "nonexistent")
  674. errors = SongAdmin(Song, AdminSite()).check()
  675. expected = [
  676. checks.Error(
  677. "The value of 'readonly_fields[1]' refers to 'nonexistent', which is "
  678. "not a callable, an attribute of 'SongAdmin', or an attribute of "
  679. "'admin_checks.Song'.",
  680. obj=SongAdmin,
  681. id="admin.E035",
  682. )
  683. ]
  684. self.assertEqual(errors, expected)
  685. def test_nonexistent_field_on_inline(self):
  686. class CityInline(admin.TabularInline):
  687. model = City
  688. readonly_fields = ["i_dont_exist"] # Missing attribute
  689. errors = CityInline(State, AdminSite()).check()
  690. expected = [
  691. checks.Error(
  692. "The value of 'readonly_fields[0]' refers to 'i_dont_exist', which is "
  693. "not a callable, an attribute of 'CityInline', or an attribute of "
  694. "'admin_checks.City'.",
  695. obj=CityInline,
  696. id="admin.E035",
  697. )
  698. ]
  699. self.assertEqual(errors, expected)
  700. def test_readonly_fields_not_list_or_tuple(self):
  701. class SongAdmin(admin.ModelAdmin):
  702. readonly_fields = "test"
  703. self.assertEqual(
  704. SongAdmin(Song, AdminSite()).check(),
  705. [
  706. checks.Error(
  707. "The value of 'readonly_fields' must be a list or tuple.",
  708. obj=SongAdmin,
  709. id="admin.E034",
  710. )
  711. ],
  712. )
  713. def test_extra(self):
  714. class SongAdmin(admin.ModelAdmin):
  715. @admin.display
  716. def awesome_song(self, instance):
  717. if instance.title == "Born to Run":
  718. return "Best Ever!"
  719. return "Status unknown."
  720. errors = SongAdmin(Song, AdminSite()).check()
  721. self.assertEqual(errors, [])
  722. def test_readonly_lambda(self):
  723. class SongAdmin(admin.ModelAdmin):
  724. readonly_fields = (lambda obj: "test",)
  725. errors = SongAdmin(Song, AdminSite()).check()
  726. self.assertEqual(errors, [])
  727. def test_graceful_m2m_fail(self):
  728. """
  729. Regression test for #12203/#12237 - Fail more gracefully when a M2M field that
  730. specifies the 'through' option is included in the 'fields' or the 'fieldsets'
  731. ModelAdmin options.
  732. """
  733. class BookAdmin(admin.ModelAdmin):
  734. fields = ["authors"]
  735. errors = BookAdmin(Book, AdminSite()).check()
  736. expected = [
  737. checks.Error(
  738. "The value of 'fields' cannot include the ManyToManyField 'authors', "
  739. "because that field manually specifies a relationship model.",
  740. obj=BookAdmin,
  741. id="admin.E013",
  742. )
  743. ]
  744. self.assertEqual(errors, expected)
  745. def test_cannot_include_through(self):
  746. class FieldsetBookAdmin(admin.ModelAdmin):
  747. fieldsets = (
  748. ("Header 1", {"fields": ("name",)}),
  749. ("Header 2", {"fields": ("authors",)}),
  750. )
  751. errors = FieldsetBookAdmin(Book, AdminSite()).check()
  752. expected = [
  753. checks.Error(
  754. "The value of 'fieldsets[1][1][\"fields\"]' cannot include the "
  755. "ManyToManyField 'authors', because that field manually specifies a "
  756. "relationship model.",
  757. obj=FieldsetBookAdmin,
  758. id="admin.E013",
  759. )
  760. ]
  761. self.assertEqual(errors, expected)
  762. def test_nested_fields(self):
  763. class NestedFieldsAdmin(admin.ModelAdmin):
  764. fields = ("price", ("name", "subtitle"))
  765. errors = NestedFieldsAdmin(Book, AdminSite()).check()
  766. self.assertEqual(errors, [])
  767. def test_nested_fieldsets(self):
  768. class NestedFieldsetAdmin(admin.ModelAdmin):
  769. fieldsets = (("Main", {"fields": ("price", ("name", "subtitle"))}),)
  770. errors = NestedFieldsetAdmin(Book, AdminSite()).check()
  771. self.assertEqual(errors, [])
  772. def test_explicit_through_override(self):
  773. """
  774. Regression test for #12209 -- If the explicitly provided through model
  775. is specified as a string, the admin should still be able use
  776. Model.m2m_field.through
  777. """
  778. class AuthorsInline(admin.TabularInline):
  779. model = Book.authors.through
  780. class BookAdmin(admin.ModelAdmin):
  781. inlines = [AuthorsInline]
  782. errors = BookAdmin(Book, AdminSite()).check()
  783. self.assertEqual(errors, [])
  784. def test_non_model_fields(self):
  785. """
  786. Regression for ensuring ModelAdmin.fields can contain non-model fields
  787. that broke with r11737
  788. """
  789. class SongForm(forms.ModelForm):
  790. extra_data = forms.CharField()
  791. class FieldsOnFormOnlyAdmin(admin.ModelAdmin):
  792. form = SongForm
  793. fields = ["title", "extra_data"]
  794. errors = FieldsOnFormOnlyAdmin(Song, AdminSite()).check()
  795. self.assertEqual(errors, [])
  796. def test_non_model_first_field(self):
  797. """
  798. Regression for ensuring ModelAdmin.field can handle first elem being a
  799. non-model field (test fix for UnboundLocalError introduced with r16225).
  800. """
  801. class SongForm(forms.ModelForm):
  802. extra_data = forms.CharField()
  803. class Meta:
  804. model = Song
  805. fields = "__all__"
  806. class FieldsOnFormOnlyAdmin(admin.ModelAdmin):
  807. form = SongForm
  808. fields = ["extra_data", "title"]
  809. errors = FieldsOnFormOnlyAdmin(Song, AdminSite()).check()
  810. self.assertEqual(errors, [])
  811. def test_check_sublists_for_duplicates(self):
  812. class MyModelAdmin(admin.ModelAdmin):
  813. fields = ["state", ["state"]]
  814. errors = MyModelAdmin(Song, AdminSite()).check()
  815. expected = [
  816. checks.Error(
  817. "The value of 'fields' contains duplicate field(s).",
  818. obj=MyModelAdmin,
  819. id="admin.E006",
  820. )
  821. ]
  822. self.assertEqual(errors, expected)
  823. def test_check_fieldset_sublists_for_duplicates(self):
  824. class MyModelAdmin(admin.ModelAdmin):
  825. fieldsets = [
  826. (None, {"fields": ["title", "album", ("title", "album")]}),
  827. ]
  828. errors = MyModelAdmin(Song, AdminSite()).check()
  829. expected = [
  830. checks.Error(
  831. "There are duplicate field(s) in 'fieldsets[0][1]'.",
  832. obj=MyModelAdmin,
  833. id="admin.E012",
  834. )
  835. ]
  836. self.assertEqual(errors, expected)
  837. def test_list_filter_works_on_through_field_even_when_apps_not_ready(self):
  838. """
  839. Ensure list_filter can access reverse fields even when the app registry
  840. is not ready; refs #24146.
  841. """
  842. class BookAdminWithListFilter(admin.ModelAdmin):
  843. list_filter = ["authorsbooks__featured"]
  844. # Temporarily pretending apps are not ready yet. This issue can happen
  845. # if the value of 'list_filter' refers to a 'through__field'.
  846. Book._meta.apps.ready = False
  847. try:
  848. errors = BookAdminWithListFilter(Book, AdminSite()).check()
  849. self.assertEqual(errors, [])
  850. finally:
  851. Book._meta.apps.ready = True
  852. def test_related_field_list_display(self):
  853. class SongAdmin(admin.ModelAdmin):
  854. list_display = ["pk", "original_release", "album__title"]
  855. errors = SongAdmin(Song, AdminSite()).check()
  856. self.assertEqual(errors, [])
  857. def test_related_field_list_display_wrong_field(self):
  858. class SongAdmin(admin.ModelAdmin):
  859. list_display = ["pk", "original_release", "album__hello"]
  860. errors = SongAdmin(Song, AdminSite()).check()
  861. expected = [
  862. checks.Error(
  863. "The value of 'list_display[2]' refers to 'album__hello', which is not "
  864. "a callable or attribute of 'SongAdmin', or an attribute, method, or "
  865. "field on 'admin_checks.Song'.",
  866. obj=SongAdmin,
  867. id="admin.E108",
  868. )
  869. ]
  870. self.assertEqual(errors, expected)