4👍
✅
Just override the ModelForm
being used:
class ChartAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ChartAdminForm, self).__init__(*args, **kwargs)
if self.instance.module_id:
self.fields['parent'].queryset = self.fields['parent'].queryset.filter(module=self.instance.module)
class ChartAdmin(admin.ModelAdmin):
form = ChartAdminForm
...
2👍
From what i’ve seen in the source code, kwargs should contain only the widget (not helping !).
One possible hack, would be to override the get_form() modeladmin method, just to set request.current_object. Then, you could use request.current_object in formfield_callback:
def get_form(self, request, obj=None, **kwargs):
request.current_object = obj
return super(ChartAdmin, self).get_form(request, obj, **kwargs)
def formfield_for_foreignkey(self, db_field, request, **kwargs):
instance = request.current_object
kwargs['queryset'] = Chart.objects.filter(module=instance.module)
return super(ChartAdmin, self).formfield_for_foreignkey(self, db_field, request, **kwargs)
👤jpic
- [Django]-Saving post from tweepy to django model in a good way
- [Django]-Using session key of Django session as foreign key
- [Django]-Django-REST or Firebase?
- [Django]-Using different templates with django form wizard
Source:stackexchange.com