Reputation: 6248
I have a ModelForm
that has an extra field that is a custom widget. I can add an extra field with a widget and pass arbitrary key values to it when constructing the widget. I'm also able to access model data within the ModelForm
in the __init__
function.
My problem lies in that adding an extra field in the ModelForm
requires doing so outside the __init__
function while accessing model data is only possible from within the __init__
function.
class SomeForm(forms.ModelForm):
title = None
def __init__(self, *args, **kwargs):
some_data = kwargs['instance'].some_data
# ^ Here I can access model data.
super(SomeForm, self).__init__(*args, **kwargs)
self.fields['some_extra_field'] = forms.CharField(widget= SomWidget())
# ^ This is where I would pass model data, but this does not add the field.
class Meta:
model = Page
fields = "__all__"
some_extra_field = forms.CharField(widget= SomeWidget())
# ^ I can add a field here, but there's no way to pass some_data to it.
I've also tried setting self.some_data
in __init__
, but it's still not accessible when I try to use self.some_data
when setting some_extra_field
at then end of the class.
How should pass model data to a widget in a ModelForm
?
Upvotes: 1
Views: 1956
Reputation: 37319
If I'm following what you need correctly, you can do this simply by editing or reassigning the widget in __init__
. Something like:
class SomeForm(forms.ModelForm):
title = None
def __init__(self, *args, **kwargs):
some_data = kwargs['instance'].some_data
super(SomeForm, self).__init__(*args, **kwargs)
# Pass whatever data you want to the widget constructor here
self.fields['some_extra_field'].widget = SomWidget(foo=...))
# or possibly (depending on what you're doing)
self.fields['some_extra_field'].widget.foo = ...
Upvotes: 2