Ticket #8620: django_model_forms_excluding_fields_fix_2.diff

File django_model_forms_excluding_fields_fix_2.diff, 2.4 KB (added by shimonrura, 14 years ago)

updated patch with tests based on r15800

  • django/forms/models.py

     
    214214                raise FieldError(message)
    215215            # Override default model fields with any custom declared ones
    216216            # (plus, include all the other declared fields).
     217            if opts.fields:
     218                [declared_fields.pop(f) for f in declared_fields.keys() if f not in opts.fields]
     219            if opts.exclude:
     220                [declared_fields.pop(f) for f in declared_fields.keys() if f in opts.exclude]
    217221            fields.update(declared_fields)
    218222        else:
    219223            fields = declared_fields
  • tests/regressiontests/forms/tests/models.py

     
    11# -*- coding: utf-8 -*-
    22import datetime
    33from django.core.files.uploadedfile import SimpleUploadedFile
    4 from django.forms import Form, ModelForm, FileField, ModelChoiceField
     4from django.forms import Form, ModelForm, FileField, ModelChoiceField, CharField
    55from django.test import TestCase
    66from regressiontests.forms.models import ChoiceModel, ChoiceOptionModel, ChoiceFieldModel, FileModel, Group, BoundaryModel, Defaults
    77
     
    154154
    155155        f = ExcludingForm({'name': u'Hello', 'value': 99, 'def_date': datetime.date(1999, 3, 2)})
    156156        self.assertTrue(f.is_valid())
    157         self.assertEqual(f.cleaned_data['name'], u'Hello')
     157        self.assertNotIn('name', f.cleaned_data)
    158158        obj = f.save()
    159159        self.assertEqual(obj.name, u'class default value')
    160160        self.assertEqual(obj.value, 99)
    161161        self.assertEqual(obj.def_date, datetime.date(1999, 3, 2))
     162
     163
     164class TestTicket8620(TestCase):
     165    '''Allow exclusion of not only model fields but also form fields (as
     166    might be defined in a superclass) using the exclude Meta attribute.'''
     167
     168    class ParentForm(ModelForm):
     169        extra_non_model_field = CharField()
     170
     171    class ChildForm(ParentForm):
     172        class Meta:
     173            model = Defaults  # any model is suitable for this test
     174            exclude = ('extra_non_model_field',)
     175
     176    def test_extra_non_model_field_is_excluded(self):
     177        form = TestTicket8620.ChildForm()
     178        self.assertNotIn('extra_non_model_field', form.fields)
Back to Top