问题
What should I put in rel and admin site? This is the field in my form:
tutor_temporal = forms.ModelChoiceField(queryset=Tutor_temporal.objects.all(),label='Tutor No Registrado', required=False,
widget=RelatedFieldWidgetWrapper(widget=forms.Select(attrs={'class': 'input is-small is-rounded '}),rel=Tutor_temporal._meta.get_field('id').rel,admin_site= admin_site))
The problem is that when I try that, throws this AttributeError: 'AutoField' object has no attribute 'rel', because apparently is deprecated.
回答1:
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,
)
)
回答2:
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,
来源:https://stackoverflow.com/questions/64489803/how-to-use-relatedfieldwidgetwrapper-in-django-3