Ticket #12203: 12203-m2m-w-through-modeladmin-fields-option1.diff

File 12203-m2m-w-through-modeladmin-fields-option1.diff, 2.4 KB (added by ramiro, 6 years ago)

patch implementing first admin validation strategy described by Russell

  • django/contrib/admin/validation.py

    diff --git a/django/contrib/admin/validation.py b/django/contrib/admin/validation.py
    a b  
    149149            validate_inline(inline, cls, model)
    150150
    151151def validate_inline(cls, parent, parent_model):
    152    
     152
    153153    # model is already verified to exist and be a Model
    154154    if cls.fk_name: # default value is None
    155155        f = get_field(cls, cls.model, cls.model._meta, 'fk_name', cls.fk_name)
     
    200200            raise ImproperlyConfigured('Both fieldsets and fields are specified in %s.' % cls.__name__)
    201201        if len(cls.fields) > len(set(cls.fields)):
    202202            raise ImproperlyConfigured('There are duplicate field(s) in %s.fields' % cls.__name__)
     203        for idx, field in enumerate(cls.fields):
     204            f = get_field(cls, model, opts, 'fields', field)
     205            if isinstance(f, models.ManyToManyField) and f.rel.through:
     206                raise ImproperlyConfigured("'fields' option can't include a ManyToManyField field that uses the 'through' option. Problem is in %s.fields, '%s' field." % (cls.__name__, field))
    203207
    204208    # fieldsets
    205209    if cls.fieldsets: # default value is None
  • tests/regressiontests/admin_validation/models.py

    diff --git a/tests/regressiontests/admin_validation/models.py b/tests/regressiontests/admin_validation/models.py
    a b  
    2626    e = models.CharField(max_length=1)
    2727
    2828
     29class Author(models.Model):
     30    name = models.CharField(max_length=100)
     31
     32
     33class Book(models.Model):
     34    name = models.CharField(max_length=100)
     35    authors = models.ManyToManyField(Author, through='AuthorsBooks')
     36
     37
     38class AuthorsBooks(models.Model):
     39    author = models.ForeignKey(Author)
     40    book = models.ForeignKey(Book)
     41
    2942
    3043__test__ = {'API_TESTS':"""
    3144
     
    95108
    96109>>> validate_inline(TwoAlbumFKAndAnEInline, None, Album)
    97110
     111# Regression test for #12203 - Fail more gracefully when a M2M field that
     112# specifies the 'through' option is included in the 'fields' ModelAdmin option.
     113
     114>>> class BookAdmin(admin.ModelAdmin):
     115...     fields = ['authors']
     116
     117>>> validate(BookAdmin, Book)
     118Traceback (most recent call last):
     119    ...
     120ImproperlyConfigured: 'fields' option can't include a ManyToManyField field that uses the 'through' option. Problem is in BookAdmin.fields, 'authors' field.
    98121"""}
Back to Top