1👍
I’ve currently faced similiar problem and there is a way to use widget for two fields.
I’m using version 1.4 and haven’t tried in any other.
In your view, you probably have something like this:
form = TestModelForm(instance=instance)
where instance
is object from your database you want to edit.
Let’s see what Django is doing when it creates your form
# django/forms/models.py
class BaseModelForm(BaseForm):
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, error_class=ErrorList, label_suffix=':',
empty_permitted=False, instance=None):
...
if instance is None:
...
else:
self.instance = instance
object_data = model_to_dict(instance, opts.fields, opts.exclude)
# if initial was provided, it should override the values from instance
if initial is not None:
object_data.update(initial)
...
super(BaseModelForm, self).__init__(data, files, auto_id, prefix,
object_data, error_class,
label_suffix, empty_permitted)
then, when form is rendered, BoundField
class uses this object_data
to assign initial value to the widget.
Therefore all you need to do is provide initial
in your form constructor.
class TestModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
if 'instance' in kwargs:
initial = dictionary with initial values
initial.update(kwargs['initial'] or {})
...
super(TestModelForm, self).__init__(initial=initial, *args, **kwargs)
Also remember to add your field to your forms fields
list.
That way you don’t have two unused hidden widgets, no need to use javascript and imo, code is more explanatory.
Source:stackexchange.com