Opened 9 years ago

Closed 9 years ago

#26200 closed Bug (duplicate)

Integrity constraint violations when ForeignKey field is not included on the ModelForm

Reported by: Gary Reynolds Owned by: nobody
Component: Forms Version: 1.8
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

Using the Author and Book example from the model_forms tests, Book has a unique_together constraint on ('title', 'author').

If we have a ModelForm which only includes the 'title' field, and use that to update an instance in such a way that it would cause a violation of this constraint, the existing behaviour is to validate the form and allow an update.

Unfortunately this results in an IntegrityError.

There is a work around - it's possible to manually catch this in your own clean methods on the model or form.

Change History (3)

comment:1 by Gary Reynolds, 9 years ago

On further searching of the developers mailing list, this might be a partial of #13091?

I hadn't experienced the behaviour on non-FK fields, but it would not be too difficult remove the if isinstance(self.instance._meta.get_field(field_name), models.ForeignKey) check.

Unfortunately makes model_forms.tests.ModelFormBaseTest.test_exclude_and_validation fail, and the comment in that test notes "This is for backwards compatibility." which is worrying since #13091 is 6 years old!

comment:2 by Tim Graham, 9 years ago

Yes, I think we need some solution as described in #13091. I believe your proposed patch breaks the case where a developer adds a value for a field in the unique_together to the model after form validation. In that case we'll now get a validation error with no chance to correct it.

I think we can mark this ticket as a duplicate of that one, but let me know if you feel otherwise.

comment:3 by Gary Reynolds, 9 years ago

Resolution: duplicate
Status: newclosed
Note: See TracTickets for help on using tickets.
Back to Top