Debian Codegraph @

tests/admin_checks/tests.py

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