Open ercpe opened 1 year ago
Interesting, let's see what a pull request looks like with this
I finally got around to create a Merge Request with the changes we made to a subclass in our project: https://github.com/yourlabs/django-autocomplete-light/pull/1358
Today we hit a nasty bug with dal.ModelSelect2 fields where an autocomplete field would receive forwards from a different class which uses the same base class.
We traced the error back to the
WidgetMixin
where we found that it does not implement__deepcopy__
properly and thus would copy a reference to theforward
list between instances of the widget.Background: When Django creates a
Form
instance from a form class, the fields and widgets are copied instead of instantiated. This means that every field/widget must implement__deepcopy__
properly to create clones of any references it holds.Example to reproduce:
In this example, the reference to the
forward
list is copied once when theForm1
instance is created and again when theForm2
instance is created. Thus, thewidget.forward.append
call inForm2
adds the forward to the very same list and now affects every instance of the form (in the same python process).To fix the issue:
Implement
__deepcopy__
inWidgetMixin
andcopy()
theforward
, e.g.See
django.forms.widgets.Widget.__deepcopy__
anddjango.forms.widgets.ChoiceWidget.__deepcopy__
for an example in Django itself where mutable types are copied when the Widget is cloned.Also, the
forward
argument to theWidgetMixin.__init__
should also be copied as it has the same issue.