Commits

Anonymous committed 8877745

Fixed #10069 -- Fixed the model form unique validation code to not proceed with using, for example, RelatedObjects returned by get_field_by_name as though they were model Fields.

  • Participants
  • Parent commits 7f48507

Comments (0)

Files changed (2)

django/forms/models.py

         return self.cleaned_data
 
     def validate_unique(self):
-        from django.db.models.fields import FieldDoesNotExist
+        from django.db.models.fields import FieldDoesNotExist, Field as ModelField
 
         # Gather a list of checks to perform. We only perform unique checks
         # for fields present and not None in cleaned_data.  Since this is a
             except FieldDoesNotExist:
                 # This is an extra field that's not on the ModelForm, ignore it
                 continue
+            if not isinstance(f, ModelField):
+                # This is an extra field that happens to have a name that matches, 
+                # for example, a related object accessor for this model.  So 
+                # get_field_by_name found it, but it is not a Field so do not proceed
+                # to use it as if it were.
+                continue
             if f.unique and self.cleaned_data.get(name) is not None:
                 unique_checks.append((name,))
 

tests/modeltests/model_forms/models.py

 >>> CategoryForm.base_fields.keys()
 ['name', 'slug', 'url', 'some_extra_field']
 
+Extra field that has a name collision with a related object accessor.
+
+>>> class WriterForm(ModelForm):
+...     book = forms.CharField(required=False)
+...
+...     class Meta:
+...         model = Writer
+
+>>> wf = WriterForm({'name': 'Richard Lockridge'})
+>>> wf.is_valid()
+True
 
 Replacing a field.