django-filter with django autocomplete light

六眼飞鱼酱① 提交于 2019-12-03 09:09:30

I'm not very familiar with DAL, but I contribute to django-filter and have a decent understanding of its internals. A few notes:

  • The filter_class in your filter_overrides should be a filter, not a widget. You can provide additional arguments (such as the widget) through the extra key, as seen here. Any parameter that does not belong to the filter is automatically passed to the underlying form field.
  • Using an override isn't the right approach anyway, as the widget needs a field-specific endpoint to perform autocompletion. Since the endpoint is field-specific, it's not applicable to all ForeignKeys.
  • django-filter uses regular Forms, not ModelForms, so an appropriate Meta inner class would not be constructed. FutureModelForm doesn't seem to provide autocomplete functionality anyway - it seems irrelevant?

Your factory will have to generate your autocomplete filters manually - something like the following:

def dal_field(field_name, url):
    return filters.ModelChoiceFilter(
        name=field_name,
        widget=autocomplete.ModelSelect2(url=url),
    )

def dal_filterset_factory(model, fields, dal_fields):
    attrs = {field: dal_field(field, url) for field, url in dal_fields.items()}
    attrs['Meta'] = type(str('Meta'), (object,), {'model': model,'fields': fields})

    filterset = type(str('%sFilterSet' % model._meta.object_name),
                     (FilterSet,), attrs)
    return filterset

# Usage:

# mapping of {field names: autocomplete endpoints}.
dal_fields = {'birth_country': 'country-autocomplete'}
fields = ['list', 'or', 'dict', 'of', 'other', 'fields']
SomeModelFilterSet = dal_filterset_factory(SomeModel, fields, dal_fields)

The fields in attrs use the declarative API. More info in the docs.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!