Commits

Anonymous committed f0e7c07

Fixed #8795: unique_together validation no longer fails on model forms that exclude fields included in the check. Thanks, Alex Gaynor.

Comments (0)

Files changed (2)

django/forms/models.py

 
     def validate_unique(self):
         from django.db.models.fields import FieldDoesNotExist
-        unique_checks = list(self.instance._meta.unique_together[:])
+
+        # Gather a list of checks to perform. Since this is a ModelForm, some
+        # fields may have been excluded; we can't perform a unique check on a
+        # form that is missing fields involved in that check.
+        unique_checks = []
+        for check in self.instance._meta.unique_together[:]:
+            fields_on_form = [field for field in check if field in self.fields]
+            if len(fields_on_form) == len(check):
+                unique_checks.append(check)
+            
         form_errors = []
         
-        # Make sure the unique checks apply to actual fields on the ModelForm
+        # Gather a list of checks for fields declared as unique and add them to
+        # the list of checks. Again, skip fields not on the form.
         for name, field in self.fields.items():
             try:
                 f = self.instance._meta.get_field_by_name(name)[0]

tests/modeltests/model_forms/models.py

 >>> form._errors
 {'__all__': [u'Price with this Price and Quantity already exists.']}
 
+>>> class PriceForm(ModelForm):
+...     class Meta:
+...         model = Price
+...         exclude = ('quantity',)
+>>> form = PriceForm({'price': '6.00'})
+>>> form.is_valid()
+True
+
 # Choices on CharField and IntegerField
 >>> class ArticleForm(ModelForm):
 ...     class Meta:
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.