Opened 14 years ago

Closed 14 years ago

Last modified 13 years ago

#15326 closed (duplicate)

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

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 (last modified by Karen Tracey)

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 (2)

comment:1 by Lior Sion, 14 years ago

Cc: Lior Sion added

comment:2 by Karen Tracey, 14 years ago

Description: modified (diff)
Resolution: duplicate
Status: newclosed

Fixed formatting. Please use WikiFormatting and preview before posting.

This is the same problem as #13091, I believe, so closing as a dup of that one.

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