Code

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, 3 years ago)

updated patch with tests based on r15800

Line 
1Index: django/forms/models.py
2===================================================================
3--- django/forms/models.py      (revision 15800)
4+++ django/forms/models.py      (working copy)
5@@ -214,6 +214,10 @@
6                 raise FieldError(message)
7             # Override default model fields with any custom declared ones
8             # (plus, include all the other declared fields).
9+            if opts.fields:
10+                [declared_fields.pop(f) for f in declared_fields.keys() if f not in opts.fields]
11+            if opts.exclude:
12+                [declared_fields.pop(f) for f in declared_fields.keys() if f in opts.exclude]
13             fields.update(declared_fields)
14         else:
15             fields = declared_fields
16Index: tests/regressiontests/forms/tests/models.py
17===================================================================
18--- tests/regressiontests/forms/tests/models.py (revision 15800)
19+++ tests/regressiontests/forms/tests/models.py (working copy)
20@@ -1,7 +1,7 @@
21 # -*- coding: utf-8 -*-
22 import datetime
23 from django.core.files.uploadedfile import SimpleUploadedFile
24-from django.forms import Form, ModelForm, FileField, ModelChoiceField
25+from django.forms import Form, ModelForm, FileField, ModelChoiceField, CharField
26 from django.test import TestCase
27 from regressiontests.forms.models import ChoiceModel, ChoiceOptionModel, ChoiceFieldModel, FileModel, Group, BoundaryModel, Defaults
28 
29@@ -154,8 +154,25 @@
30 
31         f = ExcludingForm({'name': u'Hello', 'value': 99, 'def_date': datetime.date(1999, 3, 2)})
32         self.assertTrue(f.is_valid())
33-        self.assertEqual(f.cleaned_data['name'], u'Hello')
34+        self.assertNotIn('name', f.cleaned_data)
35         obj = f.save()
36         self.assertEqual(obj.name, u'class default value')
37         self.assertEqual(obj.value, 99)
38         self.assertEqual(obj.def_date, datetime.date(1999, 3, 2))
39+
40+
41+class TestTicket8620(TestCase):
42+    '''Allow exclusion of not only model fields but also form fields (as
43+    might be defined in a superclass) using the exclude Meta attribute.'''
44+
45+    class ParentForm(ModelForm):
46+        extra_non_model_field = CharField()
47+
48+    class ChildForm(ParentForm):
49+        class Meta:
50+            model = Defaults  # any model is suitable for this test
51+            exclude = ('extra_non_model_field',)
52+
53+    def test_extra_non_model_field_is_excluded(self):
54+        form = TestTicket8620.ChildForm()
55+        self.assertNotIn('extra_non_model_field', form.fields)