#35367: Multi-field constraint are not correctly handled when a form has one field
marked as read-only
--------------------------------------+------------------------
Reporter: David | Owner: nobody
Type: Bug | Status: new
Component: Forms | Version: 4.2
Severity: Normal | Keywords:
Triage Stage: Unreviewed | Has patch: 0
Needs documentation: 0 | Needs tests: 0
Patch needs improvement: 0 | Easy pickings: 0
UI/UX: 0 |
--------------------------------------+------------------------
When a model defines a constraint which relates two or more fields and one
of those field is excluded from the related model form the validation
provide a false positive and then the form tries to store an invalid
record on the database, raising an `IntegrityError`.
Here is a code sample which reflects the situation
{{{#!python
# models.py
from django.db import models
from django.forms import modelform_factory
class MyModel(models.Model):
field_1 = models.IntegerField(null=True)
field_2 = models.IntegerField()
class Meta:
constraints = [
models.CheckConstraint(
name="mycheck",
check=models.Q(field_1__lt=models.F("field_2")) |
models.Q(field_1__isnull=True),
)
]
# this is like it would be done in admin if 'field_1' is set a readonly
Form = modelform_factory(MyModel, fields=['field_2'], exclude=['field_1'])
# this is ok for validation: 10 < 20
instance = MyModel(field_1=10, field_2=20)
# this does not respect the constraint: 10 > 5
form_instance = Form({'field_2': 5}, instance=instance)
form.is_valid()
# > True
form.save()
# > IntegrityError
}}}
This is somehow similar and related to #12627
--
Ticket URL: <
https://code.djangoproject.com/ticket/35367>
Django <
https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.