6👍
✅
from django.contrib.admin import site as admin_site
def __init__(self, *args, **kwargs):
super(TesisForm, self).__init__(*args, **kwargs)
self.fields['tutor_temporal'].widget = (
RelatedFieldWidgetWrapper(
self.fields['tutor_temporal'].widget,
self.instance._meta.get_field('tutor_temporal').remote_field,
admin_site,
)
)
1👍
I was stuck in a scenario which I overrode some fields in a ModelForm :
class VariationsForm(forms.ModelForm):
""" Variations admin form """
color = forms.ModelChoiceField(
required=True,
queryset=mdl.Color.objects.filter(
is_active=True,),
label='Color',
empty_label="-----",
)
size = forms.ModelChoiceField(
required=True,
queryset=mdl.Size.objects.filter(
is_active=True,),
label='Talla / Medida',
empty_label="-----"
)
And the "add action button" never was displayed, so I started to search on the net about how to enable this feature and I found out that usually all generated fields are wrapped by the class: RelatedFieldWidgetWrapper
https://github.com/django/django/blob/master/django/contrib/admin/widgets.py#L224,
As a part of the solution as previously shared above, I applied the wrapper to the fields that I early overrode :
from django.contrib.admin import (
widgets,
site as admin_site
)
.....
.....
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# personalize choices
for field in ["color", "size"]:
self.fields[field].widget = widgets.RelatedFieldWidgetWrapper(
self.fields[field].widget,
self.instance._meta.get_field(field).remote_field,
admin_site
)
finally :
Best regards,
- [Django]-Using reverse relationships with django-rest-framework's serializer
- [Django]-Django clean-up code
Source:stackexchange.com