Opened 10 years ago

Closed 10 years ago

#23549 closed Bug (invalid)

Model form's model_to_dict using value_from_object instead of to_python

Reported by: mwaterfall Owned by: nobody
Component: Forms Version: 1.7
Severity: Normal Keywords: form, modelform, field
Cc: M. Shafiq Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Background: I'm using a JSONField model field to store a list of strings in a field, and I'm trying to create a model form with a series of checkboxes that allows me to multiple select zero or more of these string options using TypedMultipleChoiceField and CheckboxSelectMultiple.

Issue: When the form is rendered, the checkboxes that should be checked aren't checked. When saving the form, the checked values are correctly saved and serialised by the field.

Cause:

The reason the checkboxes aren't getting checked is down to the function model_to_dict, that converts a model instance to a dict ready to populate a ModelForm. The value is retrieved from instance fields using value_from_object. Why is to_python not used?

The JSONField is following the guidelines to create a custom model field, overriding the to_python to deserialise the raw value from the DB and return a python object. This model_to_dict is bypassing this, not allowing custom fields to deserialise values before they are used to populate a form.

Hence the form is receiving the JSON string as opposed to the deserialised list, and causing things to be rendered incorrectly.

Here's the line in question: https://github.com/django/django/blob/1.7/django/forms/models.py#L151

Change History (2)

comment:1 by M. Shafiq, 10 years ago

Cc: M. Shafiq added

comment:2 by Tim Graham, 10 years ago

Resolution: invalid
Status: newclosed

In the case of ModelChoiceField, to_python() might return a model class while value_from_object() returns the value's pk such as an integer or string. To learn more, make the change you suggest and run Django's test suite and see what fails.

As it isn't evident there is a bug in Django, please see TicketClosingReasons/UseSupportChannels for ways to get help. Please reopen if you can provide more details that suggests this is indeed a bug in Django and not in the custom field. Thanks.

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