Kaydet (Commit) 4ad1eb1c authored tarafından Honza Kral's avatar Honza Kral

Fixed #12674 -- provide a way to override admin validation

Moved admin validation code to classes and have those be class
attributes to the ModelAdmin classes.
üst 886f7cc7
...@@ -10,6 +10,7 @@ from django.contrib.contenttypes.models import ContentType ...@@ -10,6 +10,7 @@ from django.contrib.contenttypes.models import ContentType
from django.contrib.admin import widgets, helpers from django.contrib.admin import widgets, helpers
from django.contrib.admin.util import (unquote, flatten_fieldsets, get_deleted_objects, from django.contrib.admin.util import (unquote, flatten_fieldsets, get_deleted_objects,
model_format_dict, NestedObjects) model_format_dict, NestedObjects)
from django.contrib.admin import validation
from django.contrib.admin.templatetags.admin_static import static from django.contrib.admin.templatetags.admin_static import static
from django.contrib import messages from django.contrib import messages
from django.views.decorators.csrf import csrf_protect from django.views.decorators.csrf import csrf_protect
...@@ -87,6 +88,14 @@ class BaseModelAdmin(six.with_metaclass(RenameBaseModelAdminMethods)): ...@@ -87,6 +88,14 @@ class BaseModelAdmin(six.with_metaclass(RenameBaseModelAdminMethods)):
readonly_fields = () readonly_fields = ()
ordering = None ordering = None
# validation
validator_class = validation.BaseValidator
@classmethod
def validate(cls, model):
validator = cls.validator_class()
validator.validate(cls, model)
def __init__(self): def __init__(self):
overrides = FORMFIELD_FOR_DBFIELD_DEFAULTS.copy() overrides = FORMFIELD_FOR_DBFIELD_DEFAULTS.copy()
overrides.update(self.formfield_overrides) overrides.update(self.formfield_overrides)
...@@ -371,6 +380,9 @@ class ModelAdmin(BaseModelAdmin): ...@@ -371,6 +380,9 @@ class ModelAdmin(BaseModelAdmin):
actions_on_bottom = False actions_on_bottom = False
actions_selection_counter = True actions_selection_counter = True
# validation
validator_class = validation.ModelAdminValidator
def __init__(self, model, admin_site): def __init__(self, model, admin_site):
self.model = model self.model = model
self.opts = model._meta self.opts = model._meta
...@@ -1447,6 +1459,9 @@ class InlineModelAdmin(BaseModelAdmin): ...@@ -1447,6 +1459,9 @@ class InlineModelAdmin(BaseModelAdmin):
verbose_name_plural = None verbose_name_plural = None
can_delete = True can_delete = True
# validation
validator_class = validation.InlineValidator
def __init__(self, parent_model, admin_site): def __init__(self, parent_model, admin_site):
self.admin_site = admin_site self.admin_site = admin_site
self.parent_model = parent_model self.parent_model = parent_model
......
...@@ -66,12 +66,6 @@ class AdminSite(object): ...@@ -66,12 +66,6 @@ class AdminSite(object):
if not admin_class: if not admin_class:
admin_class = ModelAdmin admin_class = ModelAdmin
# Don't import the humongous validation code unless required
if admin_class and settings.DEBUG:
from django.contrib.admin.validation import validate
else:
validate = lambda model, adminclass: None
if isinstance(model_or_iterable, ModelBase): if isinstance(model_or_iterable, ModelBase):
model_or_iterable = [model_or_iterable] model_or_iterable = [model_or_iterable]
for model in model_or_iterable: for model in model_or_iterable:
...@@ -94,8 +88,8 @@ class AdminSite(object): ...@@ -94,8 +88,8 @@ class AdminSite(object):
options['__module__'] = __name__ options['__module__'] = __name__
admin_class = type("%sAdmin" % model.__name__, (admin_class,), options) admin_class = type("%sAdmin" % model.__name__, (admin_class,), options)
# Validate (which might be a no-op) if admin_class is not ModelAdmin and settings.DEBUG:
validate(admin_class, model) admin_class.validate(model)
# Instantiate the admin class to save in the registry # Instantiate the admin class to save in the registry
self._registry[model] = admin_class(model, self) self._registry[model] = admin_class(model, self)
......
...@@ -2,7 +2,6 @@ from __future__ import absolute_import ...@@ -2,7 +2,6 @@ from __future__ import absolute_import
from django import forms from django import forms
from django.contrib import admin from django.contrib import admin
from django.contrib.admin.validation import validate, validate_inline
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase from django.test import TestCase
...@@ -38,13 +37,13 @@ class ValidationTestCase(TestCase): ...@@ -38,13 +37,13 @@ class ValidationTestCase(TestCase):
"fields": ["title", "original_release"], "fields": ["title", "original_release"],
}), }),
] ]
validate(SongAdmin, Song) SongAdmin.validate(Song)
def test_custom_modelforms_with_fields_fieldsets(self): def test_custom_modelforms_with_fields_fieldsets(self):
""" """
# Regression test for #8027: custom ModelForms with fields/fieldsets # Regression test for #8027: custom ModelForms with fields/fieldsets
""" """
validate(ValidFields, Song) ValidFields.validate(Song)
def test_custom_get_form_with_fieldsets(self): def test_custom_get_form_with_fieldsets(self):
""" """
...@@ -52,7 +51,7 @@ class ValidationTestCase(TestCase): ...@@ -52,7 +51,7 @@ class ValidationTestCase(TestCase):
is overridden. is overridden.
Refs #19445. Refs #19445.
""" """
validate(ValidFormFieldsets, Song) ValidFormFieldsets.validate(Song)
def test_exclude_values(self): def test_exclude_values(self):
""" """
...@@ -62,16 +61,16 @@ class ValidationTestCase(TestCase): ...@@ -62,16 +61,16 @@ class ValidationTestCase(TestCase):
exclude = ('foo') exclude = ('foo')
self.assertRaisesMessage(ImproperlyConfigured, self.assertRaisesMessage(ImproperlyConfigured,
"'ExcludedFields1.exclude' must be a list or tuple.", "'ExcludedFields1.exclude' must be a list or tuple.",
validate, ExcludedFields1.validate,
ExcludedFields1, Book) Book)
def test_exclude_duplicate_values(self): def test_exclude_duplicate_values(self):
class ExcludedFields2(admin.ModelAdmin): class ExcludedFields2(admin.ModelAdmin):
exclude = ('name', 'name') exclude = ('name', 'name')
self.assertRaisesMessage(ImproperlyConfigured, self.assertRaisesMessage(ImproperlyConfigured,
"There are duplicate field(s) in ExcludedFields2.exclude", "There are duplicate field(s) in ExcludedFields2.exclude",
validate, ExcludedFields2.validate,
ExcludedFields2, Book) Book)
def test_exclude_in_inline(self): def test_exclude_in_inline(self):
class ExcludedFieldsInline(admin.TabularInline): class ExcludedFieldsInline(admin.TabularInline):
...@@ -84,8 +83,8 @@ class ValidationTestCase(TestCase): ...@@ -84,8 +83,8 @@ class ValidationTestCase(TestCase):
self.assertRaisesMessage(ImproperlyConfigured, self.assertRaisesMessage(ImproperlyConfigured,
"'ExcludedFieldsInline.exclude' must be a list or tuple.", "'ExcludedFieldsInline.exclude' must be a list or tuple.",
validate, ExcludedFieldsAlbumAdmin.validate,
ExcludedFieldsAlbumAdmin, Album) Album)
def test_exclude_inline_model_admin(self): def test_exclude_inline_model_admin(self):
""" """
...@@ -102,8 +101,8 @@ class ValidationTestCase(TestCase): ...@@ -102,8 +101,8 @@ class ValidationTestCase(TestCase):
self.assertRaisesMessage(ImproperlyConfigured, self.assertRaisesMessage(ImproperlyConfigured,
"SongInline cannot exclude the field 'album' - this is the foreign key to the parent model admin_validation.Album.", "SongInline cannot exclude the field 'album' - this is the foreign key to the parent model admin_validation.Album.",
validate, AlbumAdmin.validate,
AlbumAdmin, Album) Album)
def test_app_label_in_admin_validation(self): def test_app_label_in_admin_validation(self):
""" """
...@@ -114,8 +113,8 @@ class ValidationTestCase(TestCase): ...@@ -114,8 +113,8 @@ class ValidationTestCase(TestCase):
self.assertRaisesMessage(ImproperlyConfigured, self.assertRaisesMessage(ImproperlyConfigured,
"'RawIdNonexistingAdmin.raw_id_fields' refers to field 'nonexisting' that is missing from model 'admin_validation.Album'.", "'RawIdNonexistingAdmin.raw_id_fields' refers to field 'nonexisting' that is missing from model 'admin_validation.Album'.",
validate, RawIdNonexistingAdmin.validate,
RawIdNonexistingAdmin, Album) Album)
def test_fk_exclusion(self): def test_fk_exclusion(self):
""" """
...@@ -127,28 +126,35 @@ class ValidationTestCase(TestCase): ...@@ -127,28 +126,35 @@ class ValidationTestCase(TestCase):
model = TwoAlbumFKAndAnE model = TwoAlbumFKAndAnE
exclude = ("e",) exclude = ("e",)
fk_name = "album1" fk_name = "album1"
validate_inline(TwoAlbumFKAndAnEInline, None, Album) class MyAdmin(admin.ModelAdmin):
inlines = [TwoAlbumFKAndAnEInline]
MyAdmin.validate(Album)
def test_inline_self_validation(self): def test_inline_self_validation(self):
class TwoAlbumFKAndAnEInline(admin.TabularInline): class TwoAlbumFKAndAnEInline(admin.TabularInline):
model = TwoAlbumFKAndAnE model = TwoAlbumFKAndAnE
class MyAdmin(admin.ModelAdmin):
inlines = [TwoAlbumFKAndAnEInline]
self.assertRaisesMessage(Exception, self.assertRaisesMessage(Exception,
"<class 'admin_validation.models.TwoAlbumFKAndAnE'> has more than 1 ForeignKey to <class 'admin_validation.models.Album'>", "<class 'admin_validation.models.TwoAlbumFKAndAnE'> has more than 1 ForeignKey to <class 'admin_validation.models.Album'>",
validate_inline, MyAdmin.validate, Album)
TwoAlbumFKAndAnEInline, None, Album)
def test_inline_with_specified(self): def test_inline_with_specified(self):
class TwoAlbumFKAndAnEInline(admin.TabularInline): class TwoAlbumFKAndAnEInline(admin.TabularInline):
model = TwoAlbumFKAndAnE model = TwoAlbumFKAndAnE
fk_name = "album1" fk_name = "album1"
validate_inline(TwoAlbumFKAndAnEInline, None, Album)
class MyAdmin(admin.ModelAdmin):
inlines = [TwoAlbumFKAndAnEInline]
MyAdmin.validate(Album)
def test_readonly(self): def test_readonly(self):
class SongAdmin(admin.ModelAdmin): class SongAdmin(admin.ModelAdmin):
readonly_fields = ("title",) readonly_fields = ("title",)
validate(SongAdmin, Song) SongAdmin.validate(Song)
def test_readonly_on_method(self): def test_readonly_on_method(self):
def my_function(obj): def my_function(obj):
...@@ -157,7 +163,7 @@ class ValidationTestCase(TestCase): ...@@ -157,7 +163,7 @@ class ValidationTestCase(TestCase):
class SongAdmin(admin.ModelAdmin): class SongAdmin(admin.ModelAdmin):
readonly_fields = (my_function,) readonly_fields = (my_function,)
validate(SongAdmin, Song) SongAdmin.validate(Song)
def test_readonly_on_modeladmin(self): def test_readonly_on_modeladmin(self):
class SongAdmin(admin.ModelAdmin): class SongAdmin(admin.ModelAdmin):
...@@ -166,13 +172,13 @@ class ValidationTestCase(TestCase): ...@@ -166,13 +172,13 @@ class ValidationTestCase(TestCase):
def readonly_method_on_modeladmin(self, obj): def readonly_method_on_modeladmin(self, obj):
pass pass
validate(SongAdmin, Song) SongAdmin.validate(Song)
def test_readonly_method_on_model(self): def test_readonly_method_on_model(self):
class SongAdmin(admin.ModelAdmin): class SongAdmin(admin.ModelAdmin):
readonly_fields = ("readonly_method_on_model",) readonly_fields = ("readonly_method_on_model",)
validate(SongAdmin, Song) SongAdmin.validate(Song)
def test_nonexistant_field(self): def test_nonexistant_field(self):
class SongAdmin(admin.ModelAdmin): class SongAdmin(admin.ModelAdmin):
...@@ -180,8 +186,8 @@ class ValidationTestCase(TestCase): ...@@ -180,8 +186,8 @@ class ValidationTestCase(TestCase):
self.assertRaisesMessage(ImproperlyConfigured, self.assertRaisesMessage(ImproperlyConfigured,
"SongAdmin.readonly_fields[1], 'nonexistant' is not a callable or an attribute of 'SongAdmin' or found in the model 'Song'.", "SongAdmin.readonly_fields[1], 'nonexistant' is not a callable or an attribute of 'SongAdmin' or found in the model 'Song'.",
validate, SongAdmin.validate,
SongAdmin, Song) Song)
def test_nonexistant_field_on_inline(self): def test_nonexistant_field_on_inline(self):
class CityInline(admin.TabularInline): class CityInline(admin.TabularInline):
...@@ -190,8 +196,8 @@ class ValidationTestCase(TestCase): ...@@ -190,8 +196,8 @@ class ValidationTestCase(TestCase):
self.assertRaisesMessage(ImproperlyConfigured, self.assertRaisesMessage(ImproperlyConfigured,
"CityInline.readonly_fields[0], 'i_dont_exist' is not a callable or an attribute of 'CityInline' or found in the model 'City'.", "CityInline.readonly_fields[0], 'i_dont_exist' is not a callable or an attribute of 'CityInline' or found in the model 'City'.",
validate_inline, CityInline.validate,
CityInline, None, State) City)
def test_extra(self): def test_extra(self):
class SongAdmin(admin.ModelAdmin): class SongAdmin(admin.ModelAdmin):
...@@ -199,13 +205,13 @@ class ValidationTestCase(TestCase): ...@@ -199,13 +205,13 @@ class ValidationTestCase(TestCase):
if instance.title == "Born to Run": if instance.title == "Born to Run":
return "Best Ever!" return "Best Ever!"
return "Status unknown." return "Status unknown."
validate(SongAdmin, Song) SongAdmin.validate(Song)
def test_readonly_lambda(self): def test_readonly_lambda(self):
class SongAdmin(admin.ModelAdmin): class SongAdmin(admin.ModelAdmin):
readonly_fields = (lambda obj: "test",) readonly_fields = (lambda obj: "test",)
validate(SongAdmin, Song) SongAdmin.validate(Song)
def test_graceful_m2m_fail(self): def test_graceful_m2m_fail(self):
""" """
...@@ -219,8 +225,8 @@ class ValidationTestCase(TestCase): ...@@ -219,8 +225,8 @@ class ValidationTestCase(TestCase):
self.assertRaisesMessage(ImproperlyConfigured, self.assertRaisesMessage(ImproperlyConfigured,
"'BookAdmin.fields' can't include the ManyToManyField field 'authors' because 'authors' manually specifies a 'through' model.", "'BookAdmin.fields' can't include the ManyToManyField field 'authors' because 'authors' manually specifies a 'through' model.",
validate, BookAdmin.validate,
BookAdmin, Book) Book)
def test_cannot_include_through(self): def test_cannot_include_through(self):
class FieldsetBookAdmin(admin.ModelAdmin): class FieldsetBookAdmin(admin.ModelAdmin):
...@@ -230,20 +236,20 @@ class ValidationTestCase(TestCase): ...@@ -230,20 +236,20 @@ class ValidationTestCase(TestCase):
) )
self.assertRaisesMessage(ImproperlyConfigured, self.assertRaisesMessage(ImproperlyConfigured,
"'FieldsetBookAdmin.fieldsets[1][1]['fields']' can't include the ManyToManyField field 'authors' because 'authors' manually specifies a 'through' model.", "'FieldsetBookAdmin.fieldsets[1][1]['fields']' can't include the ManyToManyField field 'authors' because 'authors' manually specifies a 'through' model.",
validate, FieldsetBookAdmin.validate,
FieldsetBookAdmin, Book) Book)
def test_nested_fields(self): def test_nested_fields(self):
class NestedFieldsAdmin(admin.ModelAdmin): class NestedFieldsAdmin(admin.ModelAdmin):
fields = ('price', ('name', 'subtitle')) fields = ('price', ('name', 'subtitle'))
validate(NestedFieldsAdmin, Book) NestedFieldsAdmin.validate(Book)
def test_nested_fieldsets(self): def test_nested_fieldsets(self):
class NestedFieldsetAdmin(admin.ModelAdmin): class NestedFieldsetAdmin(admin.ModelAdmin):
fieldsets = ( fieldsets = (
('Main', {'fields': ('price', ('name', 'subtitle'))}), ('Main', {'fields': ('price', ('name', 'subtitle'))}),
) )
validate(NestedFieldsetAdmin, Book) NestedFieldsetAdmin.validate(Book)
def test_explicit_through_override(self): def test_explicit_through_override(self):
""" """
...@@ -260,7 +266,7 @@ class ValidationTestCase(TestCase): ...@@ -260,7 +266,7 @@ class ValidationTestCase(TestCase):
# If the through model is still a string (and hasn't been resolved to a model) # If the through model is still a string (and hasn't been resolved to a model)
# the validation will fail. # the validation will fail.
validate(BookAdmin, Book) BookAdmin.validate(Book)
def test_non_model_fields(self): def test_non_model_fields(self):
""" """
...@@ -274,7 +280,7 @@ class ValidationTestCase(TestCase): ...@@ -274,7 +280,7 @@ class ValidationTestCase(TestCase):
form = SongForm form = SongForm
fields = ['title', 'extra_data'] fields = ['title', 'extra_data']
validate(FieldsOnFormOnlyAdmin, Song) FieldsOnFormOnlyAdmin.validate(Song)
def test_non_model_first_field(self): def test_non_model_first_field(self):
""" """
...@@ -292,4 +298,4 @@ class ValidationTestCase(TestCase): ...@@ -292,4 +298,4 @@ class ValidationTestCase(TestCase):
form = SongForm form = SongForm
fields = ['extra_data', 'title'] fields = ['extra_data', 'title']
validate(FieldsOnFormOnlyAdmin, Song) FieldsOnFormOnlyAdmin.validate(Song)
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment