Opened 3 years ago

Closed 3 years ago

#32937 closed Uncategorized (duplicate)

Form.get_initial_for_field() can return different values if called more than once

Reported by: Chris Jerdonek Owned by: nobody
Component: Forms Version: dev
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

Currently, Form.get_initial_for_field() is documented as a way to retrieve the initial data for a form field. However, it has the problem that it doesn't cache its return values, like BoundField.initial does, which can lead to buggy behavior e.g. in the case of callables that return different values each time.

One way to fix this would be for get_initial_for_field() to get its value from BoundField when it needs to fall back to the field, which can then cache it (similar to how BoundField.initial caches its return value). The downside of this is that it adds another layer of indirection, as BoundField.initial is already going to Form.get_initial_for_field() for its value. Another option might be to deprecate get_initial_for_field(), as I'm not sure if it provides any benefit that an API on BoundField couldn't better provide.

See also #32933.

Change History (3)

comment:1 by Carlton Gibson, 3 years ago

Hey Chris.

Given #32933 — pointing users to BoundField.initial, would you object to just documenting this?

We could add a paragraph in https://docs.djangoproject.com/en/3.2/ref/forms/api/#dynamic-initial-values saying _Why_ BoundField.initial is preferred: simpler interface, and caches values, which matters for callables, like now().

What do you think? I'm not sure we get much benefit adding yet more code to this one… 🤔

comment:2 by Chris Jerdonek, 3 years ago

Thanks, Carlton. Yes, something like that would be good and was along the lines of what I was thinking. I wasn't sure which direction you'd want to go until filing the ticket. So maybe this issue can be closed, and I can add a comment to the doc ticket linking to this.

comment:3 by Carlton Gibson, 3 years ago

Resolution: duplicate
Status: newclosed

Agreed. Thanks.

Duplicate of #32933

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