diff --git a/django/forms/models.py b/django/forms/models.py index 595b775f4f..d62a2ce713 100644 --- a/django/forms/models.py +++ b/django/forms/models.py @@ -163,7 +163,7 @@ def fields_for_model(model, fields=None, exclude=None, formfield_callback=lambda field_list.append((f.name, formfield)) field_dict = SortedDict(field_list) if fields: - field_dict = SortedDict([(f, field_dict[f]) for f in fields if (not exclude) or (exclude and f not in exclude)]) + field_dict = SortedDict([(f, field_dict.get(f)) for f in fields if (not exclude) or (exclude and f not in exclude)]) return field_dict class ModelFormOptions(object): diff --git a/tests/modeltests/model_forms/models.py b/tests/modeltests/model_forms/models.py index 9261900bf8..4075250482 100644 --- a/tests/modeltests/model_forms/models.py +++ b/tests/modeltests/model_forms/models.py @@ -1450,6 +1450,19 @@ ValidationError: [u'Select a valid choice. z is not one of the available choices >>> core.parent +>>> class CategoryForm(ModelForm): +... description = forms.CharField() +... class Meta: +... model = Category +... fields = ['description', 'url'] + +>>> CategoryForm.base_fields.keys() +['description', 'url'] + +>>> print CategoryForm() + + + # Clean up >>> import shutil >>> shutil.rmtree(temp_storage_dir)