Opened 12 years ago

Closed 12 years ago

#18912 closed Bug (worksforme)

ModelForm doesn't handle unique checks for parent models.

Reported by: Sebastian Noack Owned by: nobody
Component: Forms Version:
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

The unique checks performed by the ModelForm class, do not handle parent models. Unique fields inherited from a parent model are checked the same way as direct unique fields and therefore erroneously validates if there is a conflict in the parent model without a related object of the derived model.

class Animal(models.Model):
    name = models.CharField(max_length=100, unique=True)

class Mammal(Animal):
    pass

class Bird(Animal):
    pass

Bird.objects.create(name='Kiwi')

class MammalForm(ModelForm):
    class Meta:
        model = Mammal

form = MammalForm({'name': 'Kiwi'})
if form.is_valid(): # Returns true, as there is no Mammal with the name 'Kiwi'.
    form.save()     # Raises IntegrityError, because of there is already an Animal with the name 'Kiwi'.

Also unique_together definitions of parent models are completely ignored.

class Animal(models.Model):
    type = models.IntegerField(choices=((1, 'Mammal'), (2, 'Bird')))
    name = models.CharField(max_length=100)

    class Meta:
        unique_together = (('type', 'name'),)

class Mammal(Animal):
    pass

class Bird(Animal):
    pass

Mammal.objects.create(type=1, name='Cat')

class MammalForm(ModelForm):
    class Meta:
        model = Mammal

form = MammalForm({'type': 1, 'name': 'Cat'})
if form.is_valid(): # Returns true, because of unique_together definitions from parent models are ignored.
    form.save()     # Raises IntegrityError, because of there is already an Animal of type 1 (Mammal) and the name 'Cat'.

My patch will fix that behavior, making validation fail in the cases above.

Attachments (2)

0001-Made-ModelForm-correctly-handle-unique-checks-for-pa.patch (6.0 KB ) - added by Sebastian Noack 12 years ago.
0001-Made-ModelForm-correctly-handle-unique-checks-for-pa.2.patch (6.5 KB ) - added by Sebastian Noack 12 years ago.

Download all attachments as: .zip

Change History (3)

comment:1 by Matt Austin, 12 years ago

Resolution: worksforme
Status: newclosed

I was unable to reproduce this issue - for me the form correctly returned as invalid, with an error: 'Animal with this Type and Name already exists.'. Closing as 'works for me'. Also, the patch doesn't contain tests to verify the issue encountered was resolved.

Note: See TracTickets for help on using tickets.
Back to Top