Code

#21045 closed Bug (invalid)

BoundField.value doesn't use to_python

Reported by: Elvard Owned by: nobody
Component: Forms Version: 1.5
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

The problem occures when using data from POST in bound form:

class CustomForm(forms.Form):
    field = forms.IntegerField(initial=42)

form = CustomForm()
print(type(form['field'].value()))  # int

form = CustomForm({'field': '42'})
print(type(form['field'].value()))  # str

form['field'] is IntegerField, but it returns string, when you pass data from POST/GET (which are usually strings). It even returns string, when you pass initial='42' (which is odd also). The problem is with FKs in ModelForm: the value in unbound form is int (from database), but in bound form it's string (from POST).

I've checked source code and BoundField.value uses Field.prepare_value, which is undocumented and (except for DateTimeField) it just returns original value.

I would expect, that value is always data type defined by Field, which is done in to_python method.

Questions are:

1) Is it bug or feature?
2) Should I use to_python instead, when I want "consistent" type of field value?
3) What's the meaning of prepare_value?

Attachments (0)

Change History (3)

comment:1 Changed 10 months ago by timo

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

I don't think Django provides any guarantees regarding the field value types before the form is validated; for example, by calling is_valid().

comment:2 Changed 10 months ago by jcatalan

As far as I understand from the value method doc this method its meant to return the initially provided value, so if it was a string in the GET/POST dict, I guess it's ok if value returns a string. Or am I missing something.

If it's ok, maybe we should close this one as wontfix?

comment:3 Changed 10 months ago by timo

  • Resolution set to invalid
  • Status changed from new to closed

Yes, I don't think there's a bug here.

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.