[Django]-ForeignKeyAutocompleteAdmin

3đź‘Ť

âś…

as per my update, adding a ForeignKeyAutocompleteAdmin for the other side of the relation created the missing urls and the functionality seems to work

👤Verbal_Kint

0đź‘Ť

@Verbal_Kint I think I may have figured the same issue as yours.

I have a InlineModelAdmin “TaskInline” for model Task, a field “SCRIPT” of it is a foreign-key to model TestScript (managed by “TestAdmin”).

After I made sure the related model’s ModelAdmin (here for me it’s TestAdmin) inherits ForeignKeyAutoCompleteAdmin instead of admin.ModelAdmin, then made sure TestAdmin had an method wrap as below:

class TestAdmin(ForeignKeyAutocompleteAdmin):

    ForeignKeyAutocompleteAdmin.model = TestScript

    def wrap(self, view):
        def wrapper(*args, **kwargs):
            return self.admin_site.admin_view(view)(*args, **kwargs)
        wrapper.model_admin = self
        return update_wrapper(wrapper, view)

    def get_urls(self):
        info = self.model._meta.app_label, self.model._meta.model_name

        urlpatterns = super(TestAdmin, self).get_urls()
        urlpatterns.insert(0, url(r'^(.+)/run/', self.wrap(self.run_view), name='%s_%s_run' % info))
        urlpatterns.insert(0, url(r'^add/$', self.wrap(self.add_view), name='%s_%s_add' % info))
        urlpatterns.insert(0, url(r'^add_to_template_mission/$', self.wrap(self.add_to_template_mission_view), name='%s_%s_add_to_template_mission' % info))
        urlpatterns.insert(0, url(r'^add_to_mission/$', self.wrap(self.add_to_mission_view), name='%s_%s_add_to_mission' % info))
        urlpatterns.insert(0, url(r'^$', self.wrap(self.changelist_view), name='%s_%s_changelist' % info))

        return urlpatterns

class TaskInline(ForeignKeyAutocompleteTabularInline):

    model = Task

    related_search_fields = {
        'SCRIPT': ('FILENAME', 'FILE_PATH', 'FILE_CONTENT', ),
    }

And, don’t forget to have

urlpatterns = super(TestAdmin, self).get_urls()

in get_urls() inside TestAdmin

Then, everything got working fine.

Maybe there is a better way, but this did solve my problem. Hope this can help.

👤Alex Ma

Leave a comment