web/lib/django/contrib/admin/validation.py
changeset 38 77b6da96e6f1
equal deleted inserted replaced
37:8d941af65caf 38:77b6da96e6f1
       
     1 from django.core.exceptions import ImproperlyConfigured
       
     2 from django.db import models
       
     3 from django.forms.models import (BaseModelForm, BaseModelFormSet, fields_for_model,
       
     4     _get_foreign_key)
       
     5 from django.contrib.admin.options import flatten_fieldsets, BaseModelAdmin
       
     6 from django.contrib.admin.options import HORIZONTAL, VERTICAL
       
     7 from django.contrib.admin.util import lookup_field
       
     8 
       
     9 
       
    10 __all__ = ['validate']
       
    11 
       
    12 def validate(cls, model):
       
    13     """
       
    14     Does basic ModelAdmin option validation. Calls custom validation
       
    15     classmethod in the end if it is provided in cls. The signature of the
       
    16     custom validation classmethod should be: def validate(cls, model).
       
    17     """
       
    18     # Before we can introspect models, they need to be fully loaded so that
       
    19     # inter-relations are set up correctly. We force that here.
       
    20     models.get_apps()
       
    21 
       
    22     opts = model._meta
       
    23     validate_base(cls, model)
       
    24 
       
    25     # list_display
       
    26     if hasattr(cls, 'list_display'):
       
    27         check_isseq(cls, 'list_display', cls.list_display)
       
    28         for idx, field in enumerate(cls.list_display):
       
    29             if not callable(field):
       
    30                 if not hasattr(cls, field):
       
    31                     if not hasattr(model, field):
       
    32                         try:
       
    33                             opts.get_field(field)
       
    34                         except models.FieldDoesNotExist:
       
    35                             raise ImproperlyConfigured("%s.list_display[%d], %r is not a callable or an attribute of %r or found in the model %r."
       
    36                                 % (cls.__name__, idx, field, cls.__name__, model._meta.object_name))
       
    37                     else:
       
    38                         # getattr(model, field) could be an X_RelatedObjectsDescriptor
       
    39                         f = fetch_attr(cls, model, opts, "list_display[%d]" % idx, field)
       
    40                         if isinstance(f, models.ManyToManyField):
       
    41                             raise ImproperlyConfigured("'%s.list_display[%d]', '%s' is a ManyToManyField which is not supported."
       
    42                                 % (cls.__name__, idx, field))
       
    43 
       
    44     # list_display_links
       
    45     if hasattr(cls, 'list_display_links'):
       
    46         check_isseq(cls, 'list_display_links', cls.list_display_links)
       
    47         for idx, field in enumerate(cls.list_display_links):
       
    48             fetch_attr(cls, model, opts, 'list_display_links[%d]' % idx, field)
       
    49             if field not in cls.list_display:
       
    50                 raise ImproperlyConfigured("'%s.list_display_links[%d]'"
       
    51                         "refers to '%s' which is not defined in 'list_display'."
       
    52                         % (cls.__name__, idx, field))
       
    53 
       
    54     # list_filter
       
    55     if hasattr(cls, 'list_filter'):
       
    56         check_isseq(cls, 'list_filter', cls.list_filter)
       
    57         for idx, field in enumerate(cls.list_filter):
       
    58             get_field(cls, model, opts, 'list_filter[%d]' % idx, field)
       
    59 
       
    60     # list_per_page = 100
       
    61     if hasattr(cls, 'list_per_page') and not isinstance(cls.list_per_page, int):
       
    62         raise ImproperlyConfigured("'%s.list_per_page' should be a integer."
       
    63                 % cls.__name__)
       
    64 
       
    65     # list_editable
       
    66     if hasattr(cls, 'list_editable') and cls.list_editable:
       
    67         check_isseq(cls, 'list_editable', cls.list_editable)
       
    68         for idx, field_name in enumerate(cls.list_editable):
       
    69             try:
       
    70                 field = opts.get_field_by_name(field_name)[0]
       
    71             except models.FieldDoesNotExist:
       
    72                 raise ImproperlyConfigured("'%s.list_editable[%d]' refers to a "
       
    73                     "field, '%s', not defined on %s."
       
    74                     % (cls.__name__, idx, field_name, model.__name__))
       
    75             if field_name not in cls.list_display:
       
    76                 raise ImproperlyConfigured("'%s.list_editable[%d]' refers to "
       
    77                     "'%s' which is not defined in 'list_display'."
       
    78                     % (cls.__name__, idx, field_name))
       
    79             if field_name in cls.list_display_links:
       
    80                 raise ImproperlyConfigured("'%s' cannot be in both '%s.list_editable'"
       
    81                     " and '%s.list_display_links'"
       
    82                     % (field_name, cls.__name__, cls.__name__))
       
    83             if not cls.list_display_links and cls.list_display[0] in cls.list_editable:
       
    84                 raise ImproperlyConfigured("'%s.list_editable[%d]' refers to"
       
    85                     " the first field in list_display, '%s', which can't be"
       
    86                     " used unless list_display_links is set."
       
    87                     % (cls.__name__, idx, cls.list_display[0]))
       
    88             if not field.editable:
       
    89                 raise ImproperlyConfigured("'%s.list_editable[%d]' refers to a "
       
    90                     "field, '%s', which isn't editable through the admin."
       
    91                     % (cls.__name__, idx, field_name))
       
    92 
       
    93     # search_fields = ()
       
    94     if hasattr(cls, 'search_fields'):
       
    95         check_isseq(cls, 'search_fields', cls.search_fields)
       
    96 
       
    97     # date_hierarchy = None
       
    98     if cls.date_hierarchy:
       
    99         f = get_field(cls, model, opts, 'date_hierarchy', cls.date_hierarchy)
       
   100         if not isinstance(f, (models.DateField, models.DateTimeField)):
       
   101             raise ImproperlyConfigured("'%s.date_hierarchy is "
       
   102                     "neither an instance of DateField nor DateTimeField."
       
   103                     % cls.__name__)
       
   104 
       
   105     # ordering = None
       
   106     if cls.ordering:
       
   107         check_isseq(cls, 'ordering', cls.ordering)
       
   108         for idx, field in enumerate(cls.ordering):
       
   109             if field == '?' and len(cls.ordering) != 1:
       
   110                 raise ImproperlyConfigured("'%s.ordering' has the random "
       
   111                         "ordering marker '?', but contains other fields as "
       
   112                         "well. Please either remove '?' or the other fields."
       
   113                         % cls.__name__)
       
   114             if field == '?':
       
   115                 continue
       
   116             if field.startswith('-'):
       
   117                 field = field[1:]
       
   118             # Skip ordering in the format field1__field2 (FIXME: checking
       
   119             # this format would be nice, but it's a little fiddly).
       
   120             if '__' in field:
       
   121                 continue
       
   122             get_field(cls, model, opts, 'ordering[%d]' % idx, field)
       
   123 
       
   124     if hasattr(cls, "readonly_fields"):
       
   125         check_isseq(cls, "readonly_fields", cls.readonly_fields)
       
   126         for idx, field in enumerate(cls.readonly_fields):
       
   127             if not callable(field):
       
   128                 if not hasattr(cls, field):
       
   129                     if not hasattr(model, field):
       
   130                         try:
       
   131                             opts.get_field(field)
       
   132                         except models.FieldDoesNotExist:
       
   133                             raise ImproperlyConfigured("%s.readonly_fields[%d], %r is not a callable or an attribute of %r or found in the model %r."
       
   134                                 % (cls.__name__, idx, field, cls.__name__, model._meta.object_name))
       
   135 
       
   136     # list_select_related = False
       
   137     # save_as = False
       
   138     # save_on_top = False
       
   139     for attr in ('list_select_related', 'save_as', 'save_on_top'):
       
   140         if not isinstance(getattr(cls, attr), bool):
       
   141             raise ImproperlyConfigured("'%s.%s' should be a boolean."
       
   142                     % (cls.__name__, attr))
       
   143 
       
   144 
       
   145     # inlines = []
       
   146     if hasattr(cls, 'inlines'):
       
   147         check_isseq(cls, 'inlines', cls.inlines)
       
   148         for idx, inline in enumerate(cls.inlines):
       
   149             if not issubclass(inline, BaseModelAdmin):
       
   150                 raise ImproperlyConfigured("'%s.inlines[%d]' does not inherit "
       
   151                         "from BaseModelAdmin." % (cls.__name__, idx))
       
   152             if not inline.model:
       
   153                 raise ImproperlyConfigured("'model' is a required attribute "
       
   154                         "of '%s.inlines[%d]'." % (cls.__name__, idx))
       
   155             if not issubclass(inline.model, models.Model):
       
   156                 raise ImproperlyConfigured("'%s.inlines[%d].model' does not "
       
   157                         "inherit from models.Model." % (cls.__name__, idx))
       
   158             validate_base(inline, inline.model)
       
   159             validate_inline(inline, cls, model)
       
   160 
       
   161 def validate_inline(cls, parent, parent_model):
       
   162 
       
   163     # model is already verified to exist and be a Model
       
   164     if cls.fk_name: # default value is None
       
   165         f = get_field(cls, cls.model, cls.model._meta, 'fk_name', cls.fk_name)
       
   166         if not isinstance(f, models.ForeignKey):
       
   167             raise ImproperlyConfigured("'%s.fk_name is not an instance of "
       
   168                     "models.ForeignKey." % cls.__name__)
       
   169 
       
   170     fk = _get_foreign_key(parent_model, cls.model, fk_name=cls.fk_name, can_fail=True)
       
   171 
       
   172     # extra = 3
       
   173     if not isinstance(getattr(cls, 'extra'), int):
       
   174         raise ImproperlyConfigured("'%s.extra' should be a integer."
       
   175                 % cls.__name__)
       
   176 
       
   177     # max_num = None
       
   178     max_num = getattr(cls, 'max_num', None)
       
   179     if max_num is not None and not isinstance(max_num, int):
       
   180         raise ImproperlyConfigured("'%s.max_num' should be an integer or None (default)."
       
   181                 % cls.__name__)
       
   182 
       
   183     # formset
       
   184     if hasattr(cls, 'formset') and not issubclass(cls.formset, BaseModelFormSet):
       
   185         raise ImproperlyConfigured("'%s.formset' does not inherit from "
       
   186                 "BaseModelFormSet." % cls.__name__)
       
   187 
       
   188     # exclude
       
   189     if hasattr(cls, 'exclude') and cls.exclude:
       
   190         if fk and fk.name in cls.exclude:
       
   191             raise ImproperlyConfigured("%s cannot exclude the field "
       
   192                     "'%s' - this is the foreign key to the parent model "
       
   193                     "%s." % (cls.__name__, fk.name, parent_model.__name__))
       
   194 
       
   195 def validate_base(cls, model):
       
   196     opts = model._meta
       
   197 
       
   198     # raw_id_fields
       
   199     if hasattr(cls, 'raw_id_fields'):
       
   200         check_isseq(cls, 'raw_id_fields', cls.raw_id_fields)
       
   201         for idx, field in enumerate(cls.raw_id_fields):
       
   202             f = get_field(cls, model, opts, 'raw_id_fields', field)
       
   203             if not isinstance(f, (models.ForeignKey, models.ManyToManyField)):
       
   204                 raise ImproperlyConfigured("'%s.raw_id_fields[%d]', '%s' must "
       
   205                         "be either a ForeignKey or ManyToManyField."
       
   206                         % (cls.__name__, idx, field))
       
   207 
       
   208     # fields
       
   209     if cls.fields: # default value is None
       
   210         check_isseq(cls, 'fields', cls.fields)
       
   211         for field in cls.fields:
       
   212             if field in cls.readonly_fields:
       
   213                 # Stuff can be put in fields that isn't actually a model field
       
   214                 # if it's in readonly_fields, readonly_fields will handle the
       
   215                 # validation of such things.
       
   216                 continue
       
   217             check_formfield(cls, model, opts, 'fields', field)
       
   218             try:
       
   219                 f = opts.get_field(field)
       
   220             except models.FieldDoesNotExist:
       
   221                 # If we can't find a field on the model that matches,
       
   222                 # it could be an extra field on the form.
       
   223                 continue
       
   224             if isinstance(f, models.ManyToManyField) and not f.rel.through._meta.auto_created:
       
   225                 raise ImproperlyConfigured("'%s.fields' can't include the ManyToManyField "
       
   226                     "field '%s' because '%s' manually specifies "
       
   227                     "a 'through' model." % (cls.__name__, field, field))
       
   228         if cls.fieldsets:
       
   229             raise ImproperlyConfigured('Both fieldsets and fields are specified in %s.' % cls.__name__)
       
   230         if len(cls.fields) > len(set(cls.fields)):
       
   231             raise ImproperlyConfigured('There are duplicate field(s) in %s.fields' % cls.__name__)
       
   232 
       
   233     # fieldsets
       
   234     if cls.fieldsets: # default value is None
       
   235         check_isseq(cls, 'fieldsets', cls.fieldsets)
       
   236         for idx, fieldset in enumerate(cls.fieldsets):
       
   237             check_isseq(cls, 'fieldsets[%d]' % idx, fieldset)
       
   238             if len(fieldset) != 2:
       
   239                 raise ImproperlyConfigured("'%s.fieldsets[%d]' does not "
       
   240                         "have exactly two elements." % (cls.__name__, idx))
       
   241             check_isdict(cls, 'fieldsets[%d][1]' % idx, fieldset[1])
       
   242             if 'fields' not in fieldset[1]:
       
   243                 raise ImproperlyConfigured("'fields' key is required in "
       
   244                         "%s.fieldsets[%d][1] field options dict."
       
   245                         % (cls.__name__, idx))
       
   246             for fields in fieldset[1]['fields']:
       
   247                 # The entry in fields might be a tuple. If it is a standalone
       
   248                 # field, make it into a tuple to make processing easier.
       
   249                 if type(fields) != tuple:
       
   250                     fields = (fields,)
       
   251                 for field in fields:
       
   252                     if field in cls.readonly_fields:
       
   253                         # Stuff can be put in fields that isn't actually a
       
   254                         # model field if it's in readonly_fields,
       
   255                         # readonly_fields will handle the validation of such
       
   256                         # things.
       
   257                         continue
       
   258                     check_formfield(cls, model, opts, "fieldsets[%d][1]['fields']" % idx, field)
       
   259                     try:
       
   260                         f = opts.get_field(field)
       
   261                         if isinstance(f, models.ManyToManyField) and not f.rel.through._meta.auto_created:
       
   262                             raise ImproperlyConfigured("'%s.fieldsets[%d][1]['fields']' "
       
   263                                 "can't include the ManyToManyField field '%s' because "
       
   264                                 "'%s' manually specifies a 'through' model." % (
       
   265                                     cls.__name__, idx, field, field))
       
   266                     except models.FieldDoesNotExist:
       
   267                         # If we can't find a field on the model that matches,
       
   268                         # it could be an extra field on the form.
       
   269                         pass
       
   270         flattened_fieldsets = flatten_fieldsets(cls.fieldsets)
       
   271         if len(flattened_fieldsets) > len(set(flattened_fieldsets)):
       
   272             raise ImproperlyConfigured('There are duplicate field(s) in %s.fieldsets' % cls.__name__)
       
   273 
       
   274     # exclude
       
   275     if cls.exclude: # default value is None
       
   276         check_isseq(cls, 'exclude', cls.exclude)
       
   277         for field in cls.exclude:
       
   278             check_formfield(cls, model, opts, 'exclude', field)
       
   279             try:
       
   280                 f = opts.get_field(field)
       
   281             except models.FieldDoesNotExist:
       
   282                 # If we can't find a field on the model that matches,
       
   283                 # it could be an extra field on the form.
       
   284                 continue
       
   285         if len(cls.exclude) > len(set(cls.exclude)):
       
   286             raise ImproperlyConfigured('There are duplicate field(s) in %s.exclude' % cls.__name__)
       
   287 
       
   288     # form
       
   289     if hasattr(cls, 'form') and not issubclass(cls.form, BaseModelForm):
       
   290         raise ImproperlyConfigured("%s.form does not inherit from "
       
   291                 "BaseModelForm." % cls.__name__)
       
   292 
       
   293     # filter_vertical
       
   294     if hasattr(cls, 'filter_vertical'):
       
   295         check_isseq(cls, 'filter_vertical', cls.filter_vertical)
       
   296         for idx, field in enumerate(cls.filter_vertical):
       
   297             f = get_field(cls, model, opts, 'filter_vertical', field)
       
   298             if not isinstance(f, models.ManyToManyField):
       
   299                 raise ImproperlyConfigured("'%s.filter_vertical[%d]' must be "
       
   300                     "a ManyToManyField." % (cls.__name__, idx))
       
   301 
       
   302     # filter_horizontal
       
   303     if hasattr(cls, 'filter_horizontal'):
       
   304         check_isseq(cls, 'filter_horizontal', cls.filter_horizontal)
       
   305         for idx, field in enumerate(cls.filter_horizontal):
       
   306             f = get_field(cls, model, opts, 'filter_horizontal', field)
       
   307             if not isinstance(f, models.ManyToManyField):
       
   308                 raise ImproperlyConfigured("'%s.filter_horizontal[%d]' must be "
       
   309                     "a ManyToManyField." % (cls.__name__, idx))
       
   310 
       
   311     # radio_fields
       
   312     if hasattr(cls, 'radio_fields'):
       
   313         check_isdict(cls, 'radio_fields', cls.radio_fields)
       
   314         for field, val in cls.radio_fields.items():
       
   315             f = get_field(cls, model, opts, 'radio_fields', field)
       
   316             if not (isinstance(f, models.ForeignKey) or f.choices):
       
   317                 raise ImproperlyConfigured("'%s.radio_fields['%s']' "
       
   318                         "is neither an instance of ForeignKey nor does "
       
   319                         "have choices set." % (cls.__name__, field))
       
   320             if not val in (HORIZONTAL, VERTICAL):
       
   321                 raise ImproperlyConfigured("'%s.radio_fields['%s']' "
       
   322                         "is neither admin.HORIZONTAL nor admin.VERTICAL."
       
   323                         % (cls.__name__, field))
       
   324 
       
   325     # prepopulated_fields
       
   326     if hasattr(cls, 'prepopulated_fields'):
       
   327         check_isdict(cls, 'prepopulated_fields', cls.prepopulated_fields)
       
   328         for field, val in cls.prepopulated_fields.items():
       
   329             f = get_field(cls, model, opts, 'prepopulated_fields', field)
       
   330             if isinstance(f, (models.DateTimeField, models.ForeignKey,
       
   331                 models.ManyToManyField)):
       
   332                 raise ImproperlyConfigured("'%s.prepopulated_fields['%s']' "
       
   333                         "is either a DateTimeField, ForeignKey or "
       
   334                         "ManyToManyField. This isn't allowed."
       
   335                         % (cls.__name__, field))
       
   336             check_isseq(cls, "prepopulated_fields['%s']" % field, val)
       
   337             for idx, f in enumerate(val):
       
   338                 get_field(cls, model, opts, "prepopulated_fields['%s'][%d]" % (field, idx), f)
       
   339 
       
   340 def check_isseq(cls, label, obj):
       
   341     if not isinstance(obj, (list, tuple)):
       
   342         raise ImproperlyConfigured("'%s.%s' must be a list or tuple." % (cls.__name__, label))
       
   343 
       
   344 def check_isdict(cls, label, obj):
       
   345     if not isinstance(obj, dict):
       
   346         raise ImproperlyConfigured("'%s.%s' must be a dictionary." % (cls.__name__, label))
       
   347 
       
   348 def get_field(cls, model, opts, label, field):
       
   349     try:
       
   350         return opts.get_field(field)
       
   351     except models.FieldDoesNotExist:
       
   352         raise ImproperlyConfigured("'%s.%s' refers to field '%s' that is missing from model '%s'."
       
   353                 % (cls.__name__, label, field, model.__name__))
       
   354 
       
   355 def check_formfield(cls, model, opts, label, field):
       
   356     if getattr(cls.form, 'base_fields', None):
       
   357         try:
       
   358             cls.form.base_fields[field]
       
   359         except KeyError:
       
   360             raise ImproperlyConfigured("'%s.%s' refers to field '%s' that "
       
   361                 "is missing from the form." % (cls.__name__, label, field))
       
   362     else:
       
   363         fields = fields_for_model(model)
       
   364         try:
       
   365             fields[field]
       
   366         except KeyError:
       
   367             raise ImproperlyConfigured("'%s.%s' refers to field '%s' that "
       
   368                 "is missing from the form." % (cls.__name__, label, field))
       
   369 
       
   370 def fetch_attr(cls, model, opts, label, field):
       
   371     try:
       
   372         return opts.get_field(field)
       
   373     except models.FieldDoesNotExist:
       
   374         pass
       
   375     try:
       
   376         return getattr(model, field)
       
   377     except AttributeError:
       
   378         raise ImproperlyConfigured("'%s.%s' refers to '%s' that is neither a field, method or property of model '%s'."
       
   379             % (cls.__name__, label, field, model.__name__))