Debian Codegraph @

django/contrib/admin/checks.py

raw
1 import collections
2 from itertools import chain
3
4 from django.apps import apps
5 from django.conf import settings
6 from django.contrib.admin.exceptions import NotRegistered
7 from django.contrib.admin.utils import NotRelationField, flatten, get_fields_from_path
8 from django.core import checks
9 from django.core.exceptions import FieldDoesNotExist
10 from django.db import models
11 from django.db.models.constants import LOOKUP_SEP
12 from django.db.models.expressions import Combinable
13 from django.forms.models import BaseModelForm, BaseModelFormSet, _get_foreign_key
14 from django.template import engines
15 from django.template.backends.django import DjangoTemplates
16 from django.utils.module_loading import import_string
17
18
19 def _issubclass(cls, classinfo):
20 """
21 issubclass() variant that doesn't raise an exception if cls isn't a
22 class.
23 """
24 try:
25 return issubclass(cls, classinfo)
26 except TypeError:
27 return False
28
29
30 def _contains_subclass(class_path, candidate_paths):
31 """
32 Return whether or not a dotted class path (or a subclass of that class) is
33 found in a list of candidate paths.
34 """
35 cls = import_string(class_path)
36 for path in candidate_paths:
37 try:
38 candidate_cls = import_string(path)
39 except ImportError:
40 # ImportErrors are raised elsewhere.
41 continue
42 if _issubclass(candidate_cls, cls):
43 return True
44 return False
45
46
47 def check_admin_app(app_configs, **kwargs):
48 from django.contrib.admin.sites import all_sites
49
50 errors = []
51 for site in all_sites:
52 errors.extend(site.check(app_configs))
53 return errors
54
55
56 def check_dependencies(**kwargs):
57 """
58 Check that the admin's dependencies are correctly installed.
59 """
60 from django.contrib.admin.sites import all_sites
61
62 if not apps.is_installed("django.contrib.admin"):
63 return []
64 errors = []
65 app_dependencies = (
66 ("django.contrib.contenttypes", 401),
67 ("django.contrib.auth", 405),
68 ("django.contrib.messages", 406),
69 )
70 for app_name, error_code in app_dependencies:
71 if not apps.is_installed(app_name):
72 errors.append(
73 checks.Error(
74 "'%s' must be in INSTALLED_APPS in order to use the admin "
75 "application." % app_name,
76 id="admin.E%d" % error_code,
77 )
78 )
79 for engine in engines.all():
80 if isinstance(engine, DjangoTemplates):
81 django_templates_instance = engine.engine
82 break
83 else:
84 django_templates_instance = None
85 if not django_templates_instance:
86 errors.append(
87 checks.Error(
88 "A 'django.template.backends.django.DjangoTemplates' instance "
89 "must be configured in TEMPLATES in order to use the admin "
90 "application.",
91 id="admin.E403",
92 )
93 )
94 else:
95 if (
96 "django.contrib.auth.context_processors.auth"
97 not in django_templates_instance.context_processors
98 and _contains_subclass(
99 "django.contrib.auth.backends.ModelBackend",
100 settings.AUTHENTICATION_BACKENDS,
101 )
102 ):
103 errors.append(
104 checks.Error(
105 "'django.contrib.auth.context_processors.auth' must be "
106 "enabled in DjangoTemplates (TEMPLATES) if using the default "
107 "auth backend in order to use the admin application.",
108 id="admin.E402",
109 )
110 )
111 if (
112 "django.contrib.messages.context_processors.messages"
113 not in django_templates_instance.context_processors
114 ):
115 errors.append(
116 checks.Error(
117 "'django.contrib.messages.context_processors.messages' must "
118 "be enabled in DjangoTemplates (TEMPLATES) in order to use "
119 "the admin application.",
120 id="admin.E404",
121 )
122 )
123 sidebar_enabled = any(site.enable_nav_sidebar for site in all_sites)
124 if (
125 sidebar_enabled
126 and "django.template.context_processors.request"
127 not in django_templates_instance.context_processors
128 ):
129 errors.append(
130 checks.Warning(
131 "'django.template.context_processors.request' must be enabled "
132 "in DjangoTemplates (TEMPLATES) in order to use the admin "
133 "navigation sidebar.",
134 id="admin.W411",
135 )
136 )
137
138 if not _contains_subclass(
139 "django.contrib.auth.middleware.AuthenticationMiddleware", settings.MIDDLEWARE
140 ):
141 errors.append(
142 checks.Error(
143 "'django.contrib.auth.middleware.AuthenticationMiddleware' must "
144 "be in MIDDLEWARE in order to use the admin application.",
145 id="admin.E408",
146 )
147 )
148 if not _contains_subclass(
149 "django.contrib.messages.middleware.MessageMiddleware", settings.MIDDLEWARE
150 ):
151 errors.append(
152 checks.Error(
153 "'django.contrib.messages.middleware.MessageMiddleware' must "
154 "be in MIDDLEWARE in order to use the admin application.",
155 id="admin.E409",
156 )
157 )
158 if not _contains_subclass(
159 "django.contrib.sessions.middleware.SessionMiddleware", settings.MIDDLEWARE
160 ):
161 errors.append(
162 checks.Error(
163 "'django.contrib.sessions.middleware.SessionMiddleware' must "
164 "be in MIDDLEWARE in order to use the admin application.",
165 hint=(
166 "Insert "
167 "'django.contrib.sessions.middleware.SessionMiddleware' "
168 "before "
169 "'django.contrib.auth.middleware.AuthenticationMiddleware'."
170 ),
171 id="admin.E410",
172 )
173 )
174 return errors
175
176
177 class BaseModelAdminChecks:
178 def check(self, admin_obj, **kwargs):
179 return [
180 *self._check_autocomplete_fields(admin_obj),
181 *self._check_raw_id_fields(admin_obj),
182 *self._check_fields(admin_obj),
183 *self._check_fieldsets(admin_obj),
184 *self._check_exclude(admin_obj),
185 *self._check_form(admin_obj),
186 *self._check_filter_vertical(admin_obj),
187 *self._check_filter_horizontal(admin_obj),
188 *self._check_radio_fields(admin_obj),
189 *self._check_prepopulated_fields(admin_obj),
190 *self._check_view_on_site_url(admin_obj),
191 *self._check_ordering(admin_obj),
192 *self._check_readonly_fields(admin_obj),
193 ]
194
195 def _check_autocomplete_fields(self, obj):
196 """
197 Check that `autocomplete_fields` is a list or tuple of model fields.
198 """
199 if not isinstance(obj.autocomplete_fields, (list, tuple)):
200 return must_be(
201 "a list or tuple",
202 option="autocomplete_fields",
203 obj=obj,
204 id="admin.E036",
205 )
206 else:
207 return list(
208 chain.from_iterable(
209 [
210 self._check_autocomplete_fields_item(
211 obj, field_name, "autocomplete_fields[%d]" % index
212 )
213 for index, field_name in enumerate(obj.autocomplete_fields)
214 ]
215 )
216 )
217
218 def _check_autocomplete_fields_item(self, obj, field_name, label):
219 """
220 Check that an item in `autocomplete_fields` is a ForeignKey or a
221 ManyToManyField and that the item has a related ModelAdmin with
222 search_fields defined.
223 """
224 try:
225 field = obj.model._meta.get_field(field_name)
226 except FieldDoesNotExist:
227 return refer_to_missing_field(
228 field=field_name, option=label, obj=obj, id="admin.E037"
229 )
230 else:
231 if not field.many_to_many and not isinstance(field, models.ForeignKey):
232 return must_be(
233 "a foreign key or a many-to-many field",
234 option=label,
235 obj=obj,
236 id="admin.E038",
237 )
238 try:
239 related_admin = obj.admin_site.get_model_admin(field.remote_field.model)
240 except NotRegistered:
241 return [
242 checks.Error(
243 'An admin for model "%s" has to be registered '
244 "to be referenced by %s.autocomplete_fields."
245 % (
246 field.remote_field.model.__name__,
247 type(obj).__name__,
248 ),
249 obj=obj.__class__,
250 id="admin.E039",
251 )
252 ]
253 else:
254 if not related_admin.search_fields:
255 return [
256 checks.Error(
257 '%s must define "search_fields", because it\'s '
258 "referenced by %s.autocomplete_fields."
259 % (
260 related_admin.__class__.__name__,
261 type(obj).__name__,
262 ),
263 obj=obj.__class__,
264 id="admin.E040",
265 )
266 ]
267 return []
268
269 def _check_raw_id_fields(self, obj):
270 """Check that `raw_id_fields` only contains field names that are listed
271 on the model."""
272
273 if not isinstance(obj.raw_id_fields, (list, tuple)):
274 return must_be(
275 "a list or tuple", option="raw_id_fields", obj=obj, id="admin.E001"
276 )
277 else:
278 return list(
279 chain.from_iterable(
280 self._check_raw_id_fields_item(
281 obj, field_name, "raw_id_fields[%d]" % index
282 )
283 for index, field_name in enumerate(obj.raw_id_fields)
284 )
285 )
286
287 def _check_raw_id_fields_item(self, obj, field_name, label):
288 """Check an item of `raw_id_fields`, i.e. check that field named
289 `field_name` exists in model `model` and is a ForeignKey or a
290 ManyToManyField."""
291
292 try:
293 field = obj.model._meta.get_field(field_name)
294 except FieldDoesNotExist:
295 return refer_to_missing_field(
296 field=field_name, option=label, obj=obj, id="admin.E002"
297 )
298 else:
299 # Using attname is not supported.
300 if field.name != field_name:
301 return refer_to_missing_field(
302 field=field_name,
303 option=label,
304 obj=obj,
305 id="admin.E002",
306 )
307 if not field.many_to_many and not isinstance(field, models.ForeignKey):
308 return must_be(
309 "a foreign key or a many-to-many field",
310 option=label,
311 obj=obj,
312 id="admin.E003",
313 )
314 else:
315 return []
316
317 def _check_fields(self, obj):
318 """Check that `fields` only refer to existing fields, doesn't contain
319 duplicates. Check if at most one of `fields` and `fieldsets` is defined.
320 """
321
322 if obj.fields is None:
323 return []
324 elif not isinstance(obj.fields, (list, tuple)):
325 return must_be("a list or tuple", option="fields", obj=obj, id="admin.E004")
326 elif obj.fieldsets:
327 return [
328 checks.Error(
329 "Both 'fieldsets' and 'fields' are specified.",
330 obj=obj.__class__,
331 id="admin.E005",
332 )
333 ]
334 fields = flatten(obj.fields)
335 if len(fields) != len(set(fields)):
336 return [
337 checks.Error(
338 "The value of 'fields' contains duplicate field(s).",
339 obj=obj.__class__,
340 id="admin.E006",
341 )
342 ]
343
344 return list(
345 chain.from_iterable(
346 self._check_field_spec(obj, field_name, "fields")
347 for field_name in obj.fields
348 )
349 )
350
351 def _check_fieldsets(self, obj):
352 """Check that fieldsets is properly formatted and doesn't contain
353 duplicates."""
354
355 if obj.fieldsets is None:
356 return []
357 elif not isinstance(obj.fieldsets, (list, tuple)):
358 return must_be(
359 "a list or tuple", option="fieldsets", obj=obj, id="admin.E007"
360 )
361 else:
362 seen_fields = []
363 return list(
364 chain.from_iterable(
365 self._check_fieldsets_item(
366 obj, fieldset, "fieldsets[%d]" % index, seen_fields
367 )
368 for index, fieldset in enumerate(obj.fieldsets)
369 )
370 )
371
372 def _check_fieldsets_item(self, obj, fieldset, label, seen_fields):
373 """Check an item of `fieldsets`, i.e. check that this is a pair of a
374 set name and a dictionary containing "fields" key."""
375
376 if not isinstance(fieldset, (list, tuple)):
377 return must_be("a list or tuple", option=label, obj=obj, id="admin.E008")
378 elif len(fieldset) != 2:
379 return must_be("of length 2", option=label, obj=obj, id="admin.E009")
380 elif not isinstance(fieldset[1], dict):
381 return must_be(
382 "a dictionary", option="%s[1]" % label, obj=obj, id="admin.E010"
383 )
384 elif "fields" not in fieldset[1]:
385 return [
386 checks.Error(
387 "The value of '%s[1]' must contain the key 'fields'." % label,
388 obj=obj.__class__,
389 id="admin.E011",
390 )
391 ]
392 elif not isinstance(fieldset[1]["fields"], (list, tuple)):
393 return must_be(
394 "a list or tuple",
395 option="%s[1]['fields']" % label,
396 obj=obj,
397 id="admin.E008",
398 )
399
400 seen_fields.extend(flatten(fieldset[1]["fields"]))
401 if len(seen_fields) != len(set(seen_fields)):
402 return [
403 checks.Error(
404 "There are duplicate field(s) in '%s[1]'." % label,
405 obj=obj.__class__,
406 id="admin.E012",
407 )
408 ]
409 return list(
410 chain.from_iterable(
411 self._check_field_spec(obj, fieldset_fields, '%s[1]["fields"]' % label)
412 for fieldset_fields in fieldset[1]["fields"]
413 )
414 )
415
416 def _check_field_spec(self, obj, fields, label):
417 """`fields` should be an item of `fields` or an item of
418 fieldset[1]['fields'] for any `fieldset` in `fieldsets`. It should be a
419 field name or a tuple of field names."""
420
421 if isinstance(fields, tuple):
422 return list(
423 chain.from_iterable(
424 self._check_field_spec_item(
425 obj, field_name, "%s[%d]" % (label, index)
426 )
427 for index, field_name in enumerate(fields)
428 )
429 )
430 else:
431 return self._check_field_spec_item(obj, fields, label)
432
433 def _check_field_spec_item(self, obj, field_name, label):
434 if field_name in obj.readonly_fields:
435 # Stuff can be put in fields that isn't actually a model field if
436 # it's in readonly_fields, readonly_fields will handle the
437 # validation of such things.
438 return []
439 else:
440 try:
441 field = obj.model._meta.get_field(field_name)
442 except FieldDoesNotExist:
443 # If we can't find a field on the model that matches, it could
444 # be an extra field on the form.
445 return []
446 else:
447 if (
448 isinstance(field, models.ManyToManyField)
449 and not field.remote_field.through._meta.auto_created
450 ):
451 return [
452 checks.Error(
453 "The value of '%s' cannot include the ManyToManyField "
454 "'%s', because that field manually specifies a "
455 "relationship model." % (label, field_name),
456 obj=obj.__class__,
457 id="admin.E013",
458 )
459 ]
460 else:
461 return []
462
463 def _check_exclude(self, obj):
464 """Check that exclude is a sequence without duplicates."""
465
466 if obj.exclude is None: # default value is None
467 return []
468 elif not isinstance(obj.exclude, (list, tuple)):
469 return must_be(
470 "a list or tuple", option="exclude", obj=obj, id="admin.E014"
471 )
472 elif len(obj.exclude) > len(set(obj.exclude)):
473 return [
474 checks.Error(
475 "The value of 'exclude' contains duplicate field(s).",
476 obj=obj.__class__,
477 id="admin.E015",
478 )
479 ]
480 else:
481 return []
482
483 def _check_form(self, obj):
484 """Check that form subclasses BaseModelForm."""
485 if not _issubclass(obj.form, BaseModelForm):
486 return must_inherit_from(
487 parent="BaseModelForm", option="form", obj=obj, id="admin.E016"
488 )
489 else:
490 return []
491
492 def _check_filter_vertical(self, obj):
493 """Check that filter_vertical is a sequence of field names."""
494 if not isinstance(obj.filter_vertical, (list, tuple)):
495 return must_be(
496 "a list or tuple", option="filter_vertical", obj=obj, id="admin.E017"
497 )
498 else:
499 return list(
500 chain.from_iterable(
501 self._check_filter_item(
502 obj, field_name, "filter_vertical[%d]" % index
503 )
504 for index, field_name in enumerate(obj.filter_vertical)
505 )
506 )
507
508 def _check_filter_horizontal(self, obj):
509 """Check that filter_horizontal is a sequence of field names."""
510 if not isinstance(obj.filter_horizontal, (list, tuple)):
511 return must_be(
512 "a list or tuple", option="filter_horizontal", obj=obj, id="admin.E018"
513 )
514 else:
515 return list(
516 chain.from_iterable(
517 self._check_filter_item(
518 obj, field_name, "filter_horizontal[%d]" % index
519 )
520 for index, field_name in enumerate(obj.filter_horizontal)
521 )
522 )
523
524 def _check_filter_item(self, obj, field_name, label):
525 """Check one item of `filter_vertical` or `filter_horizontal`, i.e.
526 check that given field exists and is a ManyToManyField."""
527
528 try:
529 field = obj.model._meta.get_field(field_name)
530 except FieldDoesNotExist:
531 return refer_to_missing_field(
532 field=field_name, option=label, obj=obj, id="admin.E019"
533 )
534 else:
535 if not field.many_to_many or isinstance(field, models.ManyToManyRel):
536 return must_be(
537 "a many-to-many field", option=label, obj=obj, id="admin.E020"
538 )
539 elif not field.remote_field.through._meta.auto_created:
540 return [
541 checks.Error(
542 f"The value of '{label}' cannot include the ManyToManyField "
543 f"'{field_name}', because that field manually specifies a "
544 f"relationship model.",
545 obj=obj.__class__,
546 id="admin.E013",
547 )
548 ]
549 else:
550 return []
551
552 def _check_radio_fields(self, obj):
553 """Check that `radio_fields` is a dictionary."""
554 if not isinstance(obj.radio_fields, dict):
555 return must_be(
556 "a dictionary", option="radio_fields", obj=obj, id="admin.E021"
557 )
558 else:
559 return list(
560 chain.from_iterable(
561 self._check_radio_fields_key(obj, field_name, "radio_fields")
562 + self._check_radio_fields_value(
563 obj, val, 'radio_fields["%s"]' % field_name
564 )
565 for field_name, val in obj.radio_fields.items()
566 )
567 )
568
569 def _check_radio_fields_key(self, obj, field_name, label):
570 """Check that a key of `radio_fields` dictionary is name of existing
571 field and that the field is a ForeignKey or has `choices` defined."""
572
573 try:
574 field = obj.model._meta.get_field(field_name)
575 except FieldDoesNotExist:
576 return refer_to_missing_field(
577 field=field_name, option=label, obj=obj, id="admin.E022"
578 )
579 else:
580 if not (isinstance(field, models.ForeignKey) or field.choices):
581 return [
582 checks.Error(
583 "The value of '%s' refers to '%s', which is not an "
584 "instance of ForeignKey, and does not have a 'choices' "
585 "definition." % (label, field_name),
586 obj=obj.__class__,
587 id="admin.E023",
588 )
589 ]
590 else:
591 return []
592
593 def _check_radio_fields_value(self, obj, val, label):
594 """Check type of a value of `radio_fields` dictionary."""
595
596 from django.contrib.admin.options import HORIZONTAL, VERTICAL
597
598 if val not in (HORIZONTAL, VERTICAL):
599 return [
600 checks.Error(
601 "The value of '%s' must be either admin.HORIZONTAL or "
602 "admin.VERTICAL." % label,
603 obj=obj.__class__,
604 id="admin.E024",
605 )
606 ]
607 else:
608 return []
609
610 def _check_view_on_site_url(self, obj):
611 if not callable(obj.view_on_site) and not isinstance(obj.view_on_site, bool):
612 return [
613 checks.Error(
614 "The value of 'view_on_site' must be a callable or a boolean "
615 "value.",
616 obj=obj.__class__,
617 id="admin.E025",
618 )
619 ]
620 else:
621 return []
622
623 def _check_prepopulated_fields(self, obj):
624 """Check that `prepopulated_fields` is a dictionary containing allowed
625 field types."""
626 if not isinstance(obj.prepopulated_fields, dict):
627 return must_be(
628 "a dictionary", option="prepopulated_fields", obj=obj, id="admin.E026"
629 )
630 else:
631 return list(
632 chain.from_iterable(
633 self._check_prepopulated_fields_key(
634 obj, field_name, "prepopulated_fields"
635 )
636 + self._check_prepopulated_fields_value(
637 obj, val, 'prepopulated_fields["%s"]' % field_name
638 )
639 for field_name, val in obj.prepopulated_fields.items()
640 )
641 )
642
643 def _check_prepopulated_fields_key(self, obj, field_name, label):
644 """Check a key of `prepopulated_fields` dictionary, i.e. check that it
645 is a name of existing field and the field is one of the allowed types.
646 """
647
648 try:
649 field = obj.model._meta.get_field(field_name)
650 except FieldDoesNotExist:
651 return refer_to_missing_field(
652 field=field_name, option=label, obj=obj, id="admin.E027"
653 )
654 else:
655 if isinstance(
656 field, (models.DateTimeField, models.ForeignKey, models.ManyToManyField)
657 ):
658 return [
659 checks.Error(
660 "The value of '%s' refers to '%s', which must not be a "
661 "DateTimeField, a ForeignKey, a OneToOneField, or a "
662 "ManyToManyField." % (label, field_name),
663 obj=obj.__class__,
664 id="admin.E028",
665 )
666 ]
667 else:
668 return []
669
670 def _check_prepopulated_fields_value(self, obj, val, label):
671 """Check a value of `prepopulated_fields` dictionary, i.e. it's an
672 iterable of existing fields."""
673
674 if not isinstance(val, (list, tuple)):
675 return must_be("a list or tuple", option=label, obj=obj, id="admin.E029")
676 else:
677 return list(
678 chain.from_iterable(
679 self._check_prepopulated_fields_value_item(
680 obj, subfield_name, "%s[%r]" % (label, index)
681 )
682 for index, subfield_name in enumerate(val)
683 )
684 )
685
686 def _check_prepopulated_fields_value_item(self, obj, field_name, label):
687 """For `prepopulated_fields` equal to {"slug": ("title",)},
688 `field_name` is "title"."""
689
690 try:
691 obj.model._meta.get_field(field_name)
692 except FieldDoesNotExist:
693 return refer_to_missing_field(
694 field=field_name, option=label, obj=obj, id="admin.E030"
695 )
696 else:
697 return []
698
699 def _check_ordering(self, obj):
700 """Check that ordering refers to existing fields or is random."""
701
702 # ordering = None
703 if obj.ordering is None: # The default value is None
704 return []
705 elif not isinstance(obj.ordering, (list, tuple)):
706 return must_be(
707 "a list or tuple", option="ordering", obj=obj, id="admin.E031"
708 )
709 else:
710 return list(
711 chain.from_iterable(
712 self._check_ordering_item(obj, field_name, "ordering[%d]" % index)
713 for index, field_name in enumerate(obj.ordering)
714 )
715 )
716
717 def _check_ordering_item(self, obj, field_name, label):
718 """Check that `ordering` refers to existing fields."""
719 if isinstance(field_name, (Combinable, models.OrderBy)):
720 if not isinstance(field_name, models.OrderBy):
721 field_name = field_name.asc()
722 if isinstance(field_name.expression, models.F):
723 field_name = field_name.expression.name
724 else:
725 return []
726 if field_name == "?" and len(obj.ordering) != 1:
727 return [
728 checks.Error(
729 "The value of 'ordering' has the random ordering marker '?', "
730 "but contains other fields as well.",
731 hint='Either remove the "?", or remove the other fields.',
732 obj=obj.__class__,
733 id="admin.E032",
734 )
735 ]
736 elif field_name == "?":
737 return []
738 elif LOOKUP_SEP in field_name:
739 # Skip ordering in the format field1__field2 (FIXME: checking
740 # this format would be nice, but it's a little fiddly).
741 return []
742 else:
743 field_name = field_name.removeprefix("-")
744 if field_name == "pk":
745 return []
746 try:
747 obj.model._meta.get_field(field_name)
748 except FieldDoesNotExist:
749 return refer_to_missing_field(
750 field=field_name, option=label, obj=obj, id="admin.E033"
751 )
752 else:
753 return []
754
755 def _check_readonly_fields(self, obj):
756 """Check that readonly_fields refers to proper attribute or field."""
757
758 if obj.readonly_fields == ():
759 return []
760 elif not isinstance(obj.readonly_fields, (list, tuple)):
761 return must_be(
762 "a list or tuple", option="readonly_fields", obj=obj, id="admin.E034"
763 )
764 else:
765 return list(
766 chain.from_iterable(
767 self._check_readonly_fields_item(
768 obj, field_name, "readonly_fields[%d]" % index
769 )
770 for index, field_name in enumerate(obj.readonly_fields)
771 )
772 )
773
774 def _check_readonly_fields_item(self, obj, field_name, label):
775 if callable(field_name):
776 return []
777 elif hasattr(obj, field_name):
778 return []
779 elif hasattr(obj.model, field_name):
780 return []
781 else:
782 try:
783 obj.model._meta.get_field(field_name)
784 except FieldDoesNotExist:
785 return [
786 checks.Error(
787 "The value of '%s' refers to '%s', which is not a callable, "
788 "an attribute of '%s', or an attribute of '%s'."
789 % (
790 label,
791 field_name,
792 obj.__class__.__name__,
793 obj.model._meta.label,
794 ),
795 obj=obj.__class__,
796 id="admin.E035",
797 )
798 ]
799 else:
800 return []
801
802
803 class ModelAdminChecks(BaseModelAdminChecks):
804 def check(self, admin_obj, **kwargs):
805 return [
806 *super().check(admin_obj),
807 *self._check_save_as(admin_obj),
808 *self._check_save_on_top(admin_obj),
809 *self._check_inlines(admin_obj),
810 *self._check_list_display(admin_obj),
811 *self._check_list_display_links(admin_obj),
812 *self._check_list_filter(admin_obj),
813 *self._check_list_select_related(admin_obj),
814 *self._check_list_per_page(admin_obj),
815 *self._check_list_max_show_all(admin_obj),
816 *self._check_list_editable(admin_obj),
817 *self._check_search_fields(admin_obj),
818 *self._check_date_hierarchy(admin_obj),
819 *self._check_actions(admin_obj),
820 ]
821
822 def _check_save_as(self, obj):
823 """Check save_as is a boolean."""
824
825 if not isinstance(obj.save_as, bool):
826 return must_be("a boolean", option="save_as", obj=obj, id="admin.E101")
827 else:
828 return []
829
830 def _check_save_on_top(self, obj):
831 """Check save_on_top is a boolean."""
832
833 if not isinstance(obj.save_on_top, bool):
834 return must_be("a boolean", option="save_on_top", obj=obj, id="admin.E102")
835 else:
836 return []
837
838 def _check_inlines(self, obj):
839 """Check all inline model admin classes."""
840
841 if not isinstance(obj.inlines, (list, tuple)):
842 return must_be(
843 "a list or tuple", option="inlines", obj=obj, id="admin.E103"
844 )
845 else:
846 return list(
847 chain.from_iterable(
848 self._check_inlines_item(obj, item, "inlines[%d]" % index)
849 for index, item in enumerate(obj.inlines)
850 )
851 )
852
853 def _check_inlines_item(self, obj, inline, label):
854 """Check one inline model admin."""
855 try:
856 inline_label = inline.__module__ + "." + inline.__name__
857 except AttributeError:
858 return [
859 checks.Error(
860 "'%s' must inherit from 'InlineModelAdmin'." % obj,
861 obj=obj.__class__,
862 id="admin.E104",
863 )
864 ]
865
866 from django.contrib.admin.options import InlineModelAdmin
867
868 if not _issubclass(inline, InlineModelAdmin):
869 return [
870 checks.Error(
871 "'%s' must inherit from 'InlineModelAdmin'." % inline_label,
872 obj=obj.__class__,
873 id="admin.E104",
874 )
875 ]
876 elif not inline.model:
877 return [
878 checks.Error(
879 "'%s' must have a 'model' attribute." % inline_label,
880 obj=obj.__class__,
881 id="admin.E105",
882 )
883 ]
884 elif not _issubclass(inline.model, models.Model):
885 return must_be(
886 "a Model", option="%s.model" % inline_label, obj=obj, id="admin.E106"
887 )
888 else:
889 return inline(obj.model, obj.admin_site).check()
890
891 def _check_list_display(self, obj):
892 """Check that list_display only contains fields or usable attributes."""
893
894 if not isinstance(obj.list_display, (list, tuple)):
895 return must_be(
896 "a list or tuple", option="list_display", obj=obj, id="admin.E107"
897 )
898 else:
899 return list(
900 chain.from_iterable(
901 self._check_list_display_item(obj, item, "list_display[%d]" % index)
902 for index, item in enumerate(obj.list_display)
903 )
904 )
905
906 def _check_list_display_item(self, obj, item, label):
907 if callable(item):
908 return []
909 elif hasattr(obj, item):
910 return []
911 try:
912 field = obj.model._meta.get_field(item)
913 except FieldDoesNotExist:
914 try:
915 field = getattr(obj.model, item)
916 except AttributeError:
917 try:
918 field = get_fields_from_path(obj.model, item)[-1]
919 except (FieldDoesNotExist, NotRelationField):
920 return [
921 checks.Error(
922 f"The value of '{label}' refers to '{item}', which is not "
923 f"a callable or attribute of '{obj.__class__.__name__}', "
924 "or an attribute, method, or field on "
925 f"'{obj.model._meta.label}'.",
926 obj=obj.__class__,
927 id="admin.E108",
928 )
929 ]
930 if (
931 getattr(field, "is_relation", False)
932 and (field.many_to_many or field.one_to_many)
933 ) or (getattr(field, "rel", None) and field.rel.field.many_to_one):
934 return [
935 checks.Error(
936 f"The value of '{label}' must not be a many-to-many field or a "
937 f"reverse foreign key.",
938 obj=obj.__class__,
939 id="admin.E109",
940 )
941 ]
942 return []
943
944 def _check_list_display_links(self, obj):
945 """Check that list_display_links is a unique subset of list_display."""
946 from django.contrib.admin.options import ModelAdmin
947
948 if obj.list_display_links is None:
949 return []
950 elif not isinstance(obj.list_display_links, (list, tuple)):
951 return must_be(
952 "a list, a tuple, or None",
953 option="list_display_links",
954 obj=obj,
955 id="admin.E110",
956 )
957 # Check only if ModelAdmin.get_list_display() isn't overridden.
958 elif obj.get_list_display.__func__ is ModelAdmin.get_list_display:
959 return list(
960 chain.from_iterable(
961 self._check_list_display_links_item(
962 obj, field_name, "list_display_links[%d]" % index
963 )
964 for index, field_name in enumerate(obj.list_display_links)
965 )
966 )
967 return []
968
969 def _check_list_display_links_item(self, obj, field_name, label):
970 if field_name not in obj.list_display:
971 return [
972 checks.Error(
973 "The value of '%s' refers to '%s', which is not defined in "
974 "'list_display'." % (label, field_name),
975 obj=obj.__class__,
976 id="admin.E111",
977 )
978 ]
979 else:
980 return []
981
982 def _check_list_filter(self, obj):
983 if not isinstance(obj.list_filter, (list, tuple)):
984 return must_be(
985 "a list or tuple", option="list_filter", obj=obj, id="admin.E112"
986 )
987 else:
988 return list(
989 chain.from_iterable(
990 self._check_list_filter_item(obj, item, "list_filter[%d]" % index)
991 for index, item in enumerate(obj.list_filter)
992 )
993 )
994
995 def _check_list_filter_item(self, obj, item, label):
996 """
997 Check one item of `list_filter`, i.e. check if it is one of three options:
998 1. 'field' -- a basic field filter, possibly w/ relationships (e.g.
999 'field__rel')
1000 2. ('field', SomeFieldListFilter) - a field-based list filter class
1001 3. SomeListFilter - a non-field list filter class
1002 """
1003 from django.contrib.admin import FieldListFilter, ListFilter
1004
1005 if callable(item) and not isinstance(item, models.Field):
1006 # If item is option 3, it should be a ListFilter...
1007 if not _issubclass(item, ListFilter):
1008 return must_inherit_from(
1009 parent="ListFilter", option=label, obj=obj, id="admin.E113"
1010 )
1011 # ... but not a FieldListFilter.
1012 elif issubclass(item, FieldListFilter):
1013 return [
1014 checks.Error(
1015 "The value of '%s' must not inherit from 'FieldListFilter'."
1016 % label,
1017 obj=obj.__class__,
1018 id="admin.E114",
1019 )
1020 ]
1021 else:
1022 return []
1023 elif isinstance(item, (tuple, list)):
1024 # item is option #2
1025 field, list_filter_class = item
1026 if not _issubclass(list_filter_class, FieldListFilter):
1027 return must_inherit_from(
1028 parent="FieldListFilter",
1029 option="%s[1]" % label,
1030 obj=obj,
1031 id="admin.E115",
1032 )
1033 else:
1034 return []
1035 else:
1036 # item is option #1
1037 field = item
1038
1039 # Validate the field string
1040 try:
1041 get_fields_from_path(obj.model, field)
1042 except (NotRelationField, FieldDoesNotExist):
1043 return [
1044 checks.Error(
1045 "The value of '%s' refers to '%s', which does not refer to a "
1046 "Field." % (label, field),
1047 obj=obj.__class__,
1048 id="admin.E116",
1049 )
1050 ]
1051 else:
1052 return []
1053
1054 def _check_list_select_related(self, obj):
1055 """Check that list_select_related is a boolean, a list or a tuple."""
1056
1057 if not isinstance(obj.list_select_related, (bool, list, tuple)):
1058 return must_be(
1059 "a boolean, tuple or list",
1060 option="list_select_related",
1061 obj=obj,
1062 id="admin.E117",
1063 )
1064 else:
1065 return []
1066
1067 def _check_list_per_page(self, obj):
1068 """Check that list_per_page is an integer."""
1069
1070 if not isinstance(obj.list_per_page, int):
1071 return must_be(
1072 "an integer", option="list_per_page", obj=obj, id="admin.E118"
1073 )
1074 else:
1075 return []
1076
1077 def _check_list_max_show_all(self, obj):
1078 """Check that list_max_show_all is an integer."""
1079
1080 if not isinstance(obj.list_max_show_all, int):
1081 return must_be(
1082 "an integer", option="list_max_show_all", obj=obj, id="admin.E119"
1083 )
1084 else:
1085 return []
1086
1087 def _check_list_editable(self, obj):
1088 """Check that list_editable is a sequence of editable fields from
1089 list_display without first element."""
1090
1091 if not isinstance(obj.list_editable, (list, tuple)):
1092 return must_be(
1093 "a list or tuple", option="list_editable", obj=obj, id="admin.E120"
1094 )
1095 else:
1096 return list(
1097 chain.from_iterable(
1098 self._check_list_editable_item(
1099 obj, item, "list_editable[%d]" % index
1100 )
1101 for index, item in enumerate(obj.list_editable)
1102 )
1103 )
1104
1105 def _check_list_editable_item(self, obj, field_name, label):
1106 try:
1107 field = obj.model._meta.get_field(field_name)
1108 except FieldDoesNotExist:
1109 return refer_to_missing_field(
1110 field=field_name, option=label, obj=obj, id="admin.E121"
1111 )
1112 else:
1113 if field_name not in obj.list_display:
1114 return [
1115 checks.Error(
1116 "The value of '%s' refers to '%s', which is not "
1117 "contained in 'list_display'." % (label, field_name),
1118 obj=obj.__class__,
1119 id="admin.E122",
1120 )
1121 ]
1122 elif obj.list_display_links and field_name in obj.list_display_links:
1123 return [
1124 checks.Error(
1125 "The value of '%s' cannot be in both 'list_editable' and "
1126 "'list_display_links'." % field_name,
1127 obj=obj.__class__,
1128 id="admin.E123",
1129 )
1130 ]
1131 # If list_display[0] is in list_editable, check that
1132 # list_display_links is set. See #22792 and #26229 for use cases.
1133 elif (
1134 obj.list_display[0] == field_name
1135 and not obj.list_display_links
1136 and obj.list_display_links is not None
1137 ):
1138 return [
1139 checks.Error(
1140 "The value of '%s' refers to the first field in 'list_display' "
1141 "('%s'), which cannot be used unless 'list_display_links' is "
1142 "set." % (label, obj.list_display[0]),
1143 obj=obj.__class__,
1144 id="admin.E124",
1145 )
1146 ]
1147 elif not field.editable or field.primary_key:
1148 return [
1149 checks.Error(
1150 "The value of '%s' refers to '%s', which is not editable "
1151 "through the admin." % (label, field_name),
1152 obj=obj.__class__,
1153 id="admin.E125",
1154 )
1155 ]
1156 else:
1157 return []
1158
1159 def _check_search_fields(self, obj):
1160 """Check search_fields is a sequence."""
1161
1162 if not isinstance(obj.search_fields, (list, tuple)):
1163 return must_be(
1164 "a list or tuple", option="search_fields", obj=obj, id="admin.E126"
1165 )
1166 else:
1167 return []
1168
1169 def _check_date_hierarchy(self, obj):
1170 """Check that date_hierarchy refers to DateField or DateTimeField."""
1171
1172 if obj.date_hierarchy is None:
1173 return []
1174 else:
1175 try:
1176 field = get_fields_from_path(obj.model, obj.date_hierarchy)[-1]
1177 except (NotRelationField, FieldDoesNotExist):
1178 return [
1179 checks.Error(
1180 "The value of 'date_hierarchy' refers to '%s', which "
1181 "does not refer to a Field." % obj.date_hierarchy,
1182 obj=obj.__class__,
1183 id="admin.E127",
1184 )
1185 ]
1186 else:
1187 if field.get_internal_type() not in {"DateField", "DateTimeField"}:
1188 return must_be(
1189 "a DateField or DateTimeField",
1190 option="date_hierarchy",
1191 obj=obj,
1192 id="admin.E128",
1193 )
1194 else:
1195 return []
1196
1197 def _check_actions(self, obj):
1198 errors = []
1199 actions = obj._get_base_actions()
1200
1201 # Actions with an allowed_permission attribute require the ModelAdmin
1202 # to implement a has_<perm>_permission() method for each permission.
1203 for func, name, _ in actions:
1204 if not hasattr(func, "allowed_permissions"):
1205 continue
1206 for permission in func.allowed_permissions:
1207 method_name = "has_%s_permission" % permission
1208 if not hasattr(obj, method_name):
1209 errors.append(
1210 checks.Error(
1211 "%s must define a %s() method for the %s action."
1212 % (
1213 obj.__class__.__name__,
1214 method_name,
1215 func.__name__,
1216 ),
1217 obj=obj.__class__,
1218 id="admin.E129",
1219 )
1220 )
1221 # Names need to be unique.
1222 names = collections.Counter(name for _, name, _ in actions)
1223 for name, count in names.items():
1224 if count > 1:
1225 errors.append(
1226 checks.Error(
1227 "__name__ attributes of actions defined in %s must be "
1228 "unique. Name %r is not unique."
1229 % (
1230 obj.__class__.__name__,
1231 name,
1232 ),
1233 obj=obj.__class__,
1234 id="admin.E130",
1235 )
1236 )
1237 return errors
1238
1239
1240 class InlineModelAdminChecks(BaseModelAdminChecks):
1241 def check(self, inline_obj, **kwargs):
1242 parent_model = inline_obj.parent_model
1243 return [
1244 *super().check(inline_obj),
1245 *self._check_relation(inline_obj, parent_model),
1246 *self._check_exclude_of_parent_model(inline_obj, parent_model),
1247 *self._check_extra(inline_obj),
1248 *self._check_max_num(inline_obj),
1249 *self._check_min_num(inline_obj),
1250 *self._check_formset(inline_obj),
1251 ]
1252
1253 def _check_exclude_of_parent_model(self, obj, parent_model):
1254 # Do not perform more specific checks if the base checks result in an
1255 # error.
1256 errors = super()._check_exclude(obj)
1257 if errors:
1258 return []
1259
1260 # Skip if `fk_name` is invalid.
1261 if self._check_relation(obj, parent_model):
1262 return []
1263
1264 if obj.exclude is None:
1265 return []
1266
1267 fk = _get_foreign_key(parent_model, obj.model, fk_name=obj.fk_name)
1268 if fk.name in obj.exclude:
1269 return [
1270 checks.Error(
1271 "Cannot exclude the field '%s', because it is the foreign key "
1272 "to the parent model '%s'."
1273 % (
1274 fk.name,
1275 parent_model._meta.label,
1276 ),
1277 obj=obj.__class__,
1278 id="admin.E201",
1279 )
1280 ]
1281 else:
1282 return []
1283
1284 def _check_relation(self, obj, parent_model):
1285 try:
1286 _get_foreign_key(parent_model, obj.model, fk_name=obj.fk_name)
1287 except ValueError as e:
1288 return [checks.Error(e.args[0], obj=obj.__class__, id="admin.E202")]
1289 else:
1290 return []
1291
1292 def _check_extra(self, obj):
1293 """Check that extra is an integer."""
1294
1295 if not isinstance(obj.extra, int):
1296 return must_be("an integer", option="extra", obj=obj, id="admin.E203")
1297 else:
1298 return []
1299
1300 def _check_max_num(self, obj):
1301 """Check that max_num is an integer."""
1302
1303 if obj.max_num is None:
1304 return []
1305 elif not isinstance(obj.max_num, int):
1306 return must_be("an integer", option="max_num", obj=obj, id="admin.E204")
1307 else:
1308 return []
1309
1310 def _check_min_num(self, obj):
1311 """Check that min_num is an integer."""
1312
1313 if obj.min_num is None:
1314 return []
1315 elif not isinstance(obj.min_num, int):
1316 return must_be("an integer", option="min_num", obj=obj, id="admin.E205")
1317 else:
1318 return []
1319
1320 def _check_formset(self, obj):
1321 """Check formset is a subclass of BaseModelFormSet."""
1322
1323 if not _issubclass(obj.formset, BaseModelFormSet):
1324 return must_inherit_from(
1325 parent="BaseModelFormSet", option="formset", obj=obj, id="admin.E206"
1326 )
1327 else:
1328 return []
1329
1330
1331 def must_be(type, option, obj, id):
1332 return [
1333 checks.Error(
1334 "The value of '%s' must be %s." % (option, type),
1335 obj=obj.__class__,
1336 id=id,
1337 ),
1338 ]
1339
1340
1341 def must_inherit_from(parent, option, obj, id):
1342 return [
1343 checks.Error(
1344 "The value of '%s' must inherit from '%s'." % (option, parent),
1345 obj=obj.__class__,
1346 id=id,
1347 ),
1348 ]
1349
1350
1351 def refer_to_missing_field(field, option, obj, id):
1352 return [
1353 checks.Error(
1354 "The value of '%s' refers to '%s', which is not a field of '%s'."
1355 % (option, field, obj.model._meta.label),
1356 obj=obj.__class__,
1357 id=id,
1358 ),
1359 ]