Giter VIP home page Giter VIP logo

django-admin-autocomplete-list-filter's Introduction

Python Python Python Python Django Code style: black PyPI version Downloads

django-admin-autocomplete-list-filter

Ajax autocomplete list filter helper for Django admin. Uses Django’s built-in autocomplete widget! No extra package or install required!

After

Update

Dropped support for Django 2 family. Works with Django 3 or higher!. master branch is renamed to main... You can fix your existing clones via;

git branch -m master main
git fetch origin
git branch -u origin/main main
git remote set-head origin -a

Installation and Usage

$ pip install django-admin-autocomplete-list-filter

Add djaa_list_filter to INSTALLED_APPS in your settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'djaa_list_filter',           
]

Now, let’s look at this example model:

# models.py

from django.conf import settings
from django.db import models


class Post(models.Model):
    category = models.ForeignKey(to='Category', on_delete=models.CASCADE, related_name='posts')
    author = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='posts')
    title = models.CharField(max_length=255)
    body = models.TextField()
    tags = models.ManyToManyField(to='Tag', blank=True)

    def __str__(self):
        return self.title


class Category(models.Model):
    title = models.CharField(max_length=255)

    def __str__(self):
        return self.title


class Tag(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

We have 2 ForeignKey fields and one ManyToManyField to enable autocomplete list filter feature on admin. All you need is to inherit from AjaxAutocompleteListFilterModelAdmin which inherits from Django’s admin.ModelAdmin.

Now we have an extra ModelAdmin method: autocomplete_list_filter. Uses Django Admin’s search_fields logic. You need to enable search_fields in the related ModelAdmin. To enable completion on Category relation, CategoryAdmin should have search_fields that’s it!

from django.contrib import admin

from djaa_list_filter.admin import (
    AjaxAutocompleteListFilterModelAdmin,
)

from .models import Category, Post, Tag


@admin.register(Post)
class PostAdmin(AjaxAutocompleteListFilterModelAdmin):
    list_display = ('__str__', 'author', 'show_tags')
    autocomplete_list_filter = ('category', 'author', 'tags')

    def show_tags(self, obj):
        return ' , '.join(obj.tags.values_list('name', flat=True))


@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    search_fields = ['title']
    ordering = ['title']


@admin.register(Tag)
class TagAdmin(admin.ModelAdmin):
    search_fields = ['name']
    ordering = ['name']

Development

You are very welcome to contribute, fix bugs or improve this project. We hope to help people who needs this feature. We made this package for our company project. Good appetite for all the Django developers out there!

License

This project is licensed under MIT


Contributor(s)


Contribute

All PR’s are welcome!

  1. fork (https://github.com/demiroren-teknoloji/django-admin-autocomplete-list-filter/fork)
  2. Create your branch (git checkout -b my-features)
  3. commit yours (git commit -am 'added killer options')
  4. push your branch (git push origin my-features)
  5. Than create a new Pull Request!

TODO

  • Add unit tests
  • Improve JavaScript code :)

Change Log

2021-08-17

2019-10-25

  • Remove f-string for older Python versions, will change this on 1.0.0 version

2019-10-19

  • Bump version: 0.1.2
  • Add Python 3.5 supports, thanks to Peter Farrel
  • Add animated gif :)
  • Add future warning for f-strings

2019-10-11

  • Add ManyToManyField support
  • Initial release

2019-10-07

  • Init repo...

django-admin-autocomplete-list-filter's People

Contributors

guglielmo avatar maestrofjp avatar salomvary avatar vigo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-admin-autocomplete-list-filter's Issues

Upstream django commit broke functionality

Hi,
I wanted to report that after this commit on django main repository the autocomplete list filter widget no longer works.

On first analysis, when instantiating the AjaxAutocompleteSelectWidget object, its __init__ function calls super().__init__ passing a "rel" keyword argument which is no longer accepted by django AutocompleteMixin init function, raising the following exception:

TypeError: __init__() got an unexpected keyword argument 'rel'

The offending change is in django/contrib/admin/widgets.py file at line 385.

I haven't delved into it yet, but judging from the commit message, it seems that fix #29138 ("Allowed autocomplete fields to target a custom to_field rather than the PK") is directly related to the choice of replacing the "rel" kwarg with the "field" kwarg, breaking the interface.

Add support for autocomplete_fields that span foreign key relationships

Currently this list filter fails to account for fields that span across foreignkey relationships, it will correctly parse the field as a ForeignKey but will attempt to find it on the Model that belongs to the current ModelAdmin, instead of traversing across models.

I can add a more concrete example if necessary.

Multiple autocomplete filters do not seem to work

I'm using django 3, with the changes proposed in #6, and whenever multiple filters with autocomplete are present, only the last one seems to be working correctly.

The others do not react at all and the select menus are empty.

staticfiles error

django admin raises exception 'staticfiles' is not a registered tag library, because the staticfiles and admin_static template tag libraries are removed in 3.0.
There is a PR #3
that is not accepted

Slowness due to loading all options

I was investigating an admin list page slowness and found out that all options are queried and loaded into memory, which, in case of a large number of options (usually the motivation itself for using autocomplate) makes the page load very slowly.

Stack trace leading to the problem looks like this:

django/contrib/admin/options.py in wrapper(686)
  return self.admin_site.admin_view(view)(*args, **kwargs)

django/views/decorators/cache.py in _wrapped_view_func(62)
  response = view_func(request, *args, **kwargs)

django/contrib/admin/sites.py in inner(242)
  return view(request, *args, **kwargs)

django/contrib/admin/options.py in changelist_view(1931)
  cl = self.get_changelist_instance(request)

django/contrib/admin/options.py in get_changelist_instance(834)
  return ChangeList(

django/contrib/admin/views/main.py in __init__(122)
  self.queryset = self.get_queryset(request)

django/contrib/admin/views/main.py in get_queryset(503)
  ) = self.get_filters(request)

django/contrib/admin/views/main.py in get_filters(182)
  spec = field_list_filter_class(

djaa_list_filter/admin.py in __init__(53)
  super().__init__(field, request, params, model, model_admin, field_path)

django/contrib/admin/filters.py in __init__(188)
  self.lookup_choices = self.field_choices(field, request, model_admin)

django/contrib/admin/filters.py in field_choices(225)
  return field.get_choices(include_blank=False, ordering=ordering)

Using Django 4.1.1.

Getting ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation' on Django>=4.X

Version: django-admin-autocomplete-list-filter = "1.0.1"

Stacktrace

  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 848, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File ".venv/lib/python3.8/site-packages/djaa_list_filter/admin.py", line 13, in <module>
    from django.utils.translation import ugettext_lazy as _
ImportError: cannot import name 'ugettext_lazy' from 'django.utils.translation' (.venv/lib/python3.8/site-packages/django/utils/translation/__init__.py)

django.utils.translation.ugettext(), ugettext_lazy(), ugettext_noop(), ungettext(), and ungettext_lazy() are removed in Django 4.0
https://docs.djangoproject.com/en/4.0/releases/4.0/#features-removed-in-4-0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.