Opened 13 years ago

Last modified 13 years ago

#15326 closed

ModelForm doesn't do unique checks if any of the fields is exluded — at Initial Version

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

Description

If a model exists with unique_together fields, and a form doesn't display all the fields in the unique_together (at least one of them is excluded) the entire condition is ignored in the code. This is the wrong behavior, only if ALL the fields are excluded then the test should be ignore.

Use case:

House (class H) has Windows (class W) with different colors. A house has different colors for different windows, and a person can change the qualities of the window as long as they don't change the color to an existing one:

So:

class H(models.Model):

....

Class W(models.Model):

color:Models.IntegerField()
house:Models.ForeignKey(H)
..... # other qualities of the window

class Meta:

unique_together = (("color", "house"),)

And the form:

class ChangeWindowForm(ModelForm):

class Meta:

model = W
fields = ('color', .... # other qualities)

in this scenario, a form validation would pass if a H,C with the same values exist.

The line that is the problem is in django.db.models.base.py, in def _get_unique_checks(self, exclude=None):

if name in exclude:

break

a possible change:
if any(check[i:i + len(exclude)] == exclude for i in range(len(check) - len(exclude) + 1)):

break

Change History (0)

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