Ticket #8562: 8562_primary_uniques.diff

File 8562_primary_uniques.diff, 1.9 KB (added by magneto, 16 years ago)

treat OneToOne+primary & ForeignKey+unique+primary as a type of Form Autofield

  • django/forms/models.py

     
    9696    the ``fields`` argument.
    9797    """
    9898    # avoid a circular import
    99     from django.db.models.fields.related import ManyToManyField, OneToOneField
     99    from django.db.models.fields.related import ManyToManyField, OneToOneField, ForeignKey
    100100    opts = instance._meta
    101101    data = {}
    102102    for f in opts.fields + opts.many_to_many:
     
    117117                data[f.name] = [obj.pk for obj in f.value_from_object(instance)]
    118118        elif isinstance(f, OneToOneField):
    119119            data[f.attname] = f.value_from_object(instance)
     120            data[f.name] = data[f.attname]
     121        elif isinstance(f, ForeignKey) and f.primary_key and f.unique:
     122            data[f.attname] = f.value_from_object(instance)
     123            data[f.name] = data[f.attname]
    120124        else:
    121125            data[f.name] = f.value_from_object(instance)
    122126    return data
     
    319323
    320324    def add_fields(self, form, index):
    321325        """Add a hidden field for the object's primary key."""
    322         if self.model._meta.pk.auto_created:
     326        # include both edges ot OneToOne Primary key, and
     327        # ForeignKey, primary key, unique .. which is a OneToOne in reality
     328        from django.db.models.fields.related import OneToOneField, ForeignKey
     329        if self.model._meta.pk.auto_created or (self.model._meta.pk.primary_key \
     330               and ((isinstance(self.model._meta.pk, OneToOneField)) or \
     331               (isinstance(self.model._meta.pk, ForeignKey) and self.model._meta.pk.unique))):
    323332            self._pk_field_name = self.model._meta.pk.attname
    324333            form.fields[self._pk_field_name] = IntegerField(required=False, widget=HiddenInput)
    325334        super(BaseModelFormSet, self).add_fields(form, index)
Back to Top