Changeset 9208
- Timestamp:
- 10/08/08 05:09:44 (3 months ago)
- Files:
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
django/trunk/django/forms/models.py
r9086 r9208 15 15 from widgets import media_property 16 16 from formsets import BaseFormSet, formset_factory, DELETION_FIELD_NAME 17 18 try: 19 set 20 except NameError: 21 from sets import Set as set # Python 2.3 fallback 17 22 18 23 __all__ = ( … … 220 225 if len(fields_on_form) == len(check): 221 226 unique_checks.append(check) 222 227 223 228 form_errors = [] 224 229 225 230 # Gather a list of checks for fields declared as unique and add them to 226 231 # the list of checks. Again, skip fields not on the form. … … 236 241 if name in self.cleaned_data and f.unique and not is_null_pk: 237 242 unique_checks.append((name,)) 238 243 239 244 # Don't run unique checks on fields that already have an error. 240 245 unique_checks = [check for check in unique_checks if not [x in self._errors for x in check if x in self._errors]] 241 246 247 bad_fields = set() 242 248 for unique_check in unique_checks: 243 249 # Try to look up an existing object with the same values as this 244 250 # object's values for all the unique field. 245 251 246 252 lookup_kwargs = {} 247 253 for field_name in unique_check: 248 254 lookup_kwargs[field_name] = self.cleaned_data[field_name] 249 255 250 256 qs = self.instance.__class__._default_manager.filter(**lookup_kwargs) 251 257 252 # Exclude the current object from the query if we are editing an 258 # Exclude the current object from the query if we are editing an 253 259 # instance (as opposed to creating a new one) 254 260 if self.instance.pk is not None: 255 261 qs = qs.exclude(pk=self.instance.pk) 256 262 257 263 # This cute trick with extra/values is the most efficient way to 258 264 # tell if a particular query returns any results. 259 265 if qs.extra(select={'a': 1}).values('a').order_by(): 260 266 model_name = capfirst(self.instance._meta.verbose_name) 261 267 262 268 # A unique field 263 269 if len(unique_check) == 1: … … 279 285 'field_label': unicode(field_labels)} 280 286 ) 281 282 # Remove the data from the cleaned_data dict since it was invalid 287 288 # Mark these fields as needing to be removed from cleaned data 289 # later. 283 290 for field_name in unique_check: 284 del self.cleaned_data[field_name] 285 291 bad_fields.add(field_name) 292 293 for field_name in bad_fields: 294 del self.cleaned_data[field_name] 286 295 if form_errors: 287 # Raise the unique together errors since they are considered form-wide. 296 # Raise the unique together errors since they are considered 297 # form-wide. 288 298 raise ValidationError(form_errors) 289 299 … … 472 482 new_obj = self.model(**kwargs) 473 483 return save_instance(form, new_obj, exclude=[self._pk_field.name], commit=commit) 474 484 475 485 def add_fields(self, form, index): 476 486 super(BaseInlineFormSet, self).add_fields(form, index)
