Ticket #8241: onetoone_admin.8541.diff
File onetoone_admin.8541.diff, 3.2 KB (added by , 16 years ago) |
---|
-
django/forms/models.py
28 28 If commit=True, then the changes to ``instance`` will be saved to the 29 29 database. Returns ``instance``. 30 30 """ 31 from django.db import models31 from django.db.models import AutoField, OneToOneField 32 32 opts = instance._meta 33 33 if form.errors: 34 34 raise ValueError("The %s could not be %s because the data didn't" 35 35 " validate." % (opts.object_name, fail_message)) 36 36 cleaned_data = form.cleaned_data 37 37 for f in opts.fields: 38 if not f.editable or isinstance(f, models.AutoField) \38 if not f.editable or isinstance(f, (AutoField, OneToOneField)) \ 39 39 or not f.name in cleaned_data: 40 40 continue 41 41 if fields and f.name not in fields: … … 96 96 the ``fields`` argument. 97 97 """ 98 98 # avoid a circular import 99 from django.db.models.fields.related import ManyToManyField , OneToOneField99 from django.db.models.fields.related import ManyToManyField 100 100 opts = instance._meta 101 101 data = {} 102 102 for f in opts.fields + opts.many_to_many: … … 107 107 if exclude and f.name in exclude: 108 108 continue 109 109 if isinstance(f, ManyToManyField): 110 # If the object doesn't have a prim ry key yet, just use an empty110 # If the object doesn't have a primary key yet, just use an empty 111 111 # list for its m2m fields. Calling f.value_from_object will raise 112 112 # an exception. 113 113 if instance.pk is None: … … 115 115 else: 116 116 # MultipleChoiceWidget needs a list of pks, not object instances. 117 117 data[f.name] = [obj.pk for obj in f.value_from_object(instance)] 118 elif isinstance(f, OneToOneField):119 data[f.attname] = f.value_from_object(instance)120 118 else: 121 119 data[f.name] = f.value_from_object(instance) 122 120 return data … … 291 289 existing_objects[obj.pk] = obj 292 290 saved_instances = [] 293 291 for form in self.initial_forms: 294 obj = existing_objects[form.cleaned_data[self. model._meta.pk.attname]]292 obj = existing_objects[form.cleaned_data[self._pk_field_name]] 295 293 if self.can_delete and form.cleaned_data[DELETION_FIELD_NAME]: 296 294 self.deleted_objects.append(obj) 297 295 obj.delete() … … 319 317 320 318 def add_fields(self, form, index): 321 319 """Add a hidden field for the object's primary key.""" 322 if self.model._meta.pk.auto_created: 323 self._pk_field_name = self.model._meta.pk.attname 320 from django.db.models import OneToOneField 321 pk = self.model._meta.pk 322 while isinstance(pk, OneToOneField): 323 pk = pk.rel.to._meta.pk # Drill down until we find a "real" pk 324 if pk.auto_created: 325 self._pk_field_name = self.model._meta.pk.name 324 326 form.fields[self._pk_field_name] = IntegerField(required=False, widget=HiddenInput) 325 327 super(BaseModelFormSet, self).add_fields(form, index) 326 328