Opened 7 weeks ago

Last modified 7 weeks ago

#35640 closed Bug

ModelMultipleChoiceField fail when the foreignkey remote model is a child class of anohter model — at Version 1

Reported by: Omar BENHAMID Owned by:
Component: Forms Version: 3.2
Severity: Normal Keywords:
Cc: Omar BENHAMID 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 Omar BENHAMID)

The issue

When a child model is used as a foreign key, forms with ModelMultipleChoiceField (not setting to_field_name) will systematically fail to validate submited values.

Reproduction

models.py

class A(models.Model):
      pass

class B(A):
      pass

class C(models.Model):
      fkfield = models.ForeignKey(B, on_delete=models.CASCADE)

Create form with MultipleChoiceField of the foreignkey fkfield and it will systematically fail to validate.

Reason

ModelMultipleChoiceField uses value.pk in prepare_value to generate choices but uses "to_field_name" in _check_data for validation.
default to_field_name is by default related_field.field_name which is "<parent>_ptr" in the case of inheriance child models, which points to the parent itself (not the pk).

ModelMultipleChoiceField fail when the foreignkey remote model is a child class of anohter model

Workaround

Use to_field_name = 'pk' when ModelMultipleChoiceField is created.

Proposed fix

Use PK in validation like in generation of choices.

Spotted in 3.2

Change History (1)

comment:1 by Omar BENHAMID, 7 weeks ago

Description: modified (diff)
Version: 5.13.2
Note: See TracTickets for help on using tickets.
Back to Top