Ticket #5374: modeladmin_validation.diff

File modeladmin_validation.diff, 17.5 KB (added by mrts, 16 years ago)

typo

  • django/core/management/validation.py

     
    143143                    if r.get_accessor_name() == rel_query_name:
    144144                        e.add(opts, "Reverse query name for m2m field '%s' clashes with related field '%s.%s'. Add a related_name argument to the definition for '%s'." % (f.name, rel_opts.object_name, r.get_accessor_name(), f.name))
    145145
    146         # Check admin attribute.
    147         if opts.admin is not None:
    148             # prepopulated_fields
    149             if not isinstance(opts.admin.prepopulated_fields, dict):
    150                 e.add(opts, '"%s": prepopulated_fields should be a dictionary.' % f.name)
    151             else:
    152                 for field_name, field_list in opts.admin.prepopulated_fields.items():
    153                     if not isinstance(field_list, (list, tuple)):
    154                         e.add(opts, '"%s": prepopulated_fields "%s" value should be a list or tuple.' % (f.name, field_name))
    155 
    156             # list_display
    157             if not isinstance(opts.admin.list_display, (list, tuple)):
    158                 e.add(opts, '"admin.list_display", if given, must be set to a list or tuple.')
    159             else:
    160                 for fn in opts.admin.list_display:
    161                     try:
    162                         f = opts.get_field(fn)
    163                     except models.FieldDoesNotExist:
    164                         if not hasattr(cls, fn):
    165                             e.add(opts, '"admin.list_display" refers to %r, which isn\'t an attribute, method or property.' % fn)
    166                     else:
    167                         if isinstance(f, models.ManyToManyField):
    168                             e.add(opts, '"admin.list_display" doesn\'t support ManyToManyFields (%r).' % fn)
    169             # list_display_links
    170             if opts.admin.list_display_links and not opts.admin.list_display:
    171                 e.add(opts, '"admin.list_display" must be defined for "admin.list_display_links" to be used.')
    172             if not isinstance(opts.admin.list_display_links, (list, tuple)):
    173                 e.add(opts, '"admin.list_display_links", if given, must be set to a list or tuple.')
    174             else:
    175                 for fn in opts.admin.list_display_links:
    176                     try:
    177                         f = opts.get_field(fn)
    178                     except models.FieldDoesNotExist:
    179                         if not hasattr(cls, fn):
    180                             e.add(opts, '"admin.list_display_links" refers to %r, which isn\'t an attribute, method or property.' % fn)
    181                     if fn not in opts.admin.list_display:
    182                         e.add(opts, '"admin.list_display_links" refers to %r, which is not defined in "admin.list_display".' % fn)
    183             # list_filter
    184             if not isinstance(opts.admin.list_filter, (list, tuple)):
    185                 e.add(opts, '"admin.list_filter", if given, must be set to a list or tuple.')
    186             else:
    187                 for fn in opts.admin.list_filter:
    188                     try:
    189                         f = opts.get_field(fn)
    190                     except models.FieldDoesNotExist:
    191                         e.add(opts, '"admin.list_filter" refers to %r, which isn\'t a field.' % fn)
    192             # date_hierarchy
    193             if opts.admin.date_hierarchy:
    194                 try:
    195                     f = opts.get_field(opts.admin.date_hierarchy)
    196                 except models.FieldDoesNotExist:
    197                     e.add(opts, '"admin.date_hierarchy" refers to %r, which isn\'t a field.' % opts.admin.date_hierarchy)
    198 
    199146        # Check ordering attribute.
    200147        if opts.ordering:
    201148            for field_name in opts.ordering:
     
    213160                except models.FieldDoesNotExist:
    214161                    e.add(opts, '"ordering" refers to "%s", a field that doesn\'t exist.' % field_name)
    215162
    216         # Check core=True, if needed.
    217         for related in opts.get_followed_related_objects():
    218             if not related.edit_inline:
    219                 continue
    220             try:
    221                 for f in related.opts.fields:
    222                     if f.core:
    223                         raise StopIteration
    224                 e.add(related.opts, "At least one field in %s should have core=True, because it's being edited inline by %s.%s." % (related.opts.object_name, opts.module_name, opts.object_name))
    225             except StopIteration:
    226                 pass
    227 
    228163        # Check unique_together.
    229164        for ut in opts.unique_together:
    230165            for field_name in ut:
  • django/contrib/admin/validation.py

     
     1# Possible improvements: gather all errors and raise in the end instead of
     2# bailing out on the first one (like core/management/validation.py does)
     3
     4from django.core.exceptions import ImproperlyConfigured
     5from django.db import models
     6from django import newforms as forms
     7from django.contrib.admin.options import flatten_fieldsets, BaseModelAdmin
     8from django.contrib.admin.options import HORIZONTAL, VERTICAL
     9
     10def validate(cls, model):
     11    """
     12    Does basic ModelAdmin option validation. Calls custom validation
     13    classmethod in the end if it is provided in cls. The signature of the
     14    custom validation classmethod should be: def validate(cls, model).
     15    """
     16    opts = model._meta
     17    _validate_base(cls, model)
     18
     19    # currying is expensive, use wrappers instead
     20    def _check_istuplew(label, obj):
     21        _check_istuple(cls, label, obj)
     22
     23    def _check_isdictw(label, obj):
     24        _check_isdict(cls, label, obj)
     25
     26    def _check_field_existsw(label, field):
     27        return _check_field_exists(cls, model, opts, label, field)
     28
     29    def _check_attr_existsw(label, field):
     30        _check_attr_exists(cls, model, opts, label, field)
     31
     32    # list_display
     33    if not cls.list_display:
     34        raise ImproperlyConfigured("%s.list_display can not be empty." %
     35                cls.__name__)
     36    _check_istuplew('list_display', cls.list_display)
     37    for idx, field in enumerate(cls.list_display):
     38        f = _check_attr_existsw("list_display['%d']" % idx, field)
     39        if isinstance(f, models.ManyToManyField):
     40            raise ImproperlyConfigured("`%s.list_display['%d']`, `%s` is a "
     41                    "ManyToManyField which is not supported."
     42                    % (cls.__name__, idx, field))
     43
     44    # list_display_links
     45    if cls.list_display_links:
     46        _check_istuplew('list_display_links', cls.list_display_links)
     47        for idx, field in enumerate(cls.list_display_links):
     48            _check_attr_existsw('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 cls.list_filter:
     56        _check_istuplew('list_filter', cls.list_filter)
     57        for idx, field in enumerate(cls.list_filter):
     58            _check_field_existsw('list_filter[%d]' % idx, field)
     59
     60    # list_per_page = 100
     61    if not isinstance(cls.list_per_page, int):
     62        raise ImproperlyConfigured("`%s.list_per_page` should be a integer."
     63                % cls.__name__)
     64
     65    # search_fields = ()
     66    if cls.search_fields:
     67        _check_istuplew('search_fields', cls.search_fields)
     68        # TODO: search field validation is quite complex (restrictions,
     69        # follow fields etc), will skip it as of now
     70        # for idx, field in enumerate(cls.search_fields):
     71            # _check_field_existsw('search_fields[%d]' % idx, field)
     72
     73    # date_hierarchy = None
     74    if cls.date_hierarchy:
     75        f = _check_field_existsw('date_hierarchy', cls.date_hierarchy)
     76        if not isinstance(f, (models.DateField, models.DateTimeField)):
     77            raise ImproperlyConfigured("`%s.date_hierarchy is "
     78                    "neither an instance of DateField nor DateTimeField."
     79                    % cls.__name__)
     80
     81    # ordering = None
     82    if cls.ordering:
     83        _check_istuplew('ordering', cls.ordering)
     84        for idx, field in enumerate(cls.ordering):
     85            if field == '?' and len(cls.ordering) != 1:
     86                raise ImproperlyConfigured("`%s.ordering` has the random "
     87                        "ordering marker `?`, but contains other fields as "
     88                        "well. Please either remove `?` or the other fields."
     89                        % cls.__name__)
     90            if field.startswith('-'):
     91                field = field[1:]
     92            _check_field_existsw('ordering[%d]' % idx, field)
     93
     94    # list_select_related = False
     95    # save_as = False
     96    # save_on_top = False
     97    for attr in ('list_select_related', 'save_as', 'save_on_top'):
     98        if not isinstance(getattr(cls, attr), bool):
     99            raise ImproperlyConfigured("`%s.%s` should be a boolean."
     100                    % (cls.__name__, attr))
     101
     102    # inlines = []
     103    if cls.inlines:
     104        _check_istuplew('inlines', cls.inlines)
     105        for idx, inline in enumerate(cls.inlines):
     106            if not issubclass(inline, BaseModelAdmin):
     107                raise ImproperlyConfigured("`%s.inlines[%d]` does not inherit "
     108                        "from BaseModelAdmin." % (cls.__name__, idx))
     109            if not inline.model:
     110                raise ImproperlyConfigured("`model` is a required attribute "
     111                        "of `%s.inlines[%d]`." % (cls.__name__, idx))
     112            if not issubclass(inline.model, models.Model):
     113                raise ImproperlyConfigured("`%s.inlines[%d].model` does not "
     114                        "inherit from models.Model." % (cls.__name__, idx))
     115            _validate_base(inline, inline.model)
     116            _validate_inline(inline)
     117
     118    # TODO: check that the templates exist if given
     119    # change_form_template = None
     120    # change_list_template = None
     121    # delete_confirmation_template = None
     122    # object_history_template = None
     123
     124    # hook for custom validation
     125    _call_validation_hook(cls, model)
     126
     127def _validate_inline(cls):
     128    # model is already verified to exist and be a Model
     129    if cls.fk_name:
     130        f = _check_field_exists(cls, cls.model, cls.model._meta,
     131                'fk_name', cls.fk_name)
     132        if not isinstance(f, models.ForeignKey):
     133            raise ImproperlyConfigured("`%s.fk_name is not an instance of "
     134                    "models.ForeignKey." % cls.__name__)
     135    # extra = 3
     136    # max_num = 0
     137    for attr in ('extra', 'max_num'):
     138        if not isinstance(getattr(cls, attr), int):
     139            raise ImproperlyConfigured("`%s.%s` should be a integer."
     140                    % (cls.__name__, attr))
     141
     142    #TODO: check the following
     143    # formset = BaseInlineFormset
     144    # template = None
     145    # verbose_name = None
     146    # verbose_name_plural = None
     147
     148    # hook for custom validation
     149    _call_validation_hook(cls, cls.model)
     150
     151def _validate_base(cls, model):
     152    opts = model._meta
     153    # currying is expensive, use wrappers instead
     154    def _check_istuplew(label, obj):
     155        _check_istuple(cls, label, obj)
     156
     157    def _check_isdictw(label, obj):
     158        _check_isdict(cls, label, obj)
     159
     160    def _check_field_existsw(label, field):
     161        return _check_field_exists(cls, model, opts, label, field)
     162
     163    # raw_id_fields
     164    if cls.raw_id_fields:
     165        _check_istuplew('raw_id_fields', cls.raw_id_fields)
     166        for field in cls.raw_id_fields:
     167            _check_field_existsw('raw_id_fields', field)
     168
     169    # fields
     170    if cls.fields:
     171        for field in cls.fields:
     172            _check_field_existsw('fields', field)
     173
     174    # fieldsets
     175    if cls.fieldsets:
     176        _check_istuplew('fieldsets', cls.fieldsets)
     177        for idx, fieldset in enumerate(cls.fieldsets):
     178            _check_istuplew('fieldsets[%d]' % idx, fieldset)
     179            if len(fieldset) != 2:
     180                raise ImproperlyConfigured("`%s.fieldsets[%d]` does not "
     181                        "have exactly two elements." % (cls.__name__, idx))
     182            _check_isdictw('fieldsets[%d][1]' % idx, fieldset[1])
     183            if 'fields' not in fieldset[1]:
     184                raise ImproperlyConfigured("`fields` key is required in "
     185                        "%s.fieldsets[%d][1] field options dict."
     186                        % (cls.__name__, idx))
     187        for field in flatten_fieldsets(cls.fieldsets):
     188            _check_field_existsw("fieldsets[%d][1]['fields']" % idx, field)
     189
     190    # form FIXME: brosner, is this correct?
     191    # if cls.form and not isinstance(cls.form, forms.BaseForm):
     192        # raise ImproperlyConfigured("%s.form is not a form instance."
     193                # % cls.__name__)
     194
     195    # filter_vertical
     196    if cls.filter_vertical:
     197        _check_istuplew('filter_vertical', cls.filter_vertical)
     198        for field in cls.filter_vertical:
     199            _check_field_existsw('filter_vertical', field)
     200
     201    # filter_horizontal
     202    if cls.filter_horizontal:
     203        _check_istuplew('filter_horizontal', cls.filter_horizontal)
     204        for field in cls.filter_horizontal:
     205            _check_field_existsw('filter_horizontal', field)
     206
     207    # radio_fields
     208    if cls.radio_fields:
     209        _check_isdictw('radio_fields', cls.radio_fields)
     210        for field, val in cls.radio_fields.items():
     211            f = _check_field_existsw('radio_fields', field)
     212            if not (isinstance(f, models.ForeignKey) or f.choices):
     213                raise ImproperlyConfigured("`%s.radio_fields['%s']` "
     214                        "is neither an instance of ForeignKey nor does "
     215                        "have choices set." % (cls.__name__, field))
     216            if not val in (HORIZONTAL, VERTICAL):
     217                raise ImproperlyConfigured("`%s.radio_fields['%s']` "
     218                        "is neither admin.HORIZONTAL nor admin.VERTICAL."
     219                        % (cls.__name__, field))
     220
     221    # prepopulated_fields
     222    if cls.prepopulated_fields:
     223        _check_isdictw('prepopulated_fields', cls.prepopulated_fields)
     224        for field, val in cls.prepopulated_fields.items():
     225            f = _check_field_existsw('prepopulated_fields', field)
     226            if isinstance(f, (models.DateTimeField, models.ForeignKey,
     227                models.ManyToManyField)):
     228                raise ImproperlyConfigured("`%s.prepopulated_fields['%s']` "
     229                        "is either a DateTimeField, ForeignKey or "
     230                        "ManyToManyField. This isn't allowed."
     231                        % (cls.__name__, field))
     232            _check_istuplew("prepopulated_fields['%s']" % field, val)
     233            for idx, f in enumerate(val):
     234                _check_field_existsw("prepopulated_fields['%s'][%d]"
     235                        % (f, idx), f)
     236
     237def _call_validation_hook(cls, model):
     238    if hasattr(cls, 'validate'):
     239        if not callable(cls.validate):
     240            raise ImproperlyConfigured("`%s.validate` should be a callable "
     241                    "(class method)." % cls.__name__)
     242        cls.validate(model)
     243
     244def _check_istuple(cls, label, obj):
     245    if not isinstance(obj, (list, tuple)):
     246        raise ImproperlyConfigured("`%s.%s` must be a "
     247                "list or tuple." % (cls.__name__, label))
     248
     249def _check_isdict(cls, label, obj):
     250    if not isinstance(obj, dict):
     251        raise ImproperlyConfigured("`%s.%s` must be a dictionary."
     252                % (cls.__name__, label))
     253
     254def _check_field_exists(cls, model, opts, label, field):
     255    try:
     256        return opts.get_field(field)
     257    except models.FieldDoesNotExist:
     258        raise ImproperlyConfigured("`%s.%s` refers to "
     259                "field `%s` that is missing from model `%s`."
     260                % (cls.__name__, label, field, model.__name__))
     261
     262def _check_attr_exists(cls, model, opts, label, field):
     263    try:
     264        return opts.get_field(field)
     265    except models.FieldDoesNotExist:
     266        if not hasattr(model, field):
     267            raise ImproperlyConfigured("`%s.%s` refers to "
     268                    "`%s` that is neither a field, method or property "
     269                    "of model `%s`."
     270                    % (cls.__name__, label, field, model.__name__))
     271        return getattr(model, field)
  • django/contrib/admin/sites.py

     
    77from django.utils.text import capfirst
    88from django.utils.translation import ugettext_lazy, ugettext as _
    99from django.views.decorators.cache import never_cache
     10from django.conf import settings
    1011import base64
    1112import cPickle as pickle
    1213import datetime
     
    6566
    6667        If a model is already registered, this will raise AlreadyRegistered.
    6768        """
     69        do_validate = admin_class and settings.DEBUG
     70        if do_validate:
     71            # don't import the humongous validation code unless necessary
     72            from django.contrib.admin.validation import validate
    6873        admin_class = admin_class or ModelAdmin
    6974        # TODO: Handle options
    7075        if isinstance(model_or_iterable, ModelBase):
     
    7277        for model in model_or_iterable:
    7378            if model in self._registry:
    7479                raise AlreadyRegistered('The model %s is already registered' % model.__name__)
     80            if do_validate:
     81                validate(admin_class, model)
    7582            self._registry[model] = admin_class(model, self)
    7683
    7784    def unregister(self, model_or_iterable):
Back to Top