Ticket #14639: 14639-admin-site-prevent-abstract-registration.patch

File 14639-admin-site-prevent-abstract-registration.patch, 2.2 KB (added by Craig de Stigter, 14 years ago)

Prevent registration of abstract models with AdminSite.register(). Includes regression test

  • django/contrib/admin/sites.py

    diff --git a/django/contrib/admin/sites.py b/django/contrib/admin/sites.py
    index b995c0f..899a8a2 100644
    a b class AdminSite(object):  
    7878            if model in self._registry:
    7979                raise AlreadyRegistered('The model %s is already registered' % model.__name__)
    8080
     81            if model._meta.abstract:
     82                raise ValueError("Cannot register %s because it is an abstract model")
     83
    8184            # If we got **options then dynamically construct a subclass of
    8285            # admin_class with those **options.
    8386            if options:
  • tests/regressiontests/admin_registration/models.py

    diff --git a/tests/regressiontests/admin_registration/models.py b/tests/regressiontests/admin_registration/models.py
    index 4a2d4e9..ad786f5 100644
    a b class Person(models.Model):  
    99
    1010class Place(models.Model):
    1111    name = models.CharField(max_length=200)
     12
     13class AbstractModel(models.Model):
     14    name = models.CharField(max_length=200)
     15    class Meta:
     16        abstract = True
     17
     18class ConcreteModel(AbstractModel):
     19    description = models.CharField(max_length=200)
  • tests/regressiontests/admin_registration/tests.py

    diff --git a/tests/regressiontests/admin_registration/tests.py b/tests/regressiontests/admin_registration/tests.py
    index e2a5d7e..f0cbd01 100644
    a b from django.test import TestCase  
    22
    33from django.contrib import admin
    44
    5 from models import Person, Place
     5from models import Person, Place, AbstractModel, ConcreteModel
    66
    77class NameAdmin(admin.ModelAdmin):
    88    list_display = ['name']
    class TestRegistration(TestCase):  
    3030                          self.site.register,
    3131                          Person)
    3232
     33    def test_prevent_abstract_registration(self):
     34        self.site.register(ConcreteModel)
     35        self.assertRaises(ValueError,
     36                          self.site.register,
     37                          AbstractModel)
     38
    3339    def test_registration_with_star_star_options(self):
    3440        self.site.register(Person, search_fields=['name'])
    3541        self.assertEqual(self.site._registry[Person].search_fields, ['name'])
Back to Top