Populate `initial_data` of forms from model instance
|Reported by:||Christopher Lenz <cmlenz@…>||Owned by:||nobody|
|Cc:||akaihol+django@…||Triage Stage:||Design decision needed|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||yes||Patch needs improvement:||no|
Okay, I've looked for ways to populate the initial data of a form created by newforms.form_for_model() from an existing model instance.
I can't use form_for_instance because I want to add custom clean_ hooks, so the pattern I'm using looks like this:
class MyForm(forms.form_for_model(MyModel, fields=['foo', 'bar'])): def clean_foo(self): # ...
Now when I create a form instance, I can't see a clean way to populate the inital data of the form properly. I've tried the following, but it doesn't work for relations, plus it's really ugly:
form = MyForm(initial=myinstance.__dict__)
The only option seems to be overriding the __init__(), but that's a pain as I'd have to do that for every form. I guess I could probably work around this somehow, but I can't believe this isn't a problem others are seeing, so I'm attaching a patch that overrides the default __init__() to take the instance as first (optional) argument, which makes a lot of sense to me. The code would then look like this:
form = MyForm(myinstance)
Kindly asking for review/comments. Thanks.
Change History (21)
comment:1 follow-up: ↓ 2 Changed 8 years ago by SmileyChris
- Needs documentation unset
- Needs tests set
- Patch needs improvement unset
- Triage Stage changed from Unreviewed to Design decision needed
comment:2 in reply to: ↑ 1 ; follow-up: ↓ 3 Changed 8 years ago by Christopher Lenz <cmlenz@…>
- Summary changed from Override constructor of `form_for_model` class to take model instance to Populate `initial_data` of forms from model instance