tests.py 31 KB

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